// SPDX-License-Identifier: GPL-2.0-only /* * kernel/sched/core.c * * Core kernel CPU scheduler code * * Copyright (C) 1991-2002 Linus Torvalds * Copyright (C) 1998-2024 Ingo Molnar, Red Hat */ #include <linux/highmem.h> #include <linux/hrtimer_api.h> #include <linux/ktime_api.h> #include <linux/sched/signal.h> #include <linux/syscalls_api.h> #include <linux/debug_locks.h> #include <linux/prefetch.h> #include <linux/capability.h> #include <linux/pgtable_api.h> #include <linux/wait_bit.h> #include <linux/jiffies.h> #include <linux/spinlock_api.h> #include <linux/cpumask_api.h> #include <linux/lockdep_api.h> #include <linux/hardirq.h> #include <linux/softirq.h> #include <linux/refcount_api.h> #include <linux/topology.h> #include <linux/sched/clock.h> #include <linux/sched/cond_resched.h> #include <linux/sched/cputime.h> #include <linux/sched/debug.h> #include <linux/sched/hotplug.h> #include <linux/sched/init.h> #include <linux/sched/isolation.h> #include <linux/sched/loadavg.h> #include <linux/sched/mm.h> #include <linux/sched/nohz.h> #include <linux/sched/rseq_api.h> #include <linux/sched/rt.h> #include <linux/blkdev.h> #include <linux/context_tracking.h> #include <linux/cpuset.h> #include <linux/delayacct.h> #include <linux/init_task.h> #include <linux/interrupt.h> #include <linux/ioprio.h> #include <linux/kallsyms.h> #include <linux/kcov.h> #include <linux/kprobes.h> #include <linux/llist_api.h> #include <linux/mmu_context.h> #include <linux/mmzone.h> #include <linux/mutex_api.h> #include <linux/nmi.h> #include <linux/nospec.h> #include <linux/perf_event_api.h> #include <linux/profile.h> #include <linux/psi.h> #include <linux/rcuwait_api.h> #include <linux/rseq.h> #include <linux/sched/wake_q.h> #include <linux/scs.h> #include <linux/slab.h> #include <linux/syscalls.h> #include <linux/vtime.h> #include <linux/wait_api.h> #include <linux/workqueue_api.h> #ifdef CONFIG_PREEMPT_DYNAMIC # ifdef CONFIG_GENERIC_ENTRY # include <linux/entry-common.h> # endif #endif #include <uapi/linux/sched/types.h> #include <asm/irq_regs.h> #include <asm/switch_to.h> #include <asm/tlb.h> #define CREATE_TRACE_POINTS #include <linux/sched/rseq_api.h> #include <trace/events/sched.h> #include <trace/events/ipi.h> #undef CREATE_TRACE_POINTS #include "sched.h" #include "stats.h" #include "autogroup.h" #include "pelt.h" #include "smp.h" #include "stats.h" #include "../workqueue_internal.h" #include "../../io_uring/io-wq.h" #include "../smpboot.h" EXPORT_TRACEPOINT_SYMBOL_GPL(…); EXPORT_TRACEPOINT_SYMBOL_GPL(…); /* * Export tracepoints that act as a bare tracehook (ie: have no trace event * associated with them) to allow external modules to probe them. */ EXPORT_TRACEPOINT_SYMBOL_GPL(…); EXPORT_TRACEPOINT_SYMBOL_GPL(…); EXPORT_TRACEPOINT_SYMBOL_GPL(…); EXPORT_TRACEPOINT_SYMBOL_GPL(…); EXPORT_TRACEPOINT_SYMBOL_GPL(…); EXPORT_TRACEPOINT_SYMBOL_GPL(…); EXPORT_TRACEPOINT_SYMBOL_GPL(…); EXPORT_TRACEPOINT_SYMBOL_GPL(…); EXPORT_TRACEPOINT_SYMBOL_GPL(…); EXPORT_TRACEPOINT_SYMBOL_GPL(…); EXPORT_TRACEPOINT_SYMBOL_GPL(…); EXPORT_TRACEPOINT_SYMBOL_GPL(…); DEFINE_PER_CPU_SHARED_ALIGNED(struct rq, runqueues); #ifdef CONFIG_SCHED_DEBUG /* * Debugging: various feature bits * * If SCHED_DEBUG is disabled, each compilation unit has its own copy of * sysctl_sched_features, defined in sched.h, to allow constants propagation * at compile time and compiler optimization based on features default. */ #define SCHED_FEAT … const_debug unsigned int sysctl_sched_features = …; #undef SCHED_FEAT /* * Print a warning if need_resched is set for the given duration (if * LATENCY_WARN is enabled). * * If sysctl_resched_latency_warn_once is set, only one warning will be shown * per boot. */ __read_mostly int sysctl_resched_latency_warn_ms = …; __read_mostly int sysctl_resched_latency_warn_once = …; #endif /* CONFIG_SCHED_DEBUG */ /* * Number of tasks to iterate in a single balance run. * Limited because this is done with IRQs disabled. */ const_debug unsigned int sysctl_sched_nr_migrate = …; __read_mostly int scheduler_running; #ifdef CONFIG_SCHED_CORE DEFINE_STATIC_KEY_FALSE(__sched_core_enabled); /* kernel prio, less is more */ static inline int __task_prio(const struct task_struct *p) { … } /* * l(a,b) * le(a,b) := !l(b,a) * g(a,b) := l(b,a) * ge(a,b) := !l(a,b) */ /* real prio, less is less */ static inline bool prio_less(const struct task_struct *a, const struct task_struct *b, bool in_fi) { … } static inline bool __sched_core_less(const struct task_struct *a, const struct task_struct *b) { … } #define __node_2_sc(node) … static inline bool rb_sched_core_less(struct rb_node *a, const struct rb_node *b) { … } static inline int rb_sched_core_cmp(const void *key, const struct rb_node *node) { … } void sched_core_enqueue(struct rq *rq, struct task_struct *p) { … } void sched_core_dequeue(struct rq *rq, struct task_struct *p, int flags) { … } static int sched_task_is_throttled(struct task_struct *p, int cpu) { … } static struct task_struct *sched_core_next(struct task_struct *p, unsigned long cookie) { … } /* * Find left-most (aka, highest priority) and unthrottled task matching @cookie. * If no suitable task is found, NULL will be returned. */ static struct task_struct *sched_core_find(struct rq *rq, unsigned long cookie) { … } /* * Magic required such that: * * raw_spin_rq_lock(rq); * ... * raw_spin_rq_unlock(rq); * * ends up locking and unlocking the _same_ lock, and all CPUs * always agree on what rq has what lock. * * XXX entirely possible to selectively enable cores, don't bother for now. */ static DEFINE_MUTEX(sched_core_mutex); static atomic_t sched_core_count; static struct cpumask sched_core_mask; static void sched_core_lock(int cpu, unsigned long *flags) { … } static void sched_core_unlock(int cpu, unsigned long *flags) { … } static void __sched_core_flip(bool enabled) { … } static void sched_core_assert_empty(void) { … } static void __sched_core_enable(void) { … } static void __sched_core_disable(void) { … } void sched_core_get(void) { … } static void __sched_core_put(struct work_struct *work) { … } void sched_core_put(void) { … } #else /* !CONFIG_SCHED_CORE */ static inline void sched_core_enqueue(struct rq *rq, struct task_struct *p) { } static inline void sched_core_dequeue(struct rq *rq, struct task_struct *p, int flags) { } #endif /* CONFIG_SCHED_CORE */ /* * Serialization rules: * * Lock order: * * p->pi_lock * rq->lock * hrtimer_cpu_base->lock (hrtimer_start() for bandwidth controls) * * rq1->lock * rq2->lock where: rq1 < rq2 * * Regular state: * * Normal scheduling state is serialized by rq->lock. __schedule() takes the * local CPU's rq->lock, it optionally removes the task from the runqueue and * always looks at the local rq data structures to find the most eligible task * to run next. * * Task enqueue is also under rq->lock, possibly taken from another CPU. * Wakeups from another LLC domain might use an IPI to transfer the enqueue to * the local CPU to avoid bouncing the runqueue state around [ see * ttwu_queue_wakelist() ] * * Task wakeup, specifically wakeups that involve migration, are horribly * complicated to avoid having to take two rq->locks. * * Special state: * * System-calls and anything external will use task_rq_lock() which acquires * both p->pi_lock and rq->lock. As a consequence the state they change is * stable while holding either lock: * * - sched_setaffinity()/ * set_cpus_allowed_ptr(): p->cpus_ptr, p->nr_cpus_allowed * - set_user_nice(): p->se.load, p->*prio * - __sched_setscheduler(): p->sched_class, p->policy, p->*prio, * p->se.load, p->rt_priority, * p->dl.dl_{runtime, deadline, period, flags, bw, density} * - sched_setnuma(): p->numa_preferred_nid * - sched_move_task(): p->sched_task_group * - uclamp_update_active() p->uclamp* * * p->state <- TASK_*: * * is changed locklessly using set_current_state(), __set_current_state() or * set_special_state(), see their respective comments, or by * try_to_wake_up(). This latter uses p->pi_lock to serialize against * concurrent self. * * p->on_rq <- { 0, 1 = TASK_ON_RQ_QUEUED, 2 = TASK_ON_RQ_MIGRATING }: * * is set by activate_task() and cleared by deactivate_task(), under * rq->lock. Non-zero indicates the task is runnable, the special * ON_RQ_MIGRATING state is used for migration without holding both * rq->locks. It indicates task_cpu() is not stable, see task_rq_lock(). * * p->on_cpu <- { 0, 1 }: * * is set by prepare_task() and cleared by finish_task() such that it will be * set before p is scheduled-in and cleared after p is scheduled-out, both * under rq->lock. Non-zero indicates the task is running on its CPU. * * [ The astute reader will observe that it is possible for two tasks on one * CPU to have ->on_cpu = 1 at the same time. ] * * task_cpu(p): is changed by set_task_cpu(), the rules are: * * - Don't call set_task_cpu() on a blocked task: * * We don't care what CPU we're not running on, this simplifies hotplug, * the CPU assignment of blocked tasks isn't required to be valid. * * - for try_to_wake_up(), called under p->pi_lock: * * This allows try_to_wake_up() to only take one rq->lock, see its comment. * * - for migration called under rq->lock: * [ see task_on_rq_migrating() in task_rq_lock() ] * * o move_queued_task() * o detach_task() * * - for migration called under double_rq_lock(): * * o __migrate_swap_task() * o push_rt_task() / pull_rt_task() * o push_dl_task() / pull_dl_task() * o dl_task_offline_migration() * */ void raw_spin_rq_lock_nested(struct rq *rq, int subclass) { … } bool raw_spin_rq_trylock(struct rq *rq) { … } void raw_spin_rq_unlock(struct rq *rq) { … } #ifdef CONFIG_SMP /* * double_rq_lock - safely lock two runqueues */ void double_rq_lock(struct rq *rq1, struct rq *rq2) { … } #endif /* * __task_rq_lock - lock the rq @p resides on. */ struct rq *__task_rq_lock(struct task_struct *p, struct rq_flags *rf) __acquires(rq->lock) { … } /* * task_rq_lock - lock p->pi_lock and lock the rq @p resides on. */ struct rq *task_rq_lock(struct task_struct *p, struct rq_flags *rf) __acquires(p->pi_lock) __acquires(rq->lock) { … } /* * RQ-clock updating methods: */ static void update_rq_clock_task(struct rq *rq, s64 delta) { … } void update_rq_clock(struct rq *rq) { … } #ifdef CONFIG_SCHED_HRTICK /* * Use HR-timers to deliver accurate preemption points. */ static void hrtick_clear(struct rq *rq) { … } /* * High-resolution timer tick. * Runs from hardirq context with interrupts disabled. */ static enum hrtimer_restart hrtick(struct hrtimer *timer) { … } #ifdef CONFIG_SMP static void __hrtick_restart(struct rq *rq) { … } /* * called from hardirq (IPI) context */ static void __hrtick_start(void *arg) { … } /* * Called to set the hrtick timer state. * * called with rq->lock held and IRQs disabled */ void hrtick_start(struct rq *rq, u64 delay) { … } #else /* * Called to set the hrtick timer state. * * called with rq->lock held and IRQs disabled */ void hrtick_start(struct rq *rq, u64 delay) { /* * Don't schedule slices shorter than 10000ns, that just * doesn't make sense. Rely on vruntime for fairness. */ delay = max_t(u64, delay, 10000LL); hrtimer_start(&rq->hrtick_timer, ns_to_ktime(delay), HRTIMER_MODE_REL_PINNED_HARD); } #endif /* CONFIG_SMP */ static void hrtick_rq_init(struct rq *rq) { … } #else /* CONFIG_SCHED_HRTICK */ static inline void hrtick_clear(struct rq *rq) { } static inline void hrtick_rq_init(struct rq *rq) { } #endif /* CONFIG_SCHED_HRTICK */ /* * try_cmpxchg based fetch_or() macro so it works for different integer types: */ #define fetch_or(ptr, mask) … #if defined(CONFIG_SMP) && defined(TIF_POLLING_NRFLAG) /* * Atomically set TIF_NEED_RESCHED and test for TIF_POLLING_NRFLAG, * this avoids any races wrt polling state changes and thereby avoids * spurious IPIs. */ static inline bool set_nr_and_not_polling(struct task_struct *p) { … } /* * Atomically set TIF_NEED_RESCHED if TIF_POLLING_NRFLAG is set. * * If this returns true, then the idle task promises to call * sched_ttwu_pending() and reschedule soon. */ static bool set_nr_if_polling(struct task_struct *p) { … } #else static inline bool set_nr_and_not_polling(struct task_struct *p) { set_tsk_need_resched(p); return true; } #ifdef CONFIG_SMP static inline bool set_nr_if_polling(struct task_struct *p) { return false; } #endif #endif static bool __wake_q_add(struct wake_q_head *head, struct task_struct *task) { … } /** * wake_q_add() - queue a wakeup for 'later' waking. * @head: the wake_q_head to add @task to * @task: the task to queue for 'later' wakeup * * Queue a task for later wakeup, most likely by the wake_up_q() call in the * same context, _HOWEVER_ this is not guaranteed, the wakeup can come * instantly. * * This function must be used as-if it were wake_up_process(); IOW the task * must be ready to be woken at this location. */ void wake_q_add(struct wake_q_head *head, struct task_struct *task) { … } /** * wake_q_add_safe() - safely queue a wakeup for 'later' waking. * @head: the wake_q_head to add @task to * @task: the task to queue for 'later' wakeup * * Queue a task for later wakeup, most likely by the wake_up_q() call in the * same context, _HOWEVER_ this is not guaranteed, the wakeup can come * instantly. * * This function must be used as-if it were wake_up_process(); IOW the task * must be ready to be woken at this location. * * This function is essentially a task-safe equivalent to wake_q_add(). Callers * that already hold reference to @task can call the 'safe' version and trust * wake_q to do the right thing depending whether or not the @task is already * queued for wakeup. */ void wake_q_add_safe(struct wake_q_head *head, struct task_struct *task) { … } void wake_up_q(struct wake_q_head *head) { … } /* * resched_curr - mark rq's current task 'to be rescheduled now'. * * On UP this means the setting of the need_resched flag, on SMP it * might also involve a cross-CPU call to trigger the scheduler on * the target CPU. */ void resched_curr(struct rq *rq) { … } void resched_cpu(int cpu) { … } #ifdef CONFIG_SMP #ifdef CONFIG_NO_HZ_COMMON /* * In the semi idle case, use the nearest busy CPU for migrating timers * from an idle CPU. This is good for power-savings. * * We don't do similar optimization for completely idle system, as * selecting an idle CPU will add more delays to the timers than intended * (as that CPU's timer base may not be up to date wrt jiffies etc). */ int get_nohz_timer_target(void) { … } /* * When add_timer_on() enqueues a timer into the timer wheel of an * idle CPU then this timer might expire before the next timer event * which is scheduled to wake up that CPU. In case of a completely * idle system the next event might even be infinite time into the * future. wake_up_idle_cpu() ensures that the CPU is woken up and * leaves the inner idle loop so the newly added timer is taken into * account when the CPU goes back to idle and evaluates the timer * wheel for the next timer event. */ static void wake_up_idle_cpu(int cpu) { … } static bool wake_up_full_nohz_cpu(int cpu) { … } /* * Wake up the specified CPU. If the CPU is going offline, it is the * caller's responsibility to deal with the lost wakeup, for example, * by hooking into the CPU_DEAD notifier like timers and hrtimers do. */ void wake_up_nohz_cpu(int cpu) { … } static void nohz_csd_func(void *info) { … } #endif /* CONFIG_NO_HZ_COMMON */ #ifdef CONFIG_NO_HZ_FULL static inline bool __need_bw_check(struct rq *rq, struct task_struct *p) { if (rq->nr_running != 1) return false; if (p->sched_class != &fair_sched_class) return false; if (!task_on_rq_queued(p)) return false; return true; } bool sched_can_stop_tick(struct rq *rq) { int fifo_nr_running; /* Deadline tasks, even if single, need the tick */ if (rq->dl.dl_nr_running) return false; /* * If there are more than one RR tasks, we need the tick to affect the * actual RR behaviour. */ if (rq->rt.rr_nr_running) { if (rq->rt.rr_nr_running == 1) return true; else return false; } /* * If there's no RR tasks, but FIFO tasks, we can skip the tick, no * forced preemption between FIFO tasks. */ fifo_nr_running = rq->rt.rt_nr_running - rq->rt.rr_nr_running; if (fifo_nr_running) return true; /* * If there are no DL,RR/FIFO tasks, there must only be CFS tasks left; * if there's more than one we need the tick for involuntary * preemption. */ if (rq->nr_running > 1) return false; /* * If there is one task and it has CFS runtime bandwidth constraints * and it's on the cpu now we don't want to stop the tick. * This check prevents clearing the bit if a newly enqueued task here is * dequeued by migrating while the constrained task continues to run. * E.g. going from 2->1 without going through pick_next_task(). */ if (sched_feat(HZ_BW) && __need_bw_check(rq, rq->curr)) { if (cfs_task_bw_constrained(rq->curr)) return false; } return true; } #endif /* CONFIG_NO_HZ_FULL */ #endif /* CONFIG_SMP */ #if defined(CONFIG_RT_GROUP_SCHED) || (defined(CONFIG_FAIR_GROUP_SCHED) && \ (defined(CONFIG_SMP) || defined(CONFIG_CFS_BANDWIDTH))) /* * Iterate task_group tree rooted at *from, calling @down when first entering a * node and @up when leaving it for the final time. * * Caller must hold rcu_lock or sufficient equivalent. */ int walk_tg_tree_from(struct task_group *from, tg_visitor down, tg_visitor up, void *data) { … } int tg_nop(struct task_group *tg, void *data) { … } #endif void set_load_weight(struct task_struct *p, bool update_load) { … } #ifdef CONFIG_UCLAMP_TASK /* * Serializes updates of utilization clamp values * * The (slow-path) user-space triggers utilization clamp value updates which * can require updates on (fast-path) scheduler's data structures used to * support enqueue/dequeue operations. * While the per-CPU rq lock protects fast-path update operations, user-space * requests are serialized using a mutex to reduce the risk of conflicting * updates or API abuses. */ static DEFINE_MUTEX(uclamp_mutex); /* Max allowed minimum utilization */ static unsigned int __maybe_unused sysctl_sched_uclamp_util_min = …; /* Max allowed maximum utilization */ static unsigned int __maybe_unused sysctl_sched_uclamp_util_max = …; /* * By default RT tasks run at the maximum performance point/capacity of the * system. Uclamp enforces this by always setting UCLAMP_MIN of RT tasks to * SCHED_CAPACITY_SCALE. * * This knob allows admins to change the default behavior when uclamp is being * used. In battery powered devices, particularly, running at the maximum * capacity and frequency will increase energy consumption and shorten the * battery life. * * This knob only affects RT tasks that their uclamp_se->user_defined == false. * * This knob will not override the system default sched_util_clamp_min defined * above. */ unsigned int sysctl_sched_uclamp_util_min_rt_default = …; /* All clamps are required to be less or equal than these values */ static struct uclamp_se uclamp_default[UCLAMP_CNT]; /* * This static key is used to reduce the uclamp overhead in the fast path. It * primarily disables the call to uclamp_rq_{inc, dec}() in * enqueue/dequeue_task(). * * This allows users to continue to enable uclamp in their kernel config with * minimum uclamp overhead in the fast path. * * As soon as userspace modifies any of the uclamp knobs, the static key is * enabled, since we have an actual users that make use of uclamp * functionality. * * The knobs that would enable this static key are: * * * A task modifying its uclamp value with sched_setattr(). * * An admin modifying the sysctl_sched_uclamp_{min, max} via procfs. * * An admin modifying the cgroup cpu.uclamp.{min, max} */ DEFINE_STATIC_KEY_FALSE(sched_uclamp_used); static inline unsigned int uclamp_idle_value(struct rq *rq, enum uclamp_id clamp_id, unsigned int clamp_value) { … } static inline void uclamp_idle_reset(struct rq *rq, enum uclamp_id clamp_id, unsigned int clamp_value) { … } static inline unsigned int uclamp_rq_max_value(struct rq *rq, enum uclamp_id clamp_id, unsigned int clamp_value) { … } static void __uclamp_update_util_min_rt_default(struct task_struct *p) { … } static void uclamp_update_util_min_rt_default(struct task_struct *p) { … } static inline struct uclamp_se uclamp_tg_restrict(struct task_struct *p, enum uclamp_id clamp_id) { … } /* * The effective clamp bucket index of a task depends on, by increasing * priority: * - the task specific clamp value, when explicitly requested from userspace * - the task group effective clamp value, for tasks not either in the root * group or in an autogroup * - the system default clamp value, defined by the sysadmin */ static inline struct uclamp_se uclamp_eff_get(struct task_struct *p, enum uclamp_id clamp_id) { … } unsigned long uclamp_eff_value(struct task_struct *p, enum uclamp_id clamp_id) { … } /* * When a task is enqueued on a rq, the clamp bucket currently defined by the * task's uclamp::bucket_id is refcounted on that rq. This also immediately * updates the rq's clamp value if required. * * Tasks can have a task-specific value requested from user-space, track * within each bucket the maximum value for tasks refcounted in it. * This "local max aggregation" allows to track the exact "requested" value * for each bucket when all its RUNNABLE tasks require the same clamp. */ static inline void uclamp_rq_inc_id(struct rq *rq, struct task_struct *p, enum uclamp_id clamp_id) { … } /* * When a task is dequeued from a rq, the clamp bucket refcounted by the task * is released. If this is the last task reference counting the rq's max * active clamp value, then the rq's clamp value is updated. * * Both refcounted tasks and rq's cached clamp values are expected to be * always valid. If it's detected they are not, as defensive programming, * enforce the expected state and warn. */ static inline void uclamp_rq_dec_id(struct rq *rq, struct task_struct *p, enum uclamp_id clamp_id) { … } static inline void uclamp_rq_inc(struct rq *rq, struct task_struct *p) { … } static inline void uclamp_rq_dec(struct rq *rq, struct task_struct *p) { … } static inline void uclamp_rq_reinc_id(struct rq *rq, struct task_struct *p, enum uclamp_id clamp_id) { … } static inline void uclamp_update_active(struct task_struct *p) { … } #ifdef CONFIG_UCLAMP_TASK_GROUP static inline void uclamp_update_active_tasks(struct cgroup_subsys_state *css) { … } static void cpu_util_update_eff(struct cgroup_subsys_state *css); #endif #ifdef CONFIG_SYSCTL #ifdef CONFIG_UCLAMP_TASK_GROUP static void uclamp_update_root_tg(void) { … } #else static void uclamp_update_root_tg(void) { } #endif static void uclamp_sync_util_min_rt_default(void) { … } static int sysctl_sched_uclamp_handler(const struct ctl_table *table, int write, void *buffer, size_t *lenp, loff_t *ppos) { … } #endif static void uclamp_fork(struct task_struct *p) { … } static void uclamp_post_fork(struct task_struct *p) { … } static void __init init_uclamp_rq(struct rq *rq) { … } static void __init init_uclamp(void) { … } #else /* !CONFIG_UCLAMP_TASK */ static inline void uclamp_rq_inc(struct rq *rq, struct task_struct *p) { } static inline void uclamp_rq_dec(struct rq *rq, struct task_struct *p) { } static inline void uclamp_fork(struct task_struct *p) { } static inline void uclamp_post_fork(struct task_struct *p) { } static inline void init_uclamp(void) { } #endif /* CONFIG_UCLAMP_TASK */ bool sched_task_on_rq(struct task_struct *p) { … } unsigned long get_wchan(struct task_struct *p) { … } void enqueue_task(struct rq *rq, struct task_struct *p, int flags) { … } void dequeue_task(struct rq *rq, struct task_struct *p, int flags) { … } void activate_task(struct rq *rq, struct task_struct *p, int flags) { … } void deactivate_task(struct rq *rq, struct task_struct *p, int flags) { … } /** * task_curr - is this task currently executing on a CPU? * @p: the task in question. * * Return: 1 if the task is currently executing. 0 otherwise. */ inline int task_curr(const struct task_struct *p) { … } /* * switched_from, switched_to and prio_changed must _NOT_ drop rq->lock, * use the balance_callback list if you want balancing. * * this means any call to check_class_changed() must be followed by a call to * balance_callback(). */ void check_class_changed(struct rq *rq, struct task_struct *p, const struct sched_class *prev_class, int oldprio) { … } void wakeup_preempt(struct rq *rq, struct task_struct *p, int flags) { … } static __always_inline int __task_state_match(struct task_struct *p, unsigned int state) { … } static __always_inline int task_state_match(struct task_struct *p, unsigned int state) { … } /* * wait_task_inactive - wait for a thread to unschedule. * * Wait for the thread to block in any of the states set in @match_state. * If it changes, i.e. @p might have woken up, then return zero. When we * succeed in waiting for @p to be off its CPU, we return a positive number * (its total switch count). If a second call a short while later returns the * same number, the caller can be sure that @p has remained unscheduled the * whole time. * * The caller must ensure that the task *will* unschedule sometime soon, * else this function might spin for a *long* time. This function can't * be called with interrupts off, or it may introduce deadlock with * smp_call_function() if an IPI is sent by the same process we are * waiting to become inactive. */ unsigned long wait_task_inactive(struct task_struct *p, unsigned int match_state) { … } #ifdef CONFIG_SMP static void __do_set_cpus_allowed(struct task_struct *p, struct affinity_context *ctx); static void migrate_disable_switch(struct rq *rq, struct task_struct *p) { … } void migrate_disable(void) { … } EXPORT_SYMBOL_GPL(…); void migrate_enable(void) { … } EXPORT_SYMBOL_GPL(…); static inline bool rq_has_pinned_tasks(struct rq *rq) { … } /* * Per-CPU kthreads are allowed to run on !active && online CPUs, see * __set_cpus_allowed_ptr() and select_fallback_rq(). */ static inline bool is_cpu_allowed(struct task_struct *p, int cpu) { … } /* * This is how migration works: * * 1) we invoke migration_cpu_stop() on the target CPU using * stop_one_cpu(). * 2) stopper starts to run (implicitly forcing the migrated thread * off the CPU) * 3) it checks whether the migrated task is still in the wrong runqueue. * 4) if it's in the wrong runqueue then the migration thread removes * it and puts it into the right queue. * 5) stopper completes and stop_one_cpu() returns and the migration * is done. */ /* * move_queued_task - move a queued task to new rq. * * Returns (locked) new rq. Old rq's lock is released. */ static struct rq *move_queued_task(struct rq *rq, struct rq_flags *rf, struct task_struct *p, int new_cpu) { … } struct migration_arg { … }; /* * @refs: number of wait_for_completion() * @stop_pending: is @stop_work in use */ struct set_affinity_pending { … }; /* * Move (not current) task off this CPU, onto the destination CPU. We're doing * this because either it can't run here any more (set_cpus_allowed() * away from this CPU, or CPU going down), or because we're * attempting to rebalance this task on exec (sched_exec). * * So we race with normal scheduler movements, but that's OK, as long * as the task is no longer on this CPU. */ static struct rq *__migrate_task(struct rq *rq, struct rq_flags *rf, struct task_struct *p, int dest_cpu) { … } /* * migration_cpu_stop - this will be executed by a high-prio stopper thread * and performs thread migration by bumping thread off CPU then * 'pushing' onto another runqueue. */ static int migration_cpu_stop(void *data) { … } int push_cpu_stop(void *arg) { … } /* * sched_class::set_cpus_allowed must do the below, but is not required to * actually call this function. */ void set_cpus_allowed_common(struct task_struct *p, struct affinity_context *ctx) { … } static void __do_set_cpus_allowed(struct task_struct *p, struct affinity_context *ctx) { … } /* * Used for kthread_bind() and select_fallback_rq(), in both cases the user * affinity (if any) should be destroyed too. */ void do_set_cpus_allowed(struct task_struct *p, const struct cpumask *new_mask) { … } int dup_user_cpus_ptr(struct task_struct *dst, struct task_struct *src, int node) { … } static inline struct cpumask *clear_user_cpus_ptr(struct task_struct *p) { … } void release_user_cpus_ptr(struct task_struct *p) { … } /* * This function is wildly self concurrent; here be dragons. * * * When given a valid mask, __set_cpus_allowed_ptr() must block until the * designated task is enqueued on an allowed CPU. If that task is currently * running, we have to kick it out using the CPU stopper. * * Migrate-Disable comes along and tramples all over our nice sandcastle. * Consider: * * Initial conditions: P0->cpus_mask = [0, 1] * * P0@CPU0 P1 * * migrate_disable(); * <preempted> * set_cpus_allowed_ptr(P0, [1]); * * P1 *cannot* return from this set_cpus_allowed_ptr() call until P0 executes * its outermost migrate_enable() (i.e. it exits its Migrate-Disable region). * This means we need the following scheme: * * P0@CPU0 P1 * * migrate_disable(); * <preempted> * set_cpus_allowed_ptr(P0, [1]); * <blocks> * <resumes> * migrate_enable(); * __set_cpus_allowed_ptr(); * <wakes local stopper> * `--> <woken on migration completion> * * Now the fun stuff: there may be several P1-like tasks, i.e. multiple * concurrent set_cpus_allowed_ptr(P0, [*]) calls. CPU affinity changes of any * task p are serialized by p->pi_lock, which we can leverage: the one that * should come into effect at the end of the Migrate-Disable region is the last * one. This means we only need to track a single cpumask (i.e. p->cpus_mask), * but we still need to properly signal those waiting tasks at the appropriate * moment. * * This is implemented using struct set_affinity_pending. The first * __set_cpus_allowed_ptr() caller within a given Migrate-Disable region will * setup an instance of that struct and install it on the targeted task_struct. * Any and all further callers will reuse that instance. Those then wait for * a completion signaled at the tail of the CPU stopper callback (1), triggered * on the end of the Migrate-Disable region (i.e. outermost migrate_enable()). * * * (1) In the cases covered above. There is one more where the completion is * signaled within affine_move_task() itself: when a subsequent affinity request * occurs after the stopper bailed out due to the targeted task still being * Migrate-Disable. Consider: * * Initial conditions: P0->cpus_mask = [0, 1] * * CPU0 P1 P2 * <P0> * migrate_disable(); * <preempted> * set_cpus_allowed_ptr(P0, [1]); * <blocks> * <migration/0> * migration_cpu_stop() * is_migration_disabled() * <bails> * set_cpus_allowed_ptr(P0, [0, 1]); * <signal completion> * <awakes> * * Note that the above is safe vs a concurrent migrate_enable(), as any * pending affinity completion is preceded by an uninstallation of * p->migration_pending done with p->pi_lock held. */ static int affine_move_task(struct rq *rq, struct task_struct *p, struct rq_flags *rf, int dest_cpu, unsigned int flags) __releases(rq->lock) __releases(p->pi_lock) { … } /* * Called with both p->pi_lock and rq->lock held; drops both before returning. */ static int __set_cpus_allowed_ptr_locked(struct task_struct *p, struct affinity_context *ctx, struct rq *rq, struct rq_flags *rf) __releases(rq->lock) __releases(p->pi_lock) { … } /* * Change a given task's CPU affinity. Migrate the thread to a * proper CPU and schedule it away if the CPU it's executing on * is removed from the allowed bitmask. * * NOTE: the caller must have a valid reference to the task, the * task must not exit() & deallocate itself prematurely. The * call is not atomic; no spinlocks may be held. */ int __set_cpus_allowed_ptr(struct task_struct *p, struct affinity_context *ctx) { … } int set_cpus_allowed_ptr(struct task_struct *p, const struct cpumask *new_mask) { … } EXPORT_SYMBOL_GPL(…); /* * Change a given task's CPU affinity to the intersection of its current * affinity mask and @subset_mask, writing the resulting mask to @new_mask. * If user_cpus_ptr is defined, use it as the basis for restricting CPU * affinity or use cpu_online_mask instead. * * If the resulting mask is empty, leave the affinity unchanged and return * -EINVAL. */ static int restrict_cpus_allowed_ptr(struct task_struct *p, struct cpumask *new_mask, const struct cpumask *subset_mask) { … } /* * Restrict the CPU affinity of task @p so that it is a subset of * task_cpu_possible_mask() and point @p->user_cpus_ptr to a copy of the * old affinity mask. If the resulting mask is empty, we warn and walk * up the cpuset hierarchy until we find a suitable mask. */ void force_compatible_cpus_allowed_ptr(struct task_struct *p) { … } /* * Restore the affinity of a task @p which was previously restricted by a * call to force_compatible_cpus_allowed_ptr(). * * It is the caller's responsibility to serialise this with any calls to * force_compatible_cpus_allowed_ptr(@p). */ void relax_compatible_cpus_allowed_ptr(struct task_struct *p) { … } void set_task_cpu(struct task_struct *p, unsigned int new_cpu) { … } #ifdef CONFIG_NUMA_BALANCING static void __migrate_swap_task(struct task_struct *p, int cpu) { … } struct migration_swap_arg { … }; static int migrate_swap_stop(void *data) { … } /* * Cross migrate two tasks */ int migrate_swap(struct task_struct *cur, struct task_struct *p, int target_cpu, int curr_cpu) { … } #endif /* CONFIG_NUMA_BALANCING */ /*** * kick_process - kick a running thread to enter/exit the kernel * @p: the to-be-kicked thread * * Cause a process which is running on another CPU to enter * kernel-mode, without any delay. (to get signals handled.) * * NOTE: this function doesn't have to take the runqueue lock, * because all it wants to ensure is that the remote task enters * the kernel. If the IPI races and the task has been migrated * to another CPU then no harm is done and the purpose has been * achieved as well. */ void kick_process(struct task_struct *p) { … } EXPORT_SYMBOL_GPL(…); /* * ->cpus_ptr is protected by both rq->lock and p->pi_lock * * A few notes on cpu_active vs cpu_online: * * - cpu_active must be a subset of cpu_online * * - on CPU-up we allow per-CPU kthreads on the online && !active CPU, * see __set_cpus_allowed_ptr(). At this point the newly online * CPU isn't yet part of the sched domains, and balancing will not * see it. * * - on CPU-down we clear cpu_active() to mask the sched domains and * avoid the load balancer to place new tasks on the to be removed * CPU. Existing tasks will remain running there and will be taken * off. * * This means that fallback selection must not select !active CPUs. * And can assume that any active CPU must be online. Conversely * select_task_rq() below may allow selection of !active CPUs in order * to satisfy the above rules. */ static int select_fallback_rq(int cpu, struct task_struct *p) { … } /* * The caller (fork, wakeup) owns p->pi_lock, ->cpus_ptr is stable. */ static inline int select_task_rq(struct task_struct *p, int cpu, int wake_flags) { … } void sched_set_stop_task(int cpu, struct task_struct *stop) { … } #else /* CONFIG_SMP */ static inline void migrate_disable_switch(struct rq *rq, struct task_struct *p) { } static inline bool rq_has_pinned_tasks(struct rq *rq) { return false; } #endif /* !CONFIG_SMP */ static void ttwu_stat(struct task_struct *p, int cpu, int wake_flags) { … } /* * Mark the task runnable. */ static inline void ttwu_do_wakeup(struct task_struct *p) { … } static void ttwu_do_activate(struct rq *rq, struct task_struct *p, int wake_flags, struct rq_flags *rf) { … } /* * Consider @p being inside a wait loop: * * for (;;) { * set_current_state(TASK_UNINTERRUPTIBLE); * * if (CONDITION) * break; * * schedule(); * } * __set_current_state(TASK_RUNNING); * * between set_current_state() and schedule(). In this case @p is still * runnable, so all that needs doing is change p->state back to TASK_RUNNING in * an atomic manner. * * By taking task_rq(p)->lock we serialize against schedule(), if @p->on_rq * then schedule() must still happen and p->state can be changed to * TASK_RUNNING. Otherwise we lost the race, schedule() has happened, and we * need to do a full wakeup with enqueue. * * Returns: %true when the wakeup is done, * %false otherwise. */ static int ttwu_runnable(struct task_struct *p, int wake_flags) { … } #ifdef CONFIG_SMP void sched_ttwu_pending(void *arg) { … } /* * Prepare the scene for sending an IPI for a remote smp_call * * Returns true if the caller can proceed with sending the IPI. * Returns false otherwise. */ bool call_function_single_prep_ipi(int cpu) { … } /* * Queue a task on the target CPUs wake_list and wake the CPU via IPI if * necessary. The wakee CPU on receipt of the IPI will queue the task * via sched_ttwu_wakeup() for activation so the wakee incurs the cost * of the wakeup instead of the waker. */ static void __ttwu_queue_wakelist(struct task_struct *p, int cpu, int wake_flags) { … } void wake_up_if_idle(int cpu) { … } bool cpus_equal_capacity(int this_cpu, int that_cpu) { … } bool cpus_share_cache(int this_cpu, int that_cpu) { … } /* * Whether CPUs are share cache resources, which means LLC on non-cluster * machines and LLC tag or L2 on machines with clusters. */ bool cpus_share_resources(int this_cpu, int that_cpu) { … } static inline bool ttwu_queue_cond(struct task_struct *p, int cpu) { … } static bool ttwu_queue_wakelist(struct task_struct *p, int cpu, int wake_flags) { … } #else /* !CONFIG_SMP */ static inline bool ttwu_queue_wakelist(struct task_struct *p, int cpu, int wake_flags) { return false; } #endif /* CONFIG_SMP */ static void ttwu_queue(struct task_struct *p, int cpu, int wake_flags) { … } /* * Invoked from try_to_wake_up() to check whether the task can be woken up. * * The caller holds p::pi_lock if p != current or has preemption * disabled when p == current. * * The rules of saved_state: * * The related locking code always holds p::pi_lock when updating * p::saved_state, which means the code is fully serialized in both cases. * * For PREEMPT_RT, the lock wait and lock wakeups happen via TASK_RTLOCK_WAIT. * No other bits set. This allows to distinguish all wakeup scenarios. * * For FREEZER, the wakeup happens via TASK_FROZEN. No other bits set. This * allows us to prevent early wakeup of tasks before they can be run on * asymmetric ISA architectures (eg ARMv9). */ static __always_inline bool ttwu_state_match(struct task_struct *p, unsigned int state, int *success) { … } /* * Notes on Program-Order guarantees on SMP systems. * * MIGRATION * * The basic program-order guarantee on SMP systems is that when a task [t] * migrates, all its activity on its old CPU [c0] happens-before any subsequent * execution on its new CPU [c1]. * * For migration (of runnable tasks) this is provided by the following means: * * A) UNLOCK of the rq(c0)->lock scheduling out task t * B) migration for t is required to synchronize *both* rq(c0)->lock and * rq(c1)->lock (if not at the same time, then in that order). * C) LOCK of the rq(c1)->lock scheduling in task * * Release/acquire chaining guarantees that B happens after A and C after B. * Note: the CPU doing B need not be c0 or c1 * * Example: * * CPU0 CPU1 CPU2 * * LOCK rq(0)->lock * sched-out X * sched-in Y * UNLOCK rq(0)->lock * * LOCK rq(0)->lock // orders against CPU0 * dequeue X * UNLOCK rq(0)->lock * * LOCK rq(1)->lock * enqueue X * UNLOCK rq(1)->lock * * LOCK rq(1)->lock // orders against CPU2 * sched-out Z * sched-in X * UNLOCK rq(1)->lock * * * BLOCKING -- aka. SLEEP + WAKEUP * * For blocking we (obviously) need to provide the same guarantee as for * migration. However the means are completely different as there is no lock * chain to provide order. Instead we do: * * 1) smp_store_release(X->on_cpu, 0) -- finish_task() * 2) smp_cond_load_acquire(!X->on_cpu) -- try_to_wake_up() * * Example: * * CPU0 (schedule) CPU1 (try_to_wake_up) CPU2 (schedule) * * LOCK rq(0)->lock LOCK X->pi_lock * dequeue X * sched-out X * smp_store_release(X->on_cpu, 0); * * smp_cond_load_acquire(&X->on_cpu, !VAL); * X->state = WAKING * set_task_cpu(X,2) * * LOCK rq(2)->lock * enqueue X * X->state = RUNNING * UNLOCK rq(2)->lock * * LOCK rq(2)->lock // orders against CPU1 * sched-out Z * sched-in X * UNLOCK rq(2)->lock * * UNLOCK X->pi_lock * UNLOCK rq(0)->lock * * * However, for wakeups there is a second guarantee we must provide, namely we * must ensure that CONDITION=1 done by the caller can not be reordered with * accesses to the task state; see try_to_wake_up() and set_current_state(). */ /** * try_to_wake_up - wake up a thread * @p: the thread to be awakened * @state: the mask of task states that can be woken * @wake_flags: wake modifier flags (WF_*) * * Conceptually does: * * If (@state & @p->state) @p->state = TASK_RUNNING. * * If the task was not queued/runnable, also place it back on a runqueue. * * This function is atomic against schedule() which would dequeue the task. * * It issues a full memory barrier before accessing @p->state, see the comment * with set_current_state(). * * Uses p->pi_lock to serialize against concurrent wake-ups. * * Relies on p->pi_lock stabilizing: * - p->sched_class * - p->cpus_ptr * - p->sched_task_group * in order to do migration, see its use of select_task_rq()/set_task_cpu(). * * Tries really hard to only take one task_rq(p)->lock for performance. * Takes rq->lock in: * - ttwu_runnable() -- old rq, unavoidable, see comment there; * - ttwu_queue() -- new rq, for enqueue of the task; * - psi_ttwu_dequeue() -- much sadness :-( accounting will kill us. * * As a consequence we race really badly with just about everything. See the * many memory barriers and their comments for details. * * Return: %true if @p->state changes (an actual wakeup was done), * %false otherwise. */ int try_to_wake_up(struct task_struct *p, unsigned int state, int wake_flags) { … } static bool __task_needs_rq_lock(struct task_struct *p) { … } /** * task_call_func - Invoke a function on task in fixed state * @p: Process for which the function is to be invoked, can be @current. * @func: Function to invoke. * @arg: Argument to function. * * Fix the task in it's current state by avoiding wakeups and or rq operations * and call @func(@arg) on it. This function can use ->on_rq and task_curr() * to work out what the state is, if required. Given that @func can be invoked * with a runqueue lock held, it had better be quite lightweight. * * Returns: * Whatever @func returns */ int task_call_func(struct task_struct *p, task_call_f func, void *arg) { … } /** * cpu_curr_snapshot - Return a snapshot of the currently running task * @cpu: The CPU on which to snapshot the task. * * Returns the task_struct pointer of the task "currently" running on * the specified CPU. * * If the specified CPU was offline, the return value is whatever it * is, perhaps a pointer to the task_struct structure of that CPU's idle * task, but there is no guarantee. Callers wishing a useful return * value must take some action to ensure that the specified CPU remains * online throughout. * * This function executes full memory barriers before and after fetching * the pointer, which permits the caller to confine this function's fetch * with respect to the caller's accesses to other shared variables. */ struct task_struct *cpu_curr_snapshot(int cpu) { … } /** * wake_up_process - Wake up a specific process * @p: The process to be woken up. * * Attempt to wake up the nominated process and move it to the set of runnable * processes. * * Return: 1 if the process was woken up, 0 if it was already running. * * This function executes a full memory barrier before accessing the task state. */ int wake_up_process(struct task_struct *p) { … } EXPORT_SYMBOL(…); int wake_up_state(struct task_struct *p, unsigned int state) { … } /* * Perform scheduler related setup for a newly forked process p. * p is forked by current. * * __sched_fork() is basic setup used by init_idle() too: */ static void __sched_fork(unsigned long clone_flags, struct task_struct *p) { … } DEFINE_STATIC_KEY_FALSE(sched_numa_balancing); #ifdef CONFIG_NUMA_BALANCING int sysctl_numa_balancing_mode; static void __set_numabalancing_state(bool enabled) { … } void set_numabalancing_state(bool enabled) { … } #ifdef CONFIG_PROC_SYSCTL static void reset_memory_tiering(void) { … } static int sysctl_numa_balancing(const struct ctl_table *table, int write, void *buffer, size_t *lenp, loff_t *ppos) { … } #endif #endif #ifdef CONFIG_SCHEDSTATS DEFINE_STATIC_KEY_FALSE(sched_schedstats); static void set_schedstats(bool enabled) { … } void force_schedstat_enabled(void) { … } static int __init setup_schedstats(char *str) { … } __setup(…); #ifdef CONFIG_PROC_SYSCTL static int sysctl_schedstats(const struct ctl_table *table, int write, void *buffer, size_t *lenp, loff_t *ppos) { … } #endif /* CONFIG_PROC_SYSCTL */ #endif /* CONFIG_SCHEDSTATS */ #ifdef CONFIG_SYSCTL static struct ctl_table sched_core_sysctls[] = …; static int __init sched_core_sysctl_init(void) { … } late_initcall(sched_core_sysctl_init); #endif /* CONFIG_SYSCTL */ /* * fork()/clone()-time setup: */ int sched_fork(unsigned long clone_flags, struct task_struct *p) { … } void sched_cgroup_fork(struct task_struct *p, struct kernel_clone_args *kargs) { … } void sched_post_fork(struct task_struct *p) { … } unsigned long to_ratio(u64 period, u64 runtime) { … } /* * wake_up_new_task - wake up a newly created task for the first time. * * This function will do some initial scheduler statistics housekeeping * that must be done for every newly created context, then puts the task * on the runqueue and wakes it. */ void wake_up_new_task(struct task_struct *p) { … } #ifdef CONFIG_PREEMPT_NOTIFIERS static DEFINE_STATIC_KEY_FALSE(preempt_notifier_key); void preempt_notifier_inc(void) { … } EXPORT_SYMBOL_GPL(…); void preempt_notifier_dec(void) { … } EXPORT_SYMBOL_GPL(…); /** * preempt_notifier_register - tell me when current is being preempted & rescheduled * @notifier: notifier struct to register */ void preempt_notifier_register(struct preempt_notifier *notifier) { … } EXPORT_SYMBOL_GPL(…); /** * preempt_notifier_unregister - no longer interested in preemption notifications * @notifier: notifier struct to unregister * * This is *not* safe to call from within a preemption notifier. */ void preempt_notifier_unregister(struct preempt_notifier *notifier) { … } EXPORT_SYMBOL_GPL(…); static void __fire_sched_in_preempt_notifiers(struct task_struct *curr) { … } static __always_inline void fire_sched_in_preempt_notifiers(struct task_struct *curr) { … } static void __fire_sched_out_preempt_notifiers(struct task_struct *curr, struct task_struct *next) { … } static __always_inline void fire_sched_out_preempt_notifiers(struct task_struct *curr, struct task_struct *next) { … } #else /* !CONFIG_PREEMPT_NOTIFIERS */ static inline void fire_sched_in_preempt_notifiers(struct task_struct *curr) { } static inline void fire_sched_out_preempt_notifiers(struct task_struct *curr, struct task_struct *next) { } #endif /* CONFIG_PREEMPT_NOTIFIERS */ static inline void prepare_task(struct task_struct *next) { … } static inline void finish_task(struct task_struct *prev) { … } #ifdef CONFIG_SMP static void do_balance_callbacks(struct rq *rq, struct balance_callback *head) { … } static void balance_push(struct rq *rq); /* * balance_push_callback is a right abuse of the callback interface and plays * by significantly different rules. * * Where the normal balance_callback's purpose is to be ran in the same context * that queued it (only later, when it's safe to drop rq->lock again), * balance_push_callback is specifically targeted at __schedule(). * * This abuse is tolerated because it places all the unlikely/odd cases behind * a single test, namely: rq->balance_callback == NULL. */ struct balance_callback balance_push_callback = …; static inline struct balance_callback * __splice_balance_callbacks(struct rq *rq, bool split) { … } struct balance_callback *splice_balance_callbacks(struct rq *rq) { … } static void __balance_callbacks(struct rq *rq) { … } void balance_callbacks(struct rq *rq, struct balance_callback *head) { … } #else static inline void __balance_callbacks(struct rq *rq) { } #endif static inline void prepare_lock_switch(struct rq *rq, struct task_struct *next, struct rq_flags *rf) { … } static inline void finish_lock_switch(struct rq *rq) { … } /* * NOP if the arch has not defined these: */ #ifndef prepare_arch_switch #define prepare_arch_switch(next) … #endif #ifndef finish_arch_post_lock_switch #define finish_arch_post_lock_switch() … #endif static inline void kmap_local_sched_out(void) { … } static inline void kmap_local_sched_in(void) { … } /** * prepare_task_switch - prepare to switch tasks * @rq: the runqueue preparing to switch * @prev: the current task that is being switched out * @next: the task we are going to switch to. * * This is called with the rq lock held and interrupts off. It must * be paired with a subsequent finish_task_switch after the context * switch. * * prepare_task_switch sets up locking and calls architecture specific * hooks. */ static inline void prepare_task_switch(struct rq *rq, struct task_struct *prev, struct task_struct *next) { … } /** * finish_task_switch - clean up after a task-switch * @prev: the thread we just switched away from. * * finish_task_switch must be called after the context switch, paired * with a prepare_task_switch call before the context switch. * finish_task_switch will reconcile locking set up by prepare_task_switch, * and do any other architecture-specific cleanup actions. * * Note that we may have delayed dropping an mm in context_switch(). If * so, we finish that here outside of the runqueue lock. (Doing it * with the lock held can cause deadlocks; see schedule() for * details.) * * The context switch have flipped the stack from under us and restored the * local variables which were saved when this task called schedule() in the * past. 'prev == current' is still correct but we need to recalculate this_rq * because prev may have moved to another CPU. */ static struct rq *finish_task_switch(struct task_struct *prev) __releases(rq->lock) { … } /** * schedule_tail - first thing a freshly forked thread must call. * @prev: the thread we just switched away from. */ asmlinkage __visible void schedule_tail(struct task_struct *prev) __releases(rq->lock) { … } /* * context_switch - switch to the new MM and the new thread's register state. */ static __always_inline struct rq * context_switch(struct rq *rq, struct task_struct *prev, struct task_struct *next, struct rq_flags *rf) { … } /* * nr_running and nr_context_switches: * * externally visible scheduler statistics: current number of runnable * threads, total number of context switches performed since bootup. */ unsigned int nr_running(void) { … } /* * Check if only the current task is running on the CPU. * * Caution: this function does not check that the caller has disabled * preemption, thus the result might have a time-of-check-to-time-of-use * race. The caller is responsible to use it correctly, for example: * * - from a non-preemptible section (of course) * * - from a thread that is bound to a single CPU * * - in a loop with very short iterations (e.g. a polling loop) */ bool single_task_running(void) { … } EXPORT_SYMBOL(…); unsigned long long nr_context_switches_cpu(int cpu) { … } unsigned long long nr_context_switches(void) { … } /* * Consumers of these two interfaces, like for example the cpuidle menu * governor, are using nonsensical data. Preferring shallow idle state selection * for a CPU that has IO-wait which might not even end up running the task when * it does become runnable. */ unsigned int nr_iowait_cpu(int cpu) { … } /* * IO-wait accounting, and how it's mostly bollocks (on SMP). * * The idea behind IO-wait account is to account the idle time that we could * have spend running if it were not for IO. That is, if we were to improve the * storage performance, we'd have a proportional reduction in IO-wait time. * * This all works nicely on UP, where, when a task blocks on IO, we account * idle time as IO-wait, because if the storage were faster, it could've been * running and we'd not be idle. * * This has been extended to SMP, by doing the same for each CPU. This however * is broken. * * Imagine for instance the case where two tasks block on one CPU, only the one * CPU will have IO-wait accounted, while the other has regular idle. Even * though, if the storage were faster, both could've ran at the same time, * utilising both CPUs. * * This means, that when looking globally, the current IO-wait accounting on * SMP is a lower bound, by reason of under accounting. * * Worse, since the numbers are provided per CPU, they are sometimes * interpreted per CPU, and that is nonsensical. A blocked task isn't strictly * associated with any one particular CPU, it can wake to another CPU than it * blocked on. This means the per CPU IO-wait number is meaningless. * * Task CPU affinities can make all that even more 'interesting'. */ unsigned int nr_iowait(void) { … } #ifdef CONFIG_SMP /* * sched_exec - execve() is a valuable balancing opportunity, because at * this point the task has the smallest effective memory and cache footprint. */ void sched_exec(void) { … } #endif DEFINE_PER_CPU(struct kernel_stat, kstat); DEFINE_PER_CPU(struct kernel_cpustat, kernel_cpustat); EXPORT_PER_CPU_SYMBOL(…); EXPORT_PER_CPU_SYMBOL(…); /* * The function fair_sched_class.update_curr accesses the struct curr * and its field curr->exec_start; when called from task_sched_runtime(), * we observe a high rate of cache misses in practice. * Prefetching this data results in improved performance. */ static inline void prefetch_curr_exec_start(struct task_struct *p) { … } /* * Return accounted runtime for the task. * In case the task is currently running, return the runtime plus current's * pending runtime that have not been accounted yet. */ unsigned long long task_sched_runtime(struct task_struct *p) { … } #ifdef CONFIG_SCHED_DEBUG static u64 cpu_resched_latency(struct rq *rq) { … } static int __init setup_resched_latency_warn_ms(char *str) { … } __setup(…); #else static inline u64 cpu_resched_latency(struct rq *rq) { return 0; } #endif /* CONFIG_SCHED_DEBUG */ /* * This function gets called by the timer code, with HZ frequency. * We call it with interrupts disabled. */ void sched_tick(void) { … } #ifdef CONFIG_NO_HZ_FULL struct tick_work { int cpu; atomic_t state; struct delayed_work work; }; /* Values for ->state, see diagram below. */ #define TICK_SCHED_REMOTE_OFFLINE … #define TICK_SCHED_REMOTE_OFFLINING … #define TICK_SCHED_REMOTE_RUNNING … /* * State diagram for ->state: * * * TICK_SCHED_REMOTE_OFFLINE * | ^ * | | * | | sched_tick_remote() * | | * | | * +--TICK_SCHED_REMOTE_OFFLINING * | ^ * | | * sched_tick_start() | | sched_tick_stop() * | | * V | * TICK_SCHED_REMOTE_RUNNING * * * Other transitions get WARN_ON_ONCE(), except that sched_tick_remote() * and sched_tick_start() are happy to leave the state in RUNNING. */ static struct tick_work __percpu *tick_work_cpu; static void sched_tick_remote(struct work_struct *work) { struct delayed_work *dwork = to_delayed_work(work); struct tick_work *twork = container_of(dwork, struct tick_work, work); int cpu = twork->cpu; struct rq *rq = cpu_rq(cpu); int os; /* * Handle the tick only if it appears the remote CPU is running in full * dynticks mode. The check is racy by nature, but missing a tick or * having one too much is no big deal because the scheduler tick updates * statistics and checks timeslices in a time-independent way, regardless * of when exactly it is running. */ if (tick_nohz_tick_stopped_cpu(cpu)) { guard(rq_lock_irq)(rq); struct task_struct *curr = rq->curr; if (cpu_online(cpu)) { update_rq_clock(rq); if (!is_idle_task(curr)) { /* * Make sure the next tick runs within a * reasonable amount of time. */ u64 delta = rq_clock_task(rq) - curr->se.exec_start; WARN_ON_ONCE(delta > (u64)NSEC_PER_SEC * 3); } curr->sched_class->task_tick(rq, curr, 0); calc_load_nohz_remote(rq); } } /* * Run the remote tick once per second (1Hz). This arbitrary * frequency is large enough to avoid overload but short enough * to keep scheduler internal stats reasonably up to date. But * first update state to reflect hotplug activity if required. */ os = atomic_fetch_add_unless(&twork->state, -1, TICK_SCHED_REMOTE_RUNNING); WARN_ON_ONCE(os == TICK_SCHED_REMOTE_OFFLINE); if (os == TICK_SCHED_REMOTE_RUNNING) queue_delayed_work(system_unbound_wq, dwork, HZ); } static void sched_tick_start(int cpu) { int os; struct tick_work *twork; if (housekeeping_cpu(cpu, HK_TYPE_TICK)) return; WARN_ON_ONCE(!tick_work_cpu); twork = per_cpu_ptr(tick_work_cpu, cpu); os = atomic_xchg(&twork->state, TICK_SCHED_REMOTE_RUNNING); WARN_ON_ONCE(os == TICK_SCHED_REMOTE_RUNNING); if (os == TICK_SCHED_REMOTE_OFFLINE) { twork->cpu = cpu; INIT_DELAYED_WORK(&twork->work, sched_tick_remote); queue_delayed_work(system_unbound_wq, &twork->work, HZ); } } #ifdef CONFIG_HOTPLUG_CPU static void sched_tick_stop(int cpu) { struct tick_work *twork; int os; if (housekeeping_cpu(cpu, HK_TYPE_TICK)) return; WARN_ON_ONCE(!tick_work_cpu); twork = per_cpu_ptr(tick_work_cpu, cpu); /* There cannot be competing actions, but don't rely on stop-machine. */ os = atomic_xchg(&twork->state, TICK_SCHED_REMOTE_OFFLINING); WARN_ON_ONCE(os != TICK_SCHED_REMOTE_RUNNING); /* Don't cancel, as this would mess up the state machine. */ } #endif /* CONFIG_HOTPLUG_CPU */ int __init sched_tick_offload_init(void) { tick_work_cpu = alloc_percpu(struct tick_work); BUG_ON(!tick_work_cpu); return 0; } #else /* !CONFIG_NO_HZ_FULL */ static inline void sched_tick_start(int cpu) { … } static inline void sched_tick_stop(int cpu) { … } #endif #if defined(CONFIG_PREEMPTION) && (defined(CONFIG_DEBUG_PREEMPT) || \ defined(CONFIG_TRACE_PREEMPT_TOGGLE)) /* * If the value passed in is equal to the current preempt count * then we just disabled preemption. Start timing the latency. */ static inline void preempt_latency_start(int val) { … } void preempt_count_add(int val) { … } EXPORT_SYMBOL(…); NOKPROBE_SYMBOL(preempt_count_add); /* * If the value passed in equals to the current preempt count * then we just enabled preemption. Stop timing the latency. */ static inline void preempt_latency_stop(int val) { … } void preempt_count_sub(int val) { … } EXPORT_SYMBOL(…); NOKPROBE_SYMBOL(preempt_count_sub); #else static inline void preempt_latency_start(int val) { } static inline void preempt_latency_stop(int val) { } #endif static inline unsigned long get_preempt_disable_ip(struct task_struct *p) { … } /* * Print scheduling while atomic bug: */ static noinline void __schedule_bug(struct task_struct *prev) { … } /* * Various schedule()-time debugging checks and statistics: */ static inline void schedule_debug(struct task_struct *prev, bool preempt) { … } static void put_prev_task_balance(struct rq *rq, struct task_struct *prev, struct rq_flags *rf) { … } /* * Pick up the highest-prio task: */ static inline struct task_struct * __pick_next_task(struct rq *rq, struct task_struct *prev, struct rq_flags *rf) { … } #ifdef CONFIG_SCHED_CORE static inline bool is_task_rq_idle(struct task_struct *t) { … } static inline bool cookie_equals(struct task_struct *a, unsigned long cookie) { … } static inline bool cookie_match(struct task_struct *a, struct task_struct *b) { … } static inline struct task_struct *pick_task(struct rq *rq) { … } extern void task_vruntime_update(struct rq *rq, struct task_struct *p, bool in_fi); static void queue_core_balance(struct rq *rq); static struct task_struct * pick_next_task(struct rq *rq, struct task_struct *prev, struct rq_flags *rf) { … } static bool try_steal_cookie(int this, int that) { … } static bool steal_cookie_task(int cpu, struct sched_domain *sd) { … } static void sched_core_balance(struct rq *rq) { … } static DEFINE_PER_CPU(struct balance_callback, core_balance_head); static void queue_core_balance(struct rq *rq) { … } DEFINE_LOCK_GUARD_1(core_lock, int, sched_core_lock(*_T->lock, &_T->flags), sched_core_unlock(*_T->lock, &_T->flags), … } static void sched_core_cpu_starting(unsigned int cpu) { … } static void sched_core_cpu_deactivate(unsigned int cpu) { … } static inline void sched_core_cpu_dying(unsigned int cpu) { … } #else /* !CONFIG_SCHED_CORE */ static inline void sched_core_cpu_starting(unsigned int cpu) {} static inline void sched_core_cpu_deactivate(unsigned int cpu) {} static inline void sched_core_cpu_dying(unsigned int cpu) {} static struct task_struct * pick_next_task(struct rq *rq, struct task_struct *prev, struct rq_flags *rf) { return __pick_next_task(rq, prev, rf); } #endif /* CONFIG_SCHED_CORE */ /* * Constants for the sched_mode argument of __schedule(). * * The mode argument allows RT enabled kernels to differentiate a * preemption from blocking on an 'sleeping' spin/rwlock. Note that * SM_MASK_PREEMPT for !RT has all bits set, which allows the compiler to * optimize the AND operation out and just check for zero. */ #define SM_NONE … #define SM_PREEMPT … #define SM_RTLOCK_WAIT … #ifndef CONFIG_PREEMPT_RT #define SM_MASK_PREEMPT … #else #define SM_MASK_PREEMPT … #endif /* * __schedule() is the main scheduler function. * * The main means of driving the scheduler and thus entering this function are: * * 1. Explicit blocking: mutex, semaphore, waitqueue, etc. * * 2. TIF_NEED_RESCHED flag is checked on interrupt and userspace return * paths. For example, see arch/x86/entry_64.S. * * To drive preemption between tasks, the scheduler sets the flag in timer * interrupt handler sched_tick(). * * 3. Wakeups don't really cause entry into schedule(). They add a * task to the run-queue and that's it. * * Now, if the new task added to the run-queue preempts the current * task, then the wakeup sets TIF_NEED_RESCHED and schedule() gets * called on the nearest possible occasion: * * - If the kernel is preemptible (CONFIG_PREEMPTION=y): * * - in syscall or exception context, at the next outmost * preempt_enable(). (this might be as soon as the wake_up()'s * spin_unlock()!) * * - in IRQ context, return from interrupt-handler to * preemptible context * * - If the kernel is not preemptible (CONFIG_PREEMPTION is not set) * then at the next: * * - cond_resched() call * - explicit schedule() call * - return from syscall or exception to user-space * - return from interrupt-handler to user-space * * WARNING: must be called with preemption disabled! */ static void __sched notrace __schedule(unsigned int sched_mode) { … } void __noreturn do_task_dead(void) { … } static inline void sched_submit_work(struct task_struct *tsk) { … } static void sched_update_worker(struct task_struct *tsk) { … } static __always_inline void __schedule_loop(unsigned int sched_mode) { … } asmlinkage __visible void __sched schedule(void) { … } EXPORT_SYMBOL(…); /* * synchronize_rcu_tasks() makes sure that no task is stuck in preempted * state (have scheduled out non-voluntarily) by making sure that all * tasks have either left the run queue or have gone into user space. * As idle tasks do not do either, they must not ever be preempted * (schedule out non-voluntarily). * * schedule_idle() is similar to schedule_preempt_disable() except that it * never enables preemption because it does not call sched_submit_work(). */ void __sched schedule_idle(void) { … } #if defined(CONFIG_CONTEXT_TRACKING_USER) && !defined(CONFIG_HAVE_CONTEXT_TRACKING_USER_OFFSTACK) asmlinkage __visible void __sched schedule_user(void) { /* * If we come here after a random call to set_need_resched(), * or we have been woken up remotely but the IPI has not yet arrived, * we haven't yet exited the RCU idle mode. Do it here manually until * we find a better solution. * * NB: There are buggy callers of this function. Ideally we * should warn if prev_state != CONTEXT_USER, but that will trigger * too frequently to make sense yet. */ enum ctx_state prev_state = exception_enter(); schedule(); exception_exit(prev_state); } #endif /** * schedule_preempt_disabled - called with preemption disabled * * Returns with preemption disabled. Note: preempt_count must be 1 */ void __sched schedule_preempt_disabled(void) { … } #ifdef CONFIG_PREEMPT_RT void __sched notrace schedule_rtlock(void) { __schedule_loop(SM_RTLOCK_WAIT); } NOKPROBE_SYMBOL(schedule_rtlock); #endif static void __sched notrace preempt_schedule_common(void) { … } #ifdef CONFIG_PREEMPTION /* * This is the entry point to schedule() from in-kernel preemption * off of preempt_enable. */ asmlinkage __visible void __sched notrace preempt_schedule(void) { … } NOKPROBE_SYMBOL(preempt_schedule); EXPORT_SYMBOL(…); #ifdef CONFIG_PREEMPT_DYNAMIC #if defined(CONFIG_HAVE_PREEMPT_DYNAMIC_CALL) #ifndef preempt_schedule_dynamic_enabled #define preempt_schedule_dynamic_enabled … #define preempt_schedule_dynamic_disabled … #endif DEFINE_STATIC_CALL(…); EXPORT_STATIC_CALL_TRAMP(…); #elif defined(CONFIG_HAVE_PREEMPT_DYNAMIC_KEY) static DEFINE_STATIC_KEY_TRUE(sk_dynamic_preempt_schedule); void __sched notrace dynamic_preempt_schedule(void) { if (!static_branch_unlikely(&sk_dynamic_preempt_schedule)) return; preempt_schedule(); } NOKPROBE_SYMBOL(dynamic_preempt_schedule); EXPORT_SYMBOL(dynamic_preempt_schedule); #endif #endif /** * preempt_schedule_notrace - preempt_schedule called by tracing * * The tracing infrastructure uses preempt_enable_notrace to prevent * recursion and tracing preempt enabling caused by the tracing * infrastructure itself. But as tracing can happen in areas coming * from userspace or just about to enter userspace, a preempt enable * can occur before user_exit() is called. This will cause the scheduler * to be called when the system is still in usermode. * * To prevent this, the preempt_enable_notrace will use this function * instead of preempt_schedule() to exit user context if needed before * calling the scheduler. */ asmlinkage __visible void __sched notrace preempt_schedule_notrace(void) { … } EXPORT_SYMBOL_GPL(…); #ifdef CONFIG_PREEMPT_DYNAMIC #if defined(CONFIG_HAVE_PREEMPT_DYNAMIC_CALL) #ifndef preempt_schedule_notrace_dynamic_enabled #define preempt_schedule_notrace_dynamic_enabled … #define preempt_schedule_notrace_dynamic_disabled … #endif DEFINE_STATIC_CALL(…); EXPORT_STATIC_CALL_TRAMP(…); #elif defined(CONFIG_HAVE_PREEMPT_DYNAMIC_KEY) static DEFINE_STATIC_KEY_TRUE(sk_dynamic_preempt_schedule_notrace); void __sched notrace dynamic_preempt_schedule_notrace(void) { if (!static_branch_unlikely(&sk_dynamic_preempt_schedule_notrace)) return; preempt_schedule_notrace(); } NOKPROBE_SYMBOL(dynamic_preempt_schedule_notrace); EXPORT_SYMBOL(dynamic_preempt_schedule_notrace); #endif #endif #endif /* CONFIG_PREEMPTION */ /* * This is the entry point to schedule() from kernel preemption * off of IRQ context. * Note, that this is called and return with IRQs disabled. This will * protect us against recursive calling from IRQ contexts. */ asmlinkage __visible void __sched preempt_schedule_irq(void) { … } int default_wake_function(wait_queue_entry_t *curr, unsigned mode, int wake_flags, void *key) { … } EXPORT_SYMBOL(…); void __setscheduler_prio(struct task_struct *p, int prio) { … } #ifdef CONFIG_RT_MUTEXES /* * Would be more useful with typeof()/auto_type but they don't mix with * bit-fields. Since it's a local thing, use int. Keep the generic sounding * name such that if someone were to implement this function we get to compare * notes. */ #define fetch_and_set(x, v) … void rt_mutex_pre_schedule(void) { … } void rt_mutex_schedule(void) { … } void rt_mutex_post_schedule(void) { … } /* * rt_mutex_setprio - set the current priority of a task * @p: task to boost * @pi_task: donor task * * This function changes the 'effective' priority of a task. It does * not touch ->normal_prio like __setscheduler(). * * Used by the rt_mutex code to implement priority inheritance * logic. Call site only calls if the priority of the task changed. */ void rt_mutex_setprio(struct task_struct *p, struct task_struct *pi_task) { … } #endif #if !defined(CONFIG_PREEMPTION) || defined(CONFIG_PREEMPT_DYNAMIC) int __sched __cond_resched(void) { … } EXPORT_SYMBOL(…); #endif #ifdef CONFIG_PREEMPT_DYNAMIC #if defined(CONFIG_HAVE_PREEMPT_DYNAMIC_CALL) #define cond_resched_dynamic_enabled … #define cond_resched_dynamic_disabled … DEFINE_STATIC_CALL_RET0(…); EXPORT_STATIC_CALL_TRAMP(…); #define might_resched_dynamic_enabled … #define might_resched_dynamic_disabled … DEFINE_STATIC_CALL_RET0(…); EXPORT_STATIC_CALL_TRAMP(…); #elif defined(CONFIG_HAVE_PREEMPT_DYNAMIC_KEY) static DEFINE_STATIC_KEY_FALSE(sk_dynamic_cond_resched); int __sched dynamic_cond_resched(void) { klp_sched_try_switch(); if (!static_branch_unlikely(&sk_dynamic_cond_resched)) return 0; return __cond_resched(); } EXPORT_SYMBOL(dynamic_cond_resched); static DEFINE_STATIC_KEY_FALSE(sk_dynamic_might_resched); int __sched dynamic_might_resched(void) { if (!static_branch_unlikely(&sk_dynamic_might_resched)) return 0; return __cond_resched(); } EXPORT_SYMBOL(dynamic_might_resched); #endif #endif /* * __cond_resched_lock() - if a reschedule is pending, drop the given lock, * call schedule, and on return reacquire the lock. * * This works OK both with and without CONFIG_PREEMPTION. We do strange low-level * operations here to prevent schedule() from being called twice (once via * spin_unlock(), once by hand). */ int __cond_resched_lock(spinlock_t *lock) { … } EXPORT_SYMBOL(…); int __cond_resched_rwlock_read(rwlock_t *lock) { … } EXPORT_SYMBOL(…); int __cond_resched_rwlock_write(rwlock_t *lock) { … } EXPORT_SYMBOL(…); #ifdef CONFIG_PREEMPT_DYNAMIC #ifdef CONFIG_GENERIC_ENTRY #include <linux/entry-common.h> #endif /* * SC:cond_resched * SC:might_resched * SC:preempt_schedule * SC:preempt_schedule_notrace * SC:irqentry_exit_cond_resched * * * NONE: * cond_resched <- __cond_resched * might_resched <- RET0 * preempt_schedule <- NOP * preempt_schedule_notrace <- NOP * irqentry_exit_cond_resched <- NOP * * VOLUNTARY: * cond_resched <- __cond_resched * might_resched <- __cond_resched * preempt_schedule <- NOP * preempt_schedule_notrace <- NOP * irqentry_exit_cond_resched <- NOP * * FULL: * cond_resched <- RET0 * might_resched <- RET0 * preempt_schedule <- preempt_schedule * preempt_schedule_notrace <- preempt_schedule_notrace * irqentry_exit_cond_resched <- irqentry_exit_cond_resched */ enum { … }; int preempt_dynamic_mode = …; int sched_dynamic_mode(const char *str) { … } #if defined(CONFIG_HAVE_PREEMPT_DYNAMIC_CALL) #define preempt_dynamic_enable(f) … #define preempt_dynamic_disable(f) … #elif defined(CONFIG_HAVE_PREEMPT_DYNAMIC_KEY) #define preempt_dynamic_enable … #define preempt_dynamic_disable … #else #error "Unsupported PREEMPT_DYNAMIC mechanism" #endif static DEFINE_MUTEX(sched_dynamic_mutex); static bool klp_override; static void __sched_dynamic_update(int mode) { … } void sched_dynamic_update(int mode) { … } #ifdef CONFIG_HAVE_PREEMPT_DYNAMIC_CALL static int klp_cond_resched(void) { … } void sched_dynamic_klp_enable(void) { … } void sched_dynamic_klp_disable(void) { … } #endif /* CONFIG_HAVE_PREEMPT_DYNAMIC_CALL */ static int __init setup_preempt_mode(char *str) { … } __setup(…); static void __init preempt_dynamic_init(void) { … } #define PREEMPT_MODEL_ACCESSOR(mode) … PREEMPT_MODEL_ACCESSOR(…); PREEMPT_MODEL_ACCESSOR(…); PREEMPT_MODEL_ACCESSOR(…); #else /* !CONFIG_PREEMPT_DYNAMIC: */ static inline void preempt_dynamic_init(void) { } #endif /* CONFIG_PREEMPT_DYNAMIC */ int io_schedule_prepare(void) { … } void io_schedule_finish(int token) { … } /* * This task is about to go to sleep on IO. Increment rq->nr_iowait so * that process accounting knows that this is a task in IO wait state. */ long __sched io_schedule_timeout(long timeout) { … } EXPORT_SYMBOL(…); void __sched io_schedule(void) { … } EXPORT_SYMBOL(…); void sched_show_task(struct task_struct *p) { … } EXPORT_SYMBOL_GPL(…); static inline bool state_filter_match(unsigned long state_filter, struct task_struct *p) { … } void show_state_filter(unsigned int state_filter) { … } /** * init_idle - set up an idle thread for a given CPU * @idle: task in question * @cpu: CPU the idle task belongs to * * NOTE: this function does not set the idle thread's NEED_RESCHED * flag, to make booting more robust. */ void __init init_idle(struct task_struct *idle, int cpu) { … } #ifdef CONFIG_SMP int cpuset_cpumask_can_shrink(const struct cpumask *cur, const struct cpumask *trial) { … } int task_can_attach(struct task_struct *p) { … } bool sched_smp_initialized __read_mostly; #ifdef CONFIG_NUMA_BALANCING /* Migrate current task p to target_cpu */ int migrate_task_to(struct task_struct *p, int target_cpu) { … } /* * Requeue a task on a given node and accurately track the number of NUMA * tasks on the runqueues */ void sched_setnuma(struct task_struct *p, int nid) { … } #endif /* CONFIG_NUMA_BALANCING */ #ifdef CONFIG_HOTPLUG_CPU /* * Ensure that the idle task is using init_mm right before its CPU goes * offline. */ void idle_task_exit(void) { … } static int __balance_push_cpu_stop(void *arg) { … } static DEFINE_PER_CPU(struct cpu_stop_work, push_work); /* * Ensure we only run per-cpu kthreads once the CPU goes !active. * * This is enabled below SCHED_AP_ACTIVE; when !cpu_active(), but only * effective when the hotplug motion is down. */ static void balance_push(struct rq *rq) { … } static void balance_push_set(int cpu, bool on) { … } /* * Invoked from a CPUs hotplug control thread after the CPU has been marked * inactive. All tasks which are not per CPU kernel threads are either * pushed off this CPU now via balance_push() or placed on a different CPU * during wakeup. Wait until the CPU is quiescent. */ static void balance_hotplug_wait(void) { … } #else static inline void balance_push(struct rq *rq) { } static inline void balance_push_set(int cpu, bool on) { } static inline void balance_hotplug_wait(void) { } #endif /* CONFIG_HOTPLUG_CPU */ void set_rq_online(struct rq *rq) { … } void set_rq_offline(struct rq *rq) { … } static inline void sched_set_rq_online(struct rq *rq, int cpu) { … } static inline void sched_set_rq_offline(struct rq *rq, int cpu) { … } /* * used to mark begin/end of suspend/resume: */ static int num_cpus_frozen; /* * Update cpusets according to cpu_active mask. If cpusets are * disabled, cpuset_update_active_cpus() becomes a simple wrapper * around partition_sched_domains(). * * If we come here as part of a suspend/resume, don't touch cpusets because we * want to restore it back to its original state upon resume anyway. */ static void cpuset_cpu_active(void) { … } static int cpuset_cpu_inactive(unsigned int cpu) { … } static inline void sched_smt_present_inc(int cpu) { … } static inline void sched_smt_present_dec(int cpu) { … } int sched_cpu_activate(unsigned int cpu) { … } int sched_cpu_deactivate(unsigned int cpu) { … } static void sched_rq_cpu_starting(unsigned int cpu) { … } int sched_cpu_starting(unsigned int cpu) { … } #ifdef CONFIG_HOTPLUG_CPU /* * Invoked immediately before the stopper thread is invoked to bring the * CPU down completely. At this point all per CPU kthreads except the * hotplug thread (current) and the stopper thread (inactive) have been * either parked or have been unbound from the outgoing CPU. Ensure that * any of those which might be on the way out are gone. * * If after this point a bound task is being woken on this CPU then the * responsible hotplug callback has failed to do it's job. * sched_cpu_dying() will catch it with the appropriate fireworks. */ int sched_cpu_wait_empty(unsigned int cpu) { … } /* * Since this CPU is going 'away' for a while, fold any nr_active delta we * might have. Called from the CPU stopper task after ensuring that the * stopper is the last running task on the CPU, so nr_active count is * stable. We need to take the tear-down thread which is calling this into * account, so we hand in adjust = 1 to the load calculation. * * Also see the comment "Global load-average calculations". */ static void calc_load_migrate(struct rq *rq) { … } static void dump_rq_tasks(struct rq *rq, const char *loglvl) { … } int sched_cpu_dying(unsigned int cpu) { … } #endif void __init sched_init_smp(void) { … } static int __init migration_init(void) { … } early_initcall(migration_init); #else void __init sched_init_smp(void) { sched_init_granularity(); } #endif /* CONFIG_SMP */ int in_sched_functions(unsigned long addr) { … } #ifdef CONFIG_CGROUP_SCHED /* * Default task group. * Every task in system belongs to this group at bootup. */ struct task_group root_task_group; LIST_HEAD(…); /* Cacheline aligned slab cache for task_group */ static struct kmem_cache *task_group_cache __ro_after_init; #endif void __init sched_init(void) { … } #ifdef CONFIG_DEBUG_ATOMIC_SLEEP void __might_sleep(const char *file, int line) { … } EXPORT_SYMBOL(…); static void print_preempt_disable_ip(int preempt_offset, unsigned long ip) { … } static inline bool resched_offsets_ok(unsigned int offsets) { … } void __might_resched(const char *file, int line, unsigned int offsets) { … } EXPORT_SYMBOL(…); void __cant_sleep(const char *file, int line, int preempt_offset) { … } EXPORT_SYMBOL_GPL(…); #ifdef CONFIG_SMP void __cant_migrate(const char *file, int line) { … } EXPORT_SYMBOL_GPL(…); #endif #endif #ifdef CONFIG_MAGIC_SYSRQ void normalize_rt_tasks(void) { … } #endif /* CONFIG_MAGIC_SYSRQ */ #if defined(CONFIG_KGDB_KDB) /* * These functions are only useful for KDB. * * They can only be called when the whole system has been * stopped - every CPU needs to be quiescent, and no scheduling * activity can take place. Using them for anything else would * be a serious bug, and as a result, they aren't even visible * under any other configuration. */ /** * curr_task - return the current task for a given CPU. * @cpu: the processor in question. * * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED! * * Return: The current task for @cpu. */ struct task_struct *curr_task(int cpu) { … } #endif /* defined(CONFIG_KGDB_KDB) */ #ifdef CONFIG_CGROUP_SCHED /* task_group_lock serializes the addition/removal of task groups */ static DEFINE_SPINLOCK(task_group_lock); static inline void alloc_uclamp_sched_group(struct task_group *tg, struct task_group *parent) { … } static void sched_free_group(struct task_group *tg) { … } static void sched_free_group_rcu(struct rcu_head *rcu) { … } static void sched_unregister_group(struct task_group *tg) { … } /* allocate runqueue etc for a new task group */ struct task_group *sched_create_group(struct task_group *parent) { … } void sched_online_group(struct task_group *tg, struct task_group *parent) { … } /* RCU callback to free various structures associated with a task group */ static void sched_unregister_group_rcu(struct rcu_head *rhp) { … } void sched_destroy_group(struct task_group *tg) { … } void sched_release_group(struct task_group *tg) { … } static struct task_group *sched_get_task_group(struct task_struct *tsk) { … } static void sched_change_group(struct task_struct *tsk, struct task_group *group) { … } /* * Change task's runqueue when it moves between groups. * * The caller of this function should have put the task in its new group by * now. This function just updates tsk->se.cfs_rq and tsk->se.parent to reflect * its new group. */ void sched_move_task(struct task_struct *tsk) { … } static inline struct task_group *css_tg(struct cgroup_subsys_state *css) { … } static struct cgroup_subsys_state * cpu_cgroup_css_alloc(struct cgroup_subsys_state *parent_css) { … } /* Expose task group only after completing cgroup initialization */ static int cpu_cgroup_css_online(struct cgroup_subsys_state *css) { … } static void cpu_cgroup_css_released(struct cgroup_subsys_state *css) { … } static void cpu_cgroup_css_free(struct cgroup_subsys_state *css) { … } #ifdef CONFIG_RT_GROUP_SCHED static int cpu_cgroup_can_attach(struct cgroup_taskset *tset) { … } #endif static void cpu_cgroup_attach(struct cgroup_taskset *tset) { … } #ifdef CONFIG_UCLAMP_TASK_GROUP static void cpu_util_update_eff(struct cgroup_subsys_state *css) { … } /* * Integer 10^N with a given N exponent by casting to integer the literal "1eN" * C expression. Since there is no way to convert a macro argument (N) into a * character constant, use two levels of macros. */ #define _POW10(exp) … #define POW10(exp) … struct uclamp_request { … }; static inline struct uclamp_request capacity_from_percent(char *buf) { … } static ssize_t cpu_uclamp_write(struct kernfs_open_file *of, char *buf, size_t nbytes, loff_t off, enum uclamp_id clamp_id) { … } static ssize_t cpu_uclamp_min_write(struct kernfs_open_file *of, char *buf, size_t nbytes, loff_t off) { … } static ssize_t cpu_uclamp_max_write(struct kernfs_open_file *of, char *buf, size_t nbytes, loff_t off) { … } static inline void cpu_uclamp_print(struct seq_file *sf, enum uclamp_id clamp_id) { … } static int cpu_uclamp_min_show(struct seq_file *sf, void *v) { … } static int cpu_uclamp_max_show(struct seq_file *sf, void *v) { … } #endif /* CONFIG_UCLAMP_TASK_GROUP */ #ifdef CONFIG_FAIR_GROUP_SCHED static int cpu_shares_write_u64(struct cgroup_subsys_state *css, struct cftype *cftype, u64 shareval) { … } static u64 cpu_shares_read_u64(struct cgroup_subsys_state *css, struct cftype *cft) { … } #ifdef CONFIG_CFS_BANDWIDTH static DEFINE_MUTEX(cfs_constraints_mutex); const u64 max_cfs_quota_period = …; /* 1s */ static const u64 min_cfs_quota_period = …; /* 1ms */ /* More than 203 days if BW_SHIFT equals 20. */ static const u64 max_cfs_runtime = …; static int __cfs_schedulable(struct task_group *tg, u64 period, u64 runtime); static int tg_set_cfs_bandwidth(struct task_group *tg, u64 period, u64 quota, u64 burst) { … } static int tg_set_cfs_quota(struct task_group *tg, long cfs_quota_us) { … } static long tg_get_cfs_quota(struct task_group *tg) { … } static int tg_set_cfs_period(struct task_group *tg, long cfs_period_us) { … } static long tg_get_cfs_period(struct task_group *tg) { … } static int tg_set_cfs_burst(struct task_group *tg, long cfs_burst_us) { … } static long tg_get_cfs_burst(struct task_group *tg) { … } static s64 cpu_cfs_quota_read_s64(struct cgroup_subsys_state *css, struct cftype *cft) { … } static int cpu_cfs_quota_write_s64(struct cgroup_subsys_state *css, struct cftype *cftype, s64 cfs_quota_us) { … } static u64 cpu_cfs_period_read_u64(struct cgroup_subsys_state *css, struct cftype *cft) { … } static int cpu_cfs_period_write_u64(struct cgroup_subsys_state *css, struct cftype *cftype, u64 cfs_period_us) { … } static u64 cpu_cfs_burst_read_u64(struct cgroup_subsys_state *css, struct cftype *cft) { … } static int cpu_cfs_burst_write_u64(struct cgroup_subsys_state *css, struct cftype *cftype, u64 cfs_burst_us) { … } struct cfs_schedulable_data { … }; /* * normalize group quota/period to be quota/max_period * note: units are usecs */ static u64 normalize_cfs_quota(struct task_group *tg, struct cfs_schedulable_data *d) { … } static int tg_cfs_schedulable_down(struct task_group *tg, void *data) { … } static int __cfs_schedulable(struct task_group *tg, u64 period, u64 quota) { … } static int cpu_cfs_stat_show(struct seq_file *sf, void *v) { … } static u64 throttled_time_self(struct task_group *tg) { … } static int cpu_cfs_local_stat_show(struct seq_file *sf, void *v) { … } #endif /* CONFIG_CFS_BANDWIDTH */ #endif /* CONFIG_FAIR_GROUP_SCHED */ #ifdef CONFIG_RT_GROUP_SCHED static int cpu_rt_runtime_write(struct cgroup_subsys_state *css, struct cftype *cft, s64 val) { … } static s64 cpu_rt_runtime_read(struct cgroup_subsys_state *css, struct cftype *cft) { … } static int cpu_rt_period_write_uint(struct cgroup_subsys_state *css, struct cftype *cftype, u64 rt_period_us) { … } static u64 cpu_rt_period_read_uint(struct cgroup_subsys_state *css, struct cftype *cft) { … } #endif /* CONFIG_RT_GROUP_SCHED */ #ifdef CONFIG_FAIR_GROUP_SCHED static s64 cpu_idle_read_s64(struct cgroup_subsys_state *css, struct cftype *cft) { … } static int cpu_idle_write_s64(struct cgroup_subsys_state *css, struct cftype *cft, s64 idle) { … } #endif static struct cftype cpu_legacy_files[] = …; static int cpu_extra_stat_show(struct seq_file *sf, struct cgroup_subsys_state *css) { … } static int cpu_local_stat_show(struct seq_file *sf, struct cgroup_subsys_state *css) { … } #ifdef CONFIG_FAIR_GROUP_SCHED static u64 cpu_weight_read_u64(struct cgroup_subsys_state *css, struct cftype *cft) { … } static int cpu_weight_write_u64(struct cgroup_subsys_state *css, struct cftype *cft, u64 weight) { … } static s64 cpu_weight_nice_read_s64(struct cgroup_subsys_state *css, struct cftype *cft) { … } static int cpu_weight_nice_write_s64(struct cgroup_subsys_state *css, struct cftype *cft, s64 nice) { … } #endif static void __maybe_unused cpu_period_quota_print(struct seq_file *sf, long period, long quota) { … } /* caller should put the current value in *@periodp before calling */ static int __maybe_unused cpu_period_quota_parse(char *buf, u64 *periodp, u64 *quotap) { … } #ifdef CONFIG_CFS_BANDWIDTH static int cpu_max_show(struct seq_file *sf, void *v) { … } static ssize_t cpu_max_write(struct kernfs_open_file *of, char *buf, size_t nbytes, loff_t off) { … } #endif static struct cftype cpu_files[] = …; struct cgroup_subsys cpu_cgrp_subsys = …; #endif /* CONFIG_CGROUP_SCHED */ void dump_cpu_task(int cpu) { … } /* * Nice levels are multiplicative, with a gentle 10% change for every * nice level changed. I.e. when a CPU-bound task goes from nice 0 to * nice 1, it will get ~10% less CPU time than another CPU-bound task * that remained on nice 0. * * The "10% effect" is relative and cumulative: from _any_ nice level, * if you go up 1 level, it's -10% CPU usage, if you go down 1 level * it's +10% CPU usage. (to achieve that we use a multiplier of 1.25. * If a task goes up by ~10% and another task goes down by ~10% then * the relative distance between them is ~25%.) */ const int sched_prio_to_weight[40] = …; /* * Inverse (2^32/x) values of the sched_prio_to_weight[] array, pre-calculated. * * In cases where the weight does not change often, we can use the * pre-calculated inverse to speed up arithmetics by turning divisions * into multiplications: */ const u32 sched_prio_to_wmult[40] = …; void call_trace_sched_update_nr_running(struct rq *rq, int count) { … } #ifdef CONFIG_SCHED_MM_CID /* * @cid_lock: Guarantee forward-progress of cid allocation. * * Concurrency ID allocation within a bitmap is mostly lock-free. The cid_lock * is only used when contention is detected by the lock-free allocation so * forward progress can be guaranteed. */ DEFINE_RAW_SPINLOCK(…); /* * @use_cid_lock: Select cid allocation behavior: lock-free vs spinlock. * * When @use_cid_lock is 0, the cid allocation is lock-free. When contention is * detected, it is set to 1 to ensure that all newly coming allocations are * serialized by @cid_lock until the allocation which detected contention * completes and sets @use_cid_lock back to 0. This guarantees forward progress * of a cid allocation. */ int use_cid_lock; /* * mm_cid remote-clear implements a lock-free algorithm to clear per-mm/cpu cid * concurrently with respect to the execution of the source runqueue context * switch. * * There is one basic properties we want to guarantee here: * * (1) Remote-clear should _never_ mark a per-cpu cid UNSET when it is actively * used by a task. That would lead to concurrent allocation of the cid and * userspace corruption. * * Provide this guarantee by introducing a Dekker memory ordering to guarantee * that a pair of loads observe at least one of a pair of stores, which can be * shown as: * * X = Y = 0 * * w[X]=1 w[Y]=1 * MB MB * r[Y]=y r[X]=x * * Which guarantees that x==0 && y==0 is impossible. But rather than using * values 0 and 1, this algorithm cares about specific state transitions of the * runqueue current task (as updated by the scheduler context switch), and the * per-mm/cpu cid value. * * Let's introduce task (Y) which has task->mm == mm and task (N) which has * task->mm != mm for the rest of the discussion. There are two scheduler state * transitions on context switch we care about: * * (TSA) Store to rq->curr with transition from (N) to (Y) * * (TSB) Store to rq->curr with transition from (Y) to (N) * * On the remote-clear side, there is one transition we care about: * * (TMA) cmpxchg to *pcpu_cid to set the LAZY flag * * There is also a transition to UNSET state which can be performed from all * sides (scheduler, remote-clear). It is always performed with a cmpxchg which * guarantees that only a single thread will succeed: * * (TMB) cmpxchg to *pcpu_cid to mark UNSET * * Just to be clear, what we do _not_ want to happen is a transition to UNSET * when a thread is actively using the cid (property (1)). * * Let's looks at the relevant combinations of TSA/TSB, and TMA transitions. * * Scenario A) (TSA)+(TMA) (from next task perspective) * * CPU0 CPU1 * * Context switch CS-1 Remote-clear * - store to rq->curr: (N)->(Y) (TSA) - cmpxchg to *pcpu_id to LAZY (TMA) * (implied barrier after cmpxchg) * - switch_mm_cid() * - memory barrier (see switch_mm_cid() * comment explaining how this barrier * is combined with other scheduler * barriers) * - mm_cid_get (next) * - READ_ONCE(*pcpu_cid) - rcu_dereference(src_rq->curr) * * This Dekker ensures that either task (Y) is observed by the * rcu_dereference() or the LAZY flag is observed by READ_ONCE(), or both are * observed. * * If task (Y) store is observed by rcu_dereference(), it means that there is * still an active task on the cpu. Remote-clear will therefore not transition * to UNSET, which fulfills property (1). * * If task (Y) is not observed, but the lazy flag is observed by READ_ONCE(), * it will move its state to UNSET, which clears the percpu cid perhaps * uselessly (which is not an issue for correctness). Because task (Y) is not * observed, CPU1 can move ahead to set the state to UNSET. Because moving * state to UNSET is done with a cmpxchg expecting that the old state has the * LAZY flag set, only one thread will successfully UNSET. * * If both states (LAZY flag and task (Y)) are observed, the thread on CPU0 * will observe the LAZY flag and transition to UNSET (perhaps uselessly), and * CPU1 will observe task (Y) and do nothing more, which is fine. * * What we are effectively preventing with this Dekker is a scenario where * neither LAZY flag nor store (Y) are observed, which would fail property (1) * because this would UNSET a cid which is actively used. */ void sched_mm_cid_migrate_from(struct task_struct *t) { … } static int __sched_mm_cid_migrate_from_fetch_cid(struct rq *src_rq, struct task_struct *t, struct mm_cid *src_pcpu_cid) { … } static int __sched_mm_cid_migrate_from_try_steal_cid(struct rq *src_rq, struct task_struct *t, struct mm_cid *src_pcpu_cid, int src_cid) { … } /* * Migration to dst cpu. Called with dst_rq lock held. * Interrupts are disabled, which keeps the window of cid ownership without the * source rq lock held small. */ void sched_mm_cid_migrate_to(struct rq *dst_rq, struct task_struct *t) { … } static void sched_mm_cid_remote_clear(struct mm_struct *mm, struct mm_cid *pcpu_cid, int cpu) { … } static void sched_mm_cid_remote_clear_old(struct mm_struct *mm, int cpu) { … } static void sched_mm_cid_remote_clear_weight(struct mm_struct *mm, int cpu, int weight) { … } static void task_mm_cid_work(struct callback_head *work) { … } void init_sched_mm_cid(struct task_struct *t) { … } void task_tick_mm_cid(struct rq *rq, struct task_struct *curr) { … } void sched_mm_cid_exit_signals(struct task_struct *t) { … } void sched_mm_cid_before_execve(struct task_struct *t) { … } void sched_mm_cid_after_execve(struct task_struct *t) { … } void sched_mm_cid_fork(struct task_struct *t) { … } #endif