xref: /linux/kernel/sched/ext/idle.c (revision 12da4723b679374ed914dc79f1c33faae212811a)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * BPF extensible scheduler class: Documentation/scheduler/sched-ext.rst
4  *
5  * Built-in idle CPU tracking policy.
6  *
7  * Copyright (c) 2022 Meta Platforms, Inc. and affiliates.
8  * Copyright (c) 2022 Tejun Heo <tj@kernel.org>
9  * Copyright (c) 2022 David Vernet <dvernet@meta.com>
10  * Copyright (c) 2024 Andrea Righi <arighi@nvidia.com>
11  */
12 #include "internal.h"
13 #include "cid.h"
14 #include "idle.h"
15 #include "sub.h"
16 
17 /* Enable/disable built-in idle CPU selection policy */
18 static DEFINE_STATIC_KEY_FALSE(scx_builtin_idle_enabled);
19 
20 /* Enable/disable per-node idle cpumasks */
21 static DEFINE_STATIC_KEY_FALSE(scx_builtin_idle_per_node);
22 
23 /* Enable/disable LLC aware optimizations */
24 static DEFINE_STATIC_KEY_FALSE(scx_selcpu_topo_llc);
25 
26 /* Enable/disable NUMA aware optimizations */
27 static DEFINE_STATIC_KEY_FALSE(scx_selcpu_topo_numa);
28 
29 /*
30  * cpumasks to track idle CPUs within each NUMA node.
31  *
32  * If SCX_OPS_BUILTIN_IDLE_PER_NODE is not enabled, a single global cpumask
33  * from is used to track all the idle CPUs in the system.
34  */
35 struct scx_idle_cpus {
36 	cpumask_var_t cpu;
37 	cpumask_var_t smt;
38 };
39 
40 /*
41  * Global host-wide idle cpumasks (used when SCX_OPS_BUILTIN_IDLE_PER_NODE
42  * is not enabled).
43  */
44 static struct scx_idle_cpus scx_idle_global_masks;
45 
46 /*
47  * Per-node idle cpumasks.
48  */
49 static struct scx_idle_cpus **scx_idle_node_masks;
50 
51 /*
52  * Local per-CPU cpumasks (used to generate temporary idle cpumasks).
53  */
54 static DEFINE_PER_CPU(cpumask_var_t, local_idle_cpumask);
55 static DEFINE_PER_CPU(cpumask_var_t, local_llc_idle_cpumask);
56 static DEFINE_PER_CPU(cpumask_var_t, local_numa_idle_cpumask);
57 
58 /*
59  * Return the idle masks associated to a target @node.
60  *
61  * NUMA_NO_NODE identifies the global idle cpumask.
62  */
63 static struct scx_idle_cpus *idle_cpumask(int node)
64 {
65 	return node == NUMA_NO_NODE ? &scx_idle_global_masks : scx_idle_node_masks[node];
66 }
67 
68 /*
69  * Returns the NUMA node ID associated with a @cpu, or NUMA_NO_NODE if
70  * per-node idle cpumasks are disabled.
71  */
72 static int scx_cpu_node_if_enabled(int cpu)
73 {
74 	if (!static_branch_maybe(CONFIG_NUMA, &scx_builtin_idle_per_node))
75 		return NUMA_NO_NODE;
76 
77 	return cpu_to_node(cpu);
78 }
79 
80 static bool scx_idle_test_and_clear_cpu(int cpu)
81 {
82 	int node = scx_cpu_node_if_enabled(cpu);
83 	struct cpumask *idle_cpus = idle_cpumask(node)->cpu;
84 
85 	/*
86 	 * SMT mask should be cleared whether we can claim @cpu or not. The SMT
87 	 * cluster is not wholly idle either way. This also prevents
88 	 * scx_pick_idle_cpu() from getting caught in an infinite loop.
89 	 */
90 	if (sched_smt_active()) {
91 		const struct cpumask *smt = cpu_smt_mask(cpu);
92 		struct cpumask *idle_smts = idle_cpumask(node)->smt;
93 
94 		/*
95 		 * If offline, @cpu is not its own sibling and
96 		 * scx_pick_idle_cpu() can get caught in an infinite loop as
97 		 * @cpu is never cleared from the idle SMT mask. Ensure that
98 		 * @cpu is eventually cleared.
99 		 *
100 		 * NOTE: Use cpumask_intersects() and cpumask_test_cpu() to
101 		 * reduce memory writes, which may help alleviate cache
102 		 * coherence pressure.
103 		 */
104 		if (cpumask_intersects(smt, idle_smts))
105 			cpumask_andnot(idle_smts, idle_smts, smt);
106 		else if (cpumask_test_cpu(cpu, idle_smts))
107 			__cpumask_clear_cpu(cpu, idle_smts);
108 	}
109 
110 	return cpumask_test_and_clear_cpu(cpu, idle_cpus);
111 }
112 
113 /*
114  * Pick an idle CPU in a specific NUMA node.
115  */
116 static s32 pick_idle_cpu_in_node(const struct cpumask *cpus_allowed, int node, u64 flags)
117 {
118 	int cpu;
119 
120 retry:
121 	if (sched_smt_active()) {
122 		cpu = cpumask_any_and_distribute(idle_cpumask(node)->smt, cpus_allowed);
123 		if (cpu < nr_cpu_ids)
124 			goto found;
125 
126 		if (flags & SCX_PICK_IDLE_CORE)
127 			return -EBUSY;
128 	}
129 
130 	cpu = cpumask_any_and_distribute(idle_cpumask(node)->cpu, cpus_allowed);
131 	if (cpu >= nr_cpu_ids)
132 		return -EBUSY;
133 
134 found:
135 	if (scx_idle_test_and_clear_cpu(cpu))
136 		return cpu;
137 	else
138 		goto retry;
139 }
140 
141 #ifdef CONFIG_NUMA
142 /*
143  * Tracks nodes that have not yet been visited when searching for an idle
144  * CPU across all available nodes.
145  */
146 static DEFINE_PER_CPU(nodemask_t, per_cpu_unvisited);
147 
148 /*
149  * Search for an idle CPU across all nodes, excluding @node.
150  */
151 static s32 pick_idle_cpu_from_online_nodes(const struct cpumask *cpus_allowed, int node, u64 flags)
152 {
153 	nodemask_t *unvisited;
154 	s32 cpu = -EBUSY;
155 
156 	preempt_disable();
157 	unvisited = this_cpu_ptr(&per_cpu_unvisited);
158 
159 	/*
160 	 * Restrict the search to the online nodes (excluding the current
161 	 * node that has been visited already).
162 	 */
163 	nodes_copy(*unvisited, node_states[N_ONLINE]);
164 	node_clear(node, *unvisited);
165 
166 	/*
167 	 * Traverse all nodes in order of increasing distance, starting
168 	 * from @node.
169 	 *
170 	 * This loop is O(N^2), with N being the amount of NUMA nodes,
171 	 * which might be quite expensive in large NUMA systems. However,
172 	 * this complexity comes into play only when a scheduler enables
173 	 * SCX_OPS_BUILTIN_IDLE_PER_NODE and it's requesting an idle CPU
174 	 * without specifying a target NUMA node, so it shouldn't be a
175 	 * bottleneck is most cases.
176 	 *
177 	 * As a future optimization we may want to cache the list of nodes
178 	 * in a per-node array, instead of actually traversing them every
179 	 * time.
180 	 */
181 	for_each_node_numadist(node, *unvisited) {
182 		cpu = pick_idle_cpu_in_node(cpus_allowed, node, flags);
183 		if (cpu >= 0)
184 			break;
185 	}
186 	preempt_enable();
187 
188 	return cpu;
189 }
190 #else
191 static inline s32
192 pick_idle_cpu_from_online_nodes(const struct cpumask *cpus_allowed, int node, u64 flags)
193 {
194 	return -EBUSY;
195 }
196 #endif
197 
198 /*
199  * Find an idle CPU in the system, starting from @node.
200  */
201 static s32 scx_pick_idle_cpu(const struct cpumask *cpus_allowed, int node, u64 flags)
202 {
203 	s32 cpu;
204 
205 	/*
206 	 * Always search in the starting node first (this is an
207 	 * optimization that can save some cycles even when the search is
208 	 * not limited to a single node).
209 	 */
210 	cpu = pick_idle_cpu_in_node(cpus_allowed, node, flags);
211 	if (cpu >= 0)
212 		return cpu;
213 
214 	/*
215 	 * Stop the search if we are using only a single global cpumask
216 	 * (NUMA_NO_NODE) or if the search is restricted to the first node
217 	 * only.
218 	 */
219 	if (node == NUMA_NO_NODE || flags & SCX_PICK_IDLE_IN_NODE)
220 		return -EBUSY;
221 
222 	/*
223 	 * Extend the search to the other online nodes.
224 	 */
225 	return pick_idle_cpu_from_online_nodes(cpus_allowed, node, flags);
226 }
227 
228 /*
229  * Return the amount of CPUs in the same LLC domain of @cpu (or zero if the LLC
230  * domain is not defined).
231  */
232 static unsigned int llc_weight(s32 cpu)
233 {
234 	struct sched_domain *sd;
235 
236 	sd = rcu_dereference(per_cpu(sd_llc, cpu));
237 	if (!sd)
238 		return 0;
239 
240 	return sd->span_weight;
241 }
242 
243 /*
244  * Return the cpumask representing the LLC domain of @cpu (or NULL if the LLC
245  * domain is not defined).
246  */
247 static struct cpumask *llc_span(s32 cpu)
248 {
249 	struct sched_domain *sd;
250 
251 	sd = rcu_dereference(per_cpu(sd_llc, cpu));
252 	if (!sd)
253 		return NULL;
254 
255 	return sched_domain_span(sd);
256 }
257 
258 /*
259  * Return the amount of CPUs in the same NUMA domain of @cpu (or zero if the
260  * NUMA domain is not defined).
261  */
262 static unsigned int numa_weight(s32 cpu)
263 {
264 	struct sched_domain *sd;
265 	struct sched_group *sg;
266 
267 	sd = rcu_dereference(per_cpu(sd_numa, cpu));
268 	if (!sd)
269 		return 0;
270 	sg = sd->groups;
271 	if (!sg)
272 		return 0;
273 
274 	return sg->group_weight;
275 }
276 
277 /*
278  * Return the cpumask representing the NUMA domain of @cpu (or NULL if the NUMA
279  * domain is not defined).
280  */
281 static struct cpumask *numa_span(s32 cpu)
282 {
283 	struct sched_domain *sd;
284 	struct sched_group *sg;
285 
286 	sd = rcu_dereference(per_cpu(sd_numa, cpu));
287 	if (!sd)
288 		return NULL;
289 	sg = sd->groups;
290 	if (!sg)
291 		return NULL;
292 
293 	return sched_group_span(sg);
294 }
295 
296 /*
297  * Return true if the LLC domains do not perfectly overlap with the NUMA
298  * domains, false otherwise.
299  */
300 static bool llc_numa_mismatch(void)
301 {
302 	int cpu;
303 
304 	/*
305 	 * We need to scan all online CPUs to verify whether their scheduling
306 	 * domains overlap.
307 	 *
308 	 * While it is rare to encounter architectures with asymmetric NUMA
309 	 * topologies, CPU hotplugging or virtualized environments can result
310 	 * in asymmetric configurations.
311 	 *
312 	 * For example:
313 	 *
314 	 *  NUMA 0:
315 	 *    - LLC 0: cpu0..cpu7
316 	 *    - LLC 1: cpu8..cpu15 [offline]
317 	 *
318 	 *  NUMA 1:
319 	 *    - LLC 0: cpu16..cpu23
320 	 *    - LLC 1: cpu24..cpu31
321 	 *
322 	 * In this case, if we only check the first online CPU (cpu0), we might
323 	 * incorrectly assume that the LLC and NUMA domains are fully
324 	 * overlapping, which is incorrect (as NUMA 1 has two distinct LLC
325 	 * domains).
326 	 */
327 	for_each_online_cpu(cpu)
328 		if (llc_weight(cpu) != numa_weight(cpu))
329 			return true;
330 
331 	return false;
332 }
333 
334 /*
335  * Initialize topology-aware scheduling.
336  *
337  * Detect if the system has multiple LLC or multiple NUMA domains and enable
338  * cache-aware / NUMA-aware scheduling optimizations in the default CPU idle
339  * selection policy.
340  *
341  * Assumption: the kernel's internal topology representation assumes that each
342  * CPU belongs to a single LLC domain, and that each LLC domain is entirely
343  * contained within a single NUMA node.
344  */
345 void scx_idle_update_selcpu_topology(struct sched_ext_ops *ops)
346 {
347 	bool enable_llc = false, enable_numa = false;
348 	unsigned int nr_cpus;
349 	s32 cpu = cpumask_first(cpu_online_mask);
350 
351 	/*
352 	 * Enable LLC domain optimization only when there are multiple LLC
353 	 * domains among the online CPUs. If all online CPUs are part of a
354 	 * single LLC domain, the idle CPU selection logic can choose any
355 	 * online CPU without bias.
356 	 *
357 	 * Note that it is sufficient to check the LLC domain of the first
358 	 * online CPU to determine whether a single LLC domain includes all
359 	 * CPUs.
360 	 */
361 	rcu_read_lock();
362 	nr_cpus = llc_weight(cpu);
363 	if (nr_cpus > 0) {
364 		if (nr_cpus < num_online_cpus())
365 			enable_llc = true;
366 		pr_debug("sched_ext: LLC=%*pb weight=%u\n",
367 			 cpumask_pr_args(llc_span(cpu)), llc_weight(cpu));
368 	}
369 
370 	/*
371 	 * Enable NUMA optimization only when there are multiple NUMA domains
372 	 * among the online CPUs and the NUMA domains don't perfectly overlap
373 	 * with the LLC domains.
374 	 *
375 	 * If all CPUs belong to the same NUMA node and the same LLC domain,
376 	 * enabling both NUMA and LLC optimizations is unnecessary, as checking
377 	 * for an idle CPU in the same domain twice is redundant.
378 	 *
379 	 * If SCX_OPS_BUILTIN_IDLE_PER_NODE is enabled ignore the NUMA
380 	 * optimization, as we would naturally select idle CPUs within
381 	 * specific NUMA nodes querying the corresponding per-node cpumask.
382 	 */
383 	if (!(ops->flags & SCX_OPS_BUILTIN_IDLE_PER_NODE)) {
384 		nr_cpus = numa_weight(cpu);
385 		if (nr_cpus > 0) {
386 			if (nr_cpus < num_online_cpus() && llc_numa_mismatch())
387 				enable_numa = true;
388 			pr_debug("sched_ext: NUMA=%*pb weight=%u\n",
389 				 cpumask_pr_args(numa_span(cpu)), nr_cpus);
390 		}
391 	}
392 	rcu_read_unlock();
393 
394 	pr_debug("sched_ext: LLC idle selection %s\n",
395 		 str_enabled_disabled(enable_llc));
396 	pr_debug("sched_ext: NUMA idle selection %s\n",
397 		 str_enabled_disabled(enable_numa));
398 
399 	if (enable_llc)
400 		static_branch_enable_cpuslocked(&scx_selcpu_topo_llc);
401 	else
402 		static_branch_disable_cpuslocked(&scx_selcpu_topo_llc);
403 	if (enable_numa)
404 		static_branch_enable_cpuslocked(&scx_selcpu_topo_numa);
405 	else
406 		static_branch_disable_cpuslocked(&scx_selcpu_topo_numa);
407 }
408 
409 /*
410  * Return true if @p can run on all possible CPUs, false otherwise.
411  */
412 static inline bool task_affinity_all(const struct task_struct *p)
413 {
414 	return p->nr_cpus_allowed >= num_possible_cpus();
415 }
416 
417 /*
418  * Built-in CPU idle selection policy:
419  *
420  * 1. Prioritize full-idle cores:
421  *   - always prioritize CPUs from fully idle cores (both logical CPUs are
422  *     idle) to avoid interference caused by SMT.
423  *
424  * 2. Reuse the same CPU:
425  *   - prefer the last used CPU to take advantage of cached data (L1, L2) and
426  *     branch prediction optimizations.
427  *
428  * 3. Prefer @prev_cpu's SMT sibling:
429  *   - if @prev_cpu is busy and no fully idle core is available, try to
430  *     place the task on an idle SMT sibling of @prev_cpu; keeping the
431  *     task on the same core makes migration cheaper, preserves L1 cache
432  *     locality and reduces wakeup latency.
433  *
434  * 4. Pick a CPU within the same LLC (Last-Level Cache):
435  *   - if the above conditions aren't met, pick a CPU that shares the same
436  *     LLC, if the LLC domain is a subset of @cpus_allowed, to maintain
437  *     cache locality.
438  *
439  * 5. Pick a CPU within the same NUMA node, if enabled:
440  *   - choose a CPU from the same NUMA node, if the node cpumask is a
441  *     subset of @cpus_allowed, to reduce memory access latency.
442  *
443  * 6. Pick any idle CPU within the @cpus_allowed domain.
444  *
445  * Step 4 and 5 are performed only if the system has, respectively,
446  * multiple LLCs / multiple NUMA nodes (see scx_selcpu_topo_llc and
447  * scx_selcpu_topo_numa) and they don't contain the same subset of CPUs.
448  *
449  * If %SCX_OPS_BUILTIN_IDLE_PER_NODE is enabled, the search will always
450  * begin in @prev_cpu's node and proceed to other nodes in order of
451  * increasing distance.
452  *
453  * Return the picked CPU if idle, or a negative value otherwise.
454  *
455  * NOTE: tasks that can only run on 1 CPU are excluded by this logic, because
456  * we never call ops.select_cpu() for them, see select_task_rq().
457  */
458 s32 scx_select_cpu_dfl(struct task_struct *p, s32 prev_cpu, u64 wake_flags,
459 		       const struct cpumask *cpus_allowed, u64 flags)
460 {
461 	const struct cpumask *llc_cpus = NULL, *numa_cpus = NULL;
462 	const struct cpumask *allowed = cpus_allowed ?: p->cpus_ptr;
463 	int node = scx_cpu_node_if_enabled(prev_cpu);
464 	bool is_prev_allowed;
465 	s32 cpu;
466 
467 	preempt_disable();
468 
469 	/*
470 	 * Determine the subset of CPUs usable by @p within @cpus_allowed.
471 	 */
472 	if (allowed != p->cpus_ptr) {
473 		struct cpumask *local_cpus = this_cpu_cpumask_var_ptr(local_idle_cpumask);
474 
475 		if (task_affinity_all(p)) {
476 			allowed = cpus_allowed;
477 		} else if (cpumask_and(local_cpus, cpus_allowed, p->cpus_ptr)) {
478 			allowed = local_cpus;
479 		} else {
480 			cpu = -EBUSY;
481 			goto out_enable;
482 		}
483 	}
484 
485 	/*
486 	 * Check whether @prev_cpu is still within the allowed set. If not,
487 	 * we can still try selecting a nearby CPU.
488 	 */
489 	is_prev_allowed = cpumask_test_cpu(prev_cpu, allowed);
490 
491 	/*
492 	 * This is necessary to protect llc_cpus.
493 	 */
494 	rcu_read_lock();
495 
496 	/*
497 	 * Determine the subset of CPUs that the task can use in its
498 	 * current LLC and node.
499 	 *
500 	 * If the task can run on all CPUs, use the node and LLC cpumasks
501 	 * directly.
502 	 */
503 	if (static_branch_maybe(CONFIG_NUMA, &scx_selcpu_topo_numa)) {
504 		struct cpumask *local_cpus = this_cpu_cpumask_var_ptr(local_numa_idle_cpumask);
505 		const struct cpumask *cpus = numa_span(prev_cpu);
506 
507 		if (allowed == p->cpus_ptr && task_affinity_all(p))
508 			numa_cpus = cpus;
509 		else if (cpus && cpumask_and(local_cpus, allowed, cpus))
510 			numa_cpus = local_cpus;
511 	}
512 
513 	if (static_branch_maybe(CONFIG_SCHED_MC, &scx_selcpu_topo_llc)) {
514 		struct cpumask *local_cpus = this_cpu_cpumask_var_ptr(local_llc_idle_cpumask);
515 		const struct cpumask *cpus = llc_span(prev_cpu);
516 
517 		if (allowed == p->cpus_ptr && task_affinity_all(p))
518 			llc_cpus = cpus;
519 		else if (cpus && cpumask_and(local_cpus, allowed, cpus))
520 			llc_cpus = local_cpus;
521 	}
522 
523 	/*
524 	 * If WAKE_SYNC, try to migrate the wakee to the waker's CPU.
525 	 */
526 	if (wake_flags & SCX_WAKE_SYNC) {
527 		int waker_node;
528 
529 		/*
530 		 * If the waker's CPU is cache affine and prev_cpu is idle,
531 		 * then avoid a migration.
532 		 */
533 		cpu = smp_processor_id();
534 		if (is_prev_allowed && cpus_share_cache(cpu, prev_cpu) &&
535 		    scx_idle_test_and_clear_cpu(prev_cpu)) {
536 			cpu = prev_cpu;
537 			goto out_unlock;
538 		}
539 
540 		/*
541 		 * If the waker's local DSQ is empty, and the system is under
542 		 * utilized, try to wake up @p to the local DSQ of the waker.
543 		 *
544 		 * Checking only for an empty local DSQ is insufficient as it
545 		 * could give the wakee an unfair advantage when the system is
546 		 * oversaturated.
547 		 *
548 		 * Checking only for the presence of idle CPUs is also
549 		 * insufficient as the local DSQ of the waker could have tasks
550 		 * piled up on it even if there is an idle core elsewhere on
551 		 * the system.
552 		 */
553 		waker_node = scx_cpu_node_if_enabled(cpu);
554 		if (!(current->flags & PF_EXITING) &&
555 		    cpu_rq(cpu)->scx.local_dsq.nr == 0 &&
556 		    (!(flags & SCX_PICK_IDLE_IN_NODE) || (waker_node == node)) &&
557 		    !cpumask_empty(idle_cpumask(waker_node)->cpu)) {
558 			if (cpumask_test_cpu(cpu, allowed))
559 				goto out_unlock;
560 		}
561 	}
562 
563 	/*
564 	 * If CPU has SMT, any wholly idle CPU is likely a better pick than
565 	 * partially idle @prev_cpu.
566 	 */
567 	if (sched_smt_active()) {
568 		/*
569 		 * Keep using @prev_cpu if it's part of a fully idle core.
570 		 */
571 		if (is_prev_allowed &&
572 		    cpumask_test_cpu(prev_cpu, idle_cpumask(node)->smt) &&
573 		    scx_idle_test_and_clear_cpu(prev_cpu)) {
574 			cpu = prev_cpu;
575 			goto out_unlock;
576 		}
577 
578 		/*
579 		 * Search for any fully idle core in the same LLC domain.
580 		 */
581 		if (llc_cpus) {
582 			cpu = pick_idle_cpu_in_node(llc_cpus, node, SCX_PICK_IDLE_CORE);
583 			if (cpu >= 0)
584 				goto out_unlock;
585 		}
586 
587 		/*
588 		 * Search for any fully idle core in the same NUMA node.
589 		 */
590 		if (numa_cpus) {
591 			cpu = pick_idle_cpu_in_node(numa_cpus, node, SCX_PICK_IDLE_CORE);
592 			if (cpu >= 0)
593 				goto out_unlock;
594 		}
595 
596 		/*
597 		 * Search for any full-idle core usable by the task.
598 		 *
599 		 * If the node-aware idle CPU selection policy is enabled
600 		 * (%SCX_OPS_BUILTIN_IDLE_PER_NODE), the search will always
601 		 * begin in prev_cpu's node and proceed to other nodes in
602 		 * order of increasing distance.
603 		 */
604 		cpu = scx_pick_idle_cpu(allowed, node, flags | SCX_PICK_IDLE_CORE);
605 		if (cpu >= 0)
606 			goto out_unlock;
607 
608 		/*
609 		 * Give up if we're strictly looking for a full-idle SMT
610 		 * core.
611 		 */
612 		if (flags & SCX_PICK_IDLE_CORE) {
613 			cpu = -EBUSY;
614 			goto out_unlock;
615 		}
616 	}
617 
618 	/*
619 	 * Use @prev_cpu if it's idle.
620 	 */
621 	if (is_prev_allowed && scx_idle_test_and_clear_cpu(prev_cpu)) {
622 		cpu = prev_cpu;
623 		goto out_unlock;
624 	}
625 
626 	/*
627 	 * Use @prev_cpu's sibling if it's idle.
628 	 */
629 	if (sched_smt_active()) {
630 		for_each_cpu_and(cpu, cpu_smt_mask(prev_cpu), allowed) {
631 			if (cpu == prev_cpu)
632 				continue;
633 			if (scx_idle_test_and_clear_cpu(cpu))
634 				goto out_unlock;
635 		}
636 	}
637 
638 	/*
639 	 * Search for any idle CPU in the same LLC domain.
640 	 */
641 	if (llc_cpus) {
642 		cpu = pick_idle_cpu_in_node(llc_cpus, node, 0);
643 		if (cpu >= 0)
644 			goto out_unlock;
645 	}
646 
647 	/*
648 	 * Search for any idle CPU in the same NUMA node.
649 	 */
650 	if (numa_cpus) {
651 		cpu = pick_idle_cpu_in_node(numa_cpus, node, 0);
652 		if (cpu >= 0)
653 			goto out_unlock;
654 	}
655 
656 	/*
657 	 * Search for any idle CPU usable by the task.
658 	 *
659 	 * If the node-aware idle CPU selection policy is enabled
660 	 * (%SCX_OPS_BUILTIN_IDLE_PER_NODE), the search will always begin
661 	 * in prev_cpu's node and proceed to other nodes in order of
662 	 * increasing distance.
663 	 */
664 	cpu = scx_pick_idle_cpu(allowed, node, flags);
665 
666 out_unlock:
667 	rcu_read_unlock();
668 out_enable:
669 	preempt_enable();
670 
671 	return cpu;
672 }
673 
674 /*
675  * Initialize global and per-node idle cpumasks.
676  */
677 void scx_idle_init_masks(void)
678 {
679 	int i;
680 
681 	/* Allocate global idle cpumasks */
682 	BUG_ON(!alloc_cpumask_var(&scx_idle_global_masks.cpu, GFP_KERNEL));
683 	BUG_ON(!alloc_cpumask_var(&scx_idle_global_masks.smt, GFP_KERNEL));
684 
685 	/* Allocate per-node idle cpumasks (use nr_node_ids for non-contiguous NUMA nodes) */
686 	scx_idle_node_masks = kzalloc_objs(*scx_idle_node_masks, nr_node_ids);
687 	BUG_ON(!scx_idle_node_masks);
688 
689 	for_each_node(i) {
690 		scx_idle_node_masks[i] = kzalloc_node(sizeof(**scx_idle_node_masks),
691 							 GFP_KERNEL, i);
692 		BUG_ON(!scx_idle_node_masks[i]);
693 
694 		BUG_ON(!alloc_cpumask_var_node(&scx_idle_node_masks[i]->cpu, GFP_KERNEL, i));
695 		BUG_ON(!alloc_cpumask_var_node(&scx_idle_node_masks[i]->smt, GFP_KERNEL, i));
696 	}
697 
698 	/* Allocate local per-cpu idle cpumasks */
699 	for_each_possible_cpu(i) {
700 		BUG_ON(!alloc_cpumask_var_node(&per_cpu(local_idle_cpumask, i),
701 					       GFP_KERNEL, cpu_to_node(i)));
702 		BUG_ON(!alloc_cpumask_var_node(&per_cpu(local_llc_idle_cpumask, i),
703 					       GFP_KERNEL, cpu_to_node(i)));
704 		BUG_ON(!alloc_cpumask_var_node(&per_cpu(local_numa_idle_cpumask, i),
705 					       GFP_KERNEL, cpu_to_node(i)));
706 	}
707 }
708 
709 static void update_builtin_idle(int cpu, bool idle)
710 {
711 	int node = scx_cpu_node_if_enabled(cpu);
712 	struct cpumask *idle_cpus = idle_cpumask(node)->cpu;
713 
714 	assign_cpu(cpu, idle_cpus, idle);
715 
716 	if (sched_smt_active()) {
717 		const struct cpumask *smt = cpu_smt_mask(cpu);
718 		struct cpumask *idle_smts = idle_cpumask(node)->smt;
719 
720 		if (idle) {
721 			/*
722 			 * idle_smt handling is racy but that's fine as it's
723 			 * only for optimization and self-correcting.
724 			 */
725 			if (!cpumask_subset(smt, idle_cpus))
726 				return;
727 			cpumask_or(idle_smts, idle_smts, smt);
728 		} else {
729 			cpumask_andnot(idle_smts, idle_smts, smt);
730 		}
731 	}
732 }
733 
734 /*
735  * Notify schedulers of an idle transition on @cpu's cid, delivering to every
736  * sched that holds %SCX_CAP_BASE on the cid (the root holds every cap). A real
737  * transition (@do_notify) reaches all holders. A forced one (@root_renotify for
738  * the root, a sub-sched's idle_renotify marker for a sub) reaches only the owed
739  * scheds.
740  */
741 static void scx_idle_notify(struct rq *rq, bool idle, bool do_notify, bool root_renotify)
742 {
743 	s32 cpu = cpu_of(rq);
744 	s32 cid = scx_cpu_arg(cpu);
745 	struct scx_sched *root = scx_root_protected_live();
746 	struct scx_sched *pos;
747 
748 	lockdep_assert_rq_held(rq);
749 
750 	/* with no sub-sched, only the root can be owed a notification */
751 	if (!scx_has_subs()) {
752 		if ((do_notify || root_renotify) &&
753 		    SCX_HAS_OP(root, update_idle) && !scx_bypassing(root, cpu))
754 			SCX_CALL_OP(root, update_idle, rq, cid, idle);
755 		return;
756 	}
757 
758 	pos = scx_next_descendant_pre(NULL, root);
759 	while (pos) {
760 		bool forced = false;
761 
762 		if (unlikely(scx_missing_caps(pos, cpu, SCX_CAP_BASE))) {
763 			pos = scx_skip_subtree_pre(pos, root);
764 			continue;
765 		}
766 
767 		if (!pos->level) {
768 			forced = root_renotify;
769 		}
770 #ifdef CONFIG_EXT_SUB_SCHED
771 		else if (per_cpu_ptr(pos->pcpu, cpu)->idle_renotify) {
772 			per_cpu_ptr(pos->pcpu, cpu)->idle_renotify = false;
773 			forced = true;
774 		}
775 #endif
776 		if ((do_notify || forced) && SCX_HAS_OP(pos, update_idle) &&
777 		    !scx_bypassing(pos, cpu))
778 			SCX_CALL_OP(pos, update_idle, rq, cid, idle);
779 		pos = scx_next_descendant_pre(pos, root);
780 	}
781 }
782 
783 /*
784  * Update the idle state of a CPU to @idle.
785  *
786  * If @do_notify is true, ops.update_idle() is invoked to notify the scx
787  * scheduler of an actual idle state transition (idle to busy or vice
788  * versa). If @do_notify is false, only the idle state in the idle masks is
789  * refreshed without invoking ops.update_idle().
790  *
791  * This distinction is necessary, because an idle CPU can be "reserved" and
792  * awakened via scx_bpf_pick_idle_cpu() + scx_bpf_kick_cpu(), marking it as
793  * busy even if no tasks are dispatched. In this case, the CPU may return
794  * to idle without a true state transition. Refreshing the idle masks
795  * without invoking ops.update_idle() ensures accurate idle state tracking
796  * while avoiding unnecessary updates and maintaining balanced state
797  * transitions.
798  */
799 void __scx_update_idle(struct rq *rq, bool idle, bool do_notify)
800 {
801 	int cpu = cpu_of(rq);
802 
803 	lockdep_assert_rq_held(rq);
804 
805 	/*
806 	 * pick_task_idle() calls here only on an idle-to-idle re-pick and the
807 	 * transitions call with @do_notify, so every reaching call updates the
808 	 * masks.
809 	 */
810 	if (static_branch_likely(&scx_builtin_idle_enabled))
811 		update_builtin_idle(cpu, idle);
812 
813 	/*
814 	 * ops.update_idle() fires on real idle transitions, indicated by
815 	 * @do_notify and managed by put_prev_task_idle()/set_next_task_idle().
816 	 * An idle pick also fires it to flush a forced notify owed to a sched
817 	 * that missed transitions while bypassed or on a cid it just gained.
818 	 * unbypass_renotify_idle() and scx_process_sync_ecaps() arm the per-rq
819 	 * gates, and scx_idle_notify() targets the owed scheds.
820 	 *
821 	 * This must come after the builtin idle update so that BPF schedulers
822 	 * can create interlocking between ops.update_idle() and ops.enqueue() -
823 	 * either enqueue() sees the idle bit or update_idle() sees the task
824 	 * that enqueue() queued.
825 	 */
826 	if (do_notify ||
827 	    (idle && (rq->scx.flags &
828 		      (SCX_RQ_SUB_IDLE_RENOTIFY | SCX_RQ_ROOT_IDLE_RENOTIFY)))) {
829 		bool root_renotify = rq->scx.flags & SCX_RQ_ROOT_IDLE_RENOTIFY;
830 
831 		rq->scx.flags &= ~(SCX_RQ_SUB_IDLE_RENOTIFY | SCX_RQ_ROOT_IDLE_RENOTIFY);
832 		scx_idle_notify(rq, idle, do_notify, root_renotify);
833 	}
834 }
835 
836 static void reset_idle_masks(struct sched_ext_ops *ops)
837 {
838 	int node;
839 
840 	/*
841 	 * Start with all CPUs marked busy. The idle masks are populated when
842 	 * bypass is lifted and each idle CPU is forced through an idle re-pick.
843 	 * This may temporarily omit idle CPUs but never advertises a busy CPU as
844 	 * idle.
845 	 */
846 	if (!(ops->flags & SCX_OPS_BUILTIN_IDLE_PER_NODE)) {
847 		cpumask_clear(idle_cpumask(NUMA_NO_NODE)->cpu);
848 		cpumask_clear(idle_cpumask(NUMA_NO_NODE)->smt);
849 		return;
850 	}
851 
852 	for_each_node(node) {
853 		cpumask_clear(idle_cpumask(node)->cpu);
854 		cpumask_clear(idle_cpumask(node)->smt);
855 	}
856 }
857 
858 void scx_idle_enable(struct sched_ext_ops *ops)
859 {
860 	if (!ops->update_idle || (ops->flags & SCX_OPS_KEEP_BUILTIN_IDLE))
861 		static_branch_enable_cpuslocked(&scx_builtin_idle_enabled);
862 	else
863 		static_branch_disable_cpuslocked(&scx_builtin_idle_enabled);
864 
865 	if (ops->flags & SCX_OPS_BUILTIN_IDLE_PER_NODE)
866 		static_branch_enable_cpuslocked(&scx_builtin_idle_per_node);
867 	else
868 		static_branch_disable_cpuslocked(&scx_builtin_idle_per_node);
869 
870 	reset_idle_masks(ops);
871 }
872 
873 void scx_idle_disable(void)
874 {
875 	static_branch_disable(&scx_builtin_idle_enabled);
876 	static_branch_disable(&scx_builtin_idle_per_node);
877 }
878 
879 /********************************************************************************
880  * Helpers that can be called from the BPF scheduler.
881  */
882 
883 static int validate_node(struct scx_sched *sch, int node)
884 {
885 	if (!static_branch_likely(&scx_builtin_idle_per_node)) {
886 		scx_error(sch, "per-node idle tracking is disabled");
887 		return -EOPNOTSUPP;
888 	}
889 
890 	/* Return no entry for NUMA_NO_NODE (not a critical scx error) */
891 	if (node == NUMA_NO_NODE)
892 		return -ENOENT;
893 
894 	/* Make sure node is in a valid range */
895 	if (node < 0 || node >= nr_node_ids) {
896 		scx_error(sch, "invalid node %d", node);
897 		return -EINVAL;
898 	}
899 
900 	/* Make sure the node is part of the set of possible nodes */
901 	if (!node_possible(node)) {
902 		scx_error(sch, "unavailable node %d", node);
903 		return -EINVAL;
904 	}
905 
906 	return node;
907 }
908 
909 __bpf_kfunc_start_defs();
910 
911 static bool check_builtin_idle_enabled(struct scx_sched *sch)
912 {
913 	if (static_branch_likely(&scx_builtin_idle_enabled))
914 		return true;
915 
916 	scx_error(sch, "built-in idle tracking is disabled");
917 	return false;
918 }
919 
920 /*
921  * Determine whether @p is a migration-disabled task in the context of BPF
922  * code.
923  *
924  * We can't simply check whether @p->migration_disabled is set in a
925  * sched_ext callback, because the BPF prolog (__bpf_prog_enter) may disable
926  * migration for the current task while running BPF code.
927  *
928  * Since the BPF prolog calls migrate_disable() only when CONFIG_PREEMPT_RCU
929  * is enabled (via rcu_read_lock_dont_migrate()), migration_disabled == 1 for
930  * the current task is ambiguous only in that case: it could be from the BPF
931  * prolog rather than a real migrate_disable() call.
932  *
933  * Without CONFIG_PREEMPT_RCU, the BPF prolog never calls migrate_disable(),
934  * so migration_disabled == 1 always means the task is truly
935  * migration-disabled.
936  *
937  * Therefore, when migration_disabled == 1 and CONFIG_PREEMPT_RCU is enabled,
938  * check whether @p is the current task or not: if it is, then migration was
939  * not disabled before entering the callback, otherwise migration was disabled.
940  *
941  * Returns true if @p is migration-disabled, false otherwise.
942  */
943 static bool is_bpf_migration_disabled(const struct task_struct *p)
944 {
945 	if (p->migration_disabled == 1) {
946 		if (IS_ENABLED(CONFIG_PREEMPT_RCU))
947 			return p != current;
948 		return true;
949 	}
950 	return p->migration_disabled;
951 }
952 
953 static s32 select_cpu_from_kfunc(struct scx_sched *sch, struct task_struct *p,
954 				 s32 prev_cpu, u64 wake_flags,
955 				 const struct cpumask *allowed, u64 flags)
956 {
957 	unsigned long irq_flags;
958 	bool we_locked = false;
959 	s32 cpu;
960 
961 	if (!scx_cpu_valid(sch, prev_cpu, NULL))
962 		return -EINVAL;
963 
964 	if (!check_builtin_idle_enabled(sch))
965 		return -EBUSY;
966 
967 	/*
968 	 * Accessing p->cpus_ptr / p->nr_cpus_allowed needs either @p's rq
969 	 * lock or @p's pi_lock. Three cases:
970 	 *
971 	 *  - inside ops.select_cpu(): try_to_wake_up() holds the wake-up
972 	 *    task's pi_lock; the wake-up task is recorded in kf_tasks[0]
973 	 *    by SCX_CALL_OP_TASK_RET().
974 	 *  - other rq-locked SCX op: scx_locked_rq() points at the held rq.
975 	 *  - truly unlocked (UNLOCKED ops, SYSCALL, non-SCX struct_ops):
976 	 *    nothing held, take pi_lock ourselves.
977 	 *
978 	 * In the first two cases, BPF schedulers may pass an arbitrary task
979 	 * that the held lock doesn't cover. Refuse those.
980 	 */
981 	if (this_rq()->scx.in_select_cpu) {
982 		if (!scx_kf_arg_task_ok(sch, p))
983 			return -EINVAL;
984 		lockdep_assert_held(&p->pi_lock);
985 	} else if (scx_locked_rq()) {
986 		if (task_rq(p) != scx_locked_rq())
987 			goto cross_task;
988 	} else {
989 		raw_spin_lock_irqsave(&p->pi_lock, irq_flags);
990 		we_locked = true;
991 	}
992 
993 	/*
994 	 * This may also be called from ops.enqueue(), so we need to handle
995 	 * per-CPU tasks as well. For these tasks, we can skip all idle CPU
996 	 * selection optimizations and simply check whether the previously
997 	 * used CPU is idle and within the allowed cpumask.
998 	 */
999 	if (p->nr_cpus_allowed == 1 || is_bpf_migration_disabled(p)) {
1000 		if (cpumask_test_cpu(prev_cpu, allowed ?: p->cpus_ptr) &&
1001 		    scx_idle_test_and_clear_cpu(prev_cpu))
1002 			cpu = prev_cpu;
1003 		else
1004 			cpu = -EBUSY;
1005 	} else {
1006 		cpu = scx_select_cpu_dfl(p, prev_cpu, wake_flags,
1007 					 allowed ?: p->cpus_ptr, flags);
1008 	}
1009 
1010 	if (we_locked)
1011 		raw_spin_unlock_irqrestore(&p->pi_lock, irq_flags);
1012 
1013 	return cpu;
1014 
1015 cross_task:
1016 	scx_error(sch, "select_cpu kfunc called cross-task on %s[%d]",
1017 		  p->comm, p->pid);
1018 	return -EINVAL;
1019 }
1020 
1021 /**
1022  * scx_bpf_cpu_node - Return the NUMA node the given @cpu belongs to, or
1023  *		      trigger an error if @cpu is invalid
1024  * @cpu: target CPU
1025  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
1026  */
1027 __bpf_kfunc s32 scx_bpf_cpu_node(s32 cpu, const struct bpf_prog_aux *aux)
1028 {
1029 	struct scx_sched *sch;
1030 
1031 	guard(rcu)();
1032 
1033 	sch = scx_prog_sched(aux);
1034 	if (unlikely(!sch) || !scx_cpu_valid(sch, cpu, NULL))
1035 		return NUMA_NO_NODE;
1036 	return cpu_to_node(cpu);
1037 }
1038 
1039 /**
1040  * scx_bpf_select_cpu_dfl - The default implementation of ops.select_cpu()
1041  * @p: task_struct to select a CPU for
1042  * @prev_cpu: CPU @p was on previously
1043  * @wake_flags: %SCX_WAKE_* flags
1044  * @is_idle: out parameter indicating whether the returned CPU is idle
1045  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
1046  *
1047  * Can be called from ops.select_cpu(), ops.enqueue(), or from an unlocked
1048  * context such as a BPF test_run() call, as long as built-in CPU selection
1049  * is enabled: ops.update_idle() is missing or %SCX_OPS_KEEP_BUILTIN_IDLE
1050  * is set.
1051  *
1052  * Returns the picked CPU with *@is_idle indicating whether the picked CPU is
1053  * currently idle and thus a good candidate for direct dispatching.
1054  */
1055 __bpf_kfunc s32 scx_bpf_select_cpu_dfl(struct task_struct *p, s32 prev_cpu,
1056 				       u64 wake_flags, bool *is_idle,
1057 				       const struct bpf_prog_aux *aux)
1058 {
1059 	struct scx_sched *sch;
1060 	s32 cpu;
1061 
1062 	guard(rcu)();
1063 
1064 	sch = scx_prog_sched(aux);
1065 	if (unlikely(!sch))
1066 		return -ENODEV;
1067 
1068 	cpu = select_cpu_from_kfunc(sch, p, prev_cpu, wake_flags, NULL, 0);
1069 	if (cpu >= 0) {
1070 		*is_idle = true;
1071 		return cpu;
1072 	}
1073 	*is_idle = false;
1074 	return prev_cpu;
1075 }
1076 
1077 struct scx_bpf_select_cpu_and_args {
1078 	/* @p and @cpus_allowed can't be packed together as KF_RCU is not transitive */
1079 	s32			prev_cpu;
1080 	u64			wake_flags;
1081 	u64			flags;
1082 };
1083 
1084 /**
1085  * __scx_bpf_select_cpu_and - Arg-wrapped CPU selection with cpumask
1086  * @p: task_struct to select a CPU for
1087  * @cpus_allowed: cpumask of allowed CPUs
1088  * @args: struct containing the rest of the arguments
1089  *       @args->prev_cpu: CPU @p was on previously
1090  *       @args->wake_flags: %SCX_WAKE_* flags
1091  *       @args->flags: %SCX_PICK_IDLE* flags
1092  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
1093  *
1094  * Wrapper kfunc that takes arguments via struct to work around BPF's 5 argument
1095  * limit. BPF programs should use scx_bpf_select_cpu_and() which is provided
1096  * as an inline wrapper in common.bpf.h.
1097  *
1098  * Can be called from ops.select_cpu(), ops.enqueue(), or from an unlocked
1099  * context such as a BPF test_run() call, as long as built-in CPU selection
1100  * is enabled: ops.update_idle() is missing or %SCX_OPS_KEEP_BUILTIN_IDLE
1101  * is set.
1102  *
1103  * @p, @args->prev_cpu and @args->wake_flags match ops.select_cpu().
1104  *
1105  * Returns the selected idle CPU, which will be automatically awakened upon
1106  * returning from ops.select_cpu() and can be used for direct dispatch, or
1107  * a negative value if no idle CPU is available.
1108  */
1109 __bpf_kfunc s32
1110 __scx_bpf_select_cpu_and(struct task_struct *p, const struct cpumask *cpus_allowed,
1111 			 struct scx_bpf_select_cpu_and_args *args,
1112 			 const struct bpf_prog_aux *aux)
1113 {
1114 	struct scx_sched *sch;
1115 
1116 	guard(rcu)();
1117 
1118 	sch = scx_prog_sched(aux);
1119 	if (unlikely(!sch))
1120 		return -ENODEV;
1121 
1122 	return select_cpu_from_kfunc(sch, p, args->prev_cpu, args->wake_flags,
1123 				     cpus_allowed, args->flags);
1124 }
1125 
1126 /*
1127  * COMPAT: Will be removed in v6.22.
1128  */
1129 __bpf_kfunc s32 scx_bpf_select_cpu_and(struct task_struct *p, s32 prev_cpu, u64 wake_flags,
1130 				       const struct cpumask *cpus_allowed, u64 flags)
1131 {
1132 	struct scx_sched *sch;
1133 
1134 	guard(rcu)();
1135 
1136 	sch = rcu_dereference(scx_root);
1137 	if (unlikely(!sch))
1138 		return -ENODEV;
1139 
1140 #ifdef CONFIG_EXT_SUB_SCHED
1141 	/*
1142 	 * Disallow if any sub-scheds are attached. There is no way to tell
1143 	 * which scheduler called us, just error out @p's scheduler.
1144 	 */
1145 	if (unlikely(!list_empty(&sch->children))) {
1146 		scx_error(scx_task_sched(p), "__scx_bpf_select_cpu_and() must be used");
1147 		return -EINVAL;
1148 	}
1149 #endif
1150 
1151 	return select_cpu_from_kfunc(sch, p, prev_cpu, wake_flags,
1152 				     cpus_allowed, flags);
1153 }
1154 
1155 /**
1156  * scx_bpf_get_idle_cpumask_node - Get a referenced kptr to the
1157  * idle-tracking per-CPU cpumask of a target NUMA node.
1158  * @node: target NUMA node
1159  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
1160  *
1161  * Returns an empty cpumask if idle tracking is not enabled, if @node is
1162  * not valid, or running on a UP kernel. In this case the actual error will
1163  * be reported to the BPF scheduler via scx_error().
1164  */
1165 __bpf_kfunc const struct cpumask *
1166 scx_bpf_get_idle_cpumask_node(s32 node, const struct bpf_prog_aux *aux)
1167 {
1168 	struct scx_sched *sch;
1169 
1170 	guard(rcu)();
1171 
1172 	sch = scx_prog_sched(aux);
1173 	if (unlikely(!sch))
1174 		return cpu_none_mask;
1175 
1176 	node = validate_node(sch, node);
1177 	if (node < 0)
1178 		return cpu_none_mask;
1179 
1180 	return idle_cpumask(node)->cpu;
1181 }
1182 
1183 /**
1184  * scx_bpf_get_idle_cpumask - Get a referenced kptr to the idle-tracking
1185  * per-CPU cpumask.
1186  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
1187  *
1188  * Returns an empty mask if idle tracking is not enabled, or running on a
1189  * UP kernel.
1190  */
1191 __bpf_kfunc const struct cpumask *scx_bpf_get_idle_cpumask(const struct bpf_prog_aux *aux)
1192 {
1193 	struct scx_sched *sch;
1194 
1195 	guard(rcu)();
1196 
1197 	sch = scx_prog_sched(aux);
1198 	if (unlikely(!sch))
1199 		return cpu_none_mask;
1200 
1201 	if (static_branch_unlikely(&scx_builtin_idle_per_node)) {
1202 		scx_error(sch, "SCX_OPS_BUILTIN_IDLE_PER_NODE enabled");
1203 		return cpu_none_mask;
1204 	}
1205 
1206 	if (!check_builtin_idle_enabled(sch))
1207 		return cpu_none_mask;
1208 
1209 	return idle_cpumask(NUMA_NO_NODE)->cpu;
1210 }
1211 
1212 /**
1213  * scx_bpf_get_idle_smtmask_node - Get a referenced kptr to the
1214  * idle-tracking, per-physical-core cpumask of a target NUMA node. Can be
1215  * used to determine if an entire physical core is free.
1216  * @node: target NUMA node
1217  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
1218  *
1219  * Returns an empty cpumask if idle tracking is not enabled, if @node is
1220  * not valid, or running on a UP kernel. In this case the actual error will
1221  * be reported to the BPF scheduler via scx_error().
1222  */
1223 __bpf_kfunc const struct cpumask *
1224 scx_bpf_get_idle_smtmask_node(s32 node, const struct bpf_prog_aux *aux)
1225 {
1226 	struct scx_sched *sch;
1227 
1228 	guard(rcu)();
1229 
1230 	sch = scx_prog_sched(aux);
1231 	if (unlikely(!sch))
1232 		return cpu_none_mask;
1233 
1234 	node = validate_node(sch, node);
1235 	if (node < 0)
1236 		return cpu_none_mask;
1237 
1238 	if (sched_smt_active())
1239 		return idle_cpumask(node)->smt;
1240 	else
1241 		return idle_cpumask(node)->cpu;
1242 }
1243 
1244 /**
1245  * scx_bpf_get_idle_smtmask - Get a referenced kptr to the idle-tracking,
1246  * per-physical-core cpumask. Can be used to determine if an entire physical
1247  * core is free.
1248  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
1249  *
1250  * Returns an empty mask if idle tracking is not enabled, or running on a
1251  * UP kernel.
1252  */
1253 __bpf_kfunc const struct cpumask *scx_bpf_get_idle_smtmask(const struct bpf_prog_aux *aux)
1254 {
1255 	struct scx_sched *sch;
1256 
1257 	guard(rcu)();
1258 
1259 	sch = scx_prog_sched(aux);
1260 	if (unlikely(!sch))
1261 		return cpu_none_mask;
1262 
1263 	if (static_branch_unlikely(&scx_builtin_idle_per_node)) {
1264 		scx_error(sch, "SCX_OPS_BUILTIN_IDLE_PER_NODE enabled");
1265 		return cpu_none_mask;
1266 	}
1267 
1268 	if (!check_builtin_idle_enabled(sch))
1269 		return cpu_none_mask;
1270 
1271 	if (sched_smt_active())
1272 		return idle_cpumask(NUMA_NO_NODE)->smt;
1273 	else
1274 		return idle_cpumask(NUMA_NO_NODE)->cpu;
1275 }
1276 
1277 /**
1278  * scx_bpf_put_idle_cpumask - Release a previously acquired referenced kptr to
1279  * either the percpu, or SMT idle-tracking cpumask.
1280  * @idle_mask: &cpumask to use
1281  */
1282 __bpf_kfunc void scx_bpf_put_idle_cpumask(const struct cpumask *idle_mask)
1283 {
1284 	/*
1285 	 * Empty function body because we aren't actually acquiring or releasing
1286 	 * a reference to a global idle cpumask, which is read-only in the
1287 	 * caller and is never released. The acquire / release semantics here
1288 	 * are just used to make the cpumask a trusted pointer in the caller.
1289 	 */
1290 }
1291 
1292 /**
1293  * scx_bpf_test_and_clear_cpu_idle - Test and clear @cpu's idle state
1294  * @cpu: cpu to test and clear idle for
1295  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
1296  *
1297  * Returns %true if @cpu was idle and its idle state was successfully cleared.
1298  * %false otherwise.
1299  *
1300  * Unavailable if ops.update_idle() is implemented and
1301  * %SCX_OPS_KEEP_BUILTIN_IDLE is not set.
1302  */
1303 __bpf_kfunc bool scx_bpf_test_and_clear_cpu_idle(s32 cpu, const struct bpf_prog_aux *aux)
1304 {
1305 	struct scx_sched *sch;
1306 
1307 	guard(rcu)();
1308 
1309 	sch = scx_prog_sched(aux);
1310 	if (unlikely(!sch))
1311 		return false;
1312 
1313 	if (!check_builtin_idle_enabled(sch))
1314 		return false;
1315 
1316 	if (!scx_cpu_valid(sch, cpu, NULL))
1317 		return false;
1318 
1319 	return scx_idle_test_and_clear_cpu(cpu);
1320 }
1321 
1322 /**
1323  * scx_bpf_pick_idle_cpu_node - Pick and claim an idle cpu from @node
1324  * @cpus_allowed: Allowed cpumask
1325  * @node: target NUMA node
1326  * @flags: %SCX_PICK_IDLE_* flags
1327  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
1328  *
1329  * Pick and claim an idle cpu in @cpus_allowed from the NUMA node @node.
1330  *
1331  * Returns the picked idle cpu number on success, or -%EBUSY if no matching
1332  * cpu was found.
1333  *
1334  * The search starts from @node and proceeds to other online NUMA nodes in
1335  * order of increasing distance (unless SCX_PICK_IDLE_IN_NODE is specified,
1336  * in which case the search is limited to the target @node).
1337  *
1338  * Always returns an error if ops.update_idle() is implemented and
1339  * %SCX_OPS_KEEP_BUILTIN_IDLE is not set, or if
1340  * %SCX_OPS_BUILTIN_IDLE_PER_NODE is not set.
1341  */
1342 __bpf_kfunc s32 scx_bpf_pick_idle_cpu_node(const struct cpumask *cpus_allowed,
1343 					   s32 node, u64 flags,
1344 					   const struct bpf_prog_aux *aux)
1345 {
1346 	struct scx_sched *sch;
1347 
1348 	guard(rcu)();
1349 
1350 	sch = scx_prog_sched(aux);
1351 	if (unlikely(!sch))
1352 		return -ENODEV;
1353 
1354 	node = validate_node(sch, node);
1355 	if (node < 0)
1356 		return node;
1357 
1358 	return scx_pick_idle_cpu(cpus_allowed, node, flags);
1359 }
1360 
1361 /**
1362  * scx_bpf_pick_idle_cpu - Pick and claim an idle cpu
1363  * @cpus_allowed: Allowed cpumask
1364  * @flags: %SCX_PICK_IDLE_* flags
1365  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
1366  *
1367  * Pick and claim an idle cpu in @cpus_allowed. Returns the picked idle cpu
1368  * number on success. -%EBUSY if no matching cpu was found.
1369  *
1370  * Idle CPU tracking may race against CPU scheduling state transitions. For
1371  * example, this function may return -%EBUSY as CPUs are transitioning into the
1372  * idle state. If the caller then assumes that there will be dispatch events on
1373  * the CPUs as they were all busy, the scheduler may end up stalling with CPUs
1374  * idling while there are pending tasks. Use scx_bpf_pick_any_cpu() and
1375  * scx_bpf_kick_cpu() to guarantee that there will be at least one dispatch
1376  * event in the near future.
1377  *
1378  * Unavailable if ops.update_idle() is implemented and
1379  * %SCX_OPS_KEEP_BUILTIN_IDLE is not set.
1380  *
1381  * Always returns an error if %SCX_OPS_BUILTIN_IDLE_PER_NODE is set, use
1382  * scx_bpf_pick_idle_cpu_node() instead.
1383  */
1384 __bpf_kfunc s32 scx_bpf_pick_idle_cpu(const struct cpumask *cpus_allowed,
1385 				      u64 flags, const struct bpf_prog_aux *aux)
1386 {
1387 	struct scx_sched *sch;
1388 
1389 	guard(rcu)();
1390 
1391 	sch = scx_prog_sched(aux);
1392 	if (unlikely(!sch))
1393 		return -ENODEV;
1394 
1395 	if (static_branch_maybe(CONFIG_NUMA, &scx_builtin_idle_per_node)) {
1396 		scx_error(sch, "per-node idle tracking is enabled");
1397 		return -EBUSY;
1398 	}
1399 
1400 	if (!check_builtin_idle_enabled(sch))
1401 		return -EBUSY;
1402 
1403 	return scx_pick_idle_cpu(cpus_allowed, NUMA_NO_NODE, flags);
1404 }
1405 
1406 /**
1407  * scx_bpf_pick_any_cpu_node - Pick and claim an idle cpu if available
1408  *			       or pick any CPU from @node
1409  * @cpus_allowed: Allowed cpumask
1410  * @node: target NUMA node
1411  * @flags: %SCX_PICK_IDLE_* flags
1412  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
1413  *
1414  * Pick and claim an idle cpu in @cpus_allowed. If none is available, pick any
1415  * CPU in @cpus_allowed. Guaranteed to succeed and returns the picked idle cpu
1416  * number if @cpus_allowed is not empty. -%EBUSY is returned if @cpus_allowed is
1417  * empty.
1418  *
1419  * The search starts from @node and proceeds to other online NUMA nodes in
1420  * order of increasing distance (unless %SCX_PICK_IDLE_IN_NODE is specified,
1421  * in which case the search is limited to the target @node, regardless of
1422  * the CPU idle state).
1423  *
1424  * If ops.update_idle() is implemented and %SCX_OPS_KEEP_BUILTIN_IDLE is not
1425  * set, this function can't tell which CPUs are idle and will always pick any
1426  * CPU.
1427  */
1428 __bpf_kfunc s32 scx_bpf_pick_any_cpu_node(const struct cpumask *cpus_allowed,
1429 					  s32 node, u64 flags,
1430 					  const struct bpf_prog_aux *aux)
1431 {
1432 	struct scx_sched *sch;
1433 	s32 cpu;
1434 
1435 	guard(rcu)();
1436 
1437 	sch = scx_prog_sched(aux);
1438 	if (unlikely(!sch))
1439 		return -ENODEV;
1440 
1441 	node = validate_node(sch, node);
1442 	if (node < 0)
1443 		return node;
1444 
1445 	cpu = scx_pick_idle_cpu(cpus_allowed, node, flags);
1446 	if (cpu >= 0)
1447 		return cpu;
1448 
1449 	if (flags & SCX_PICK_IDLE_IN_NODE)
1450 		cpu = cpumask_any_and_distribute(cpumask_of_node(node), cpus_allowed);
1451 	else
1452 		cpu = cpumask_any_distribute(cpus_allowed);
1453 	if (cpu < nr_cpu_ids)
1454 		return cpu;
1455 	else
1456 		return -EBUSY;
1457 }
1458 
1459 /**
1460  * scx_bpf_pick_any_cpu - Pick and claim an idle cpu if available or pick any CPU
1461  * @cpus_allowed: Allowed cpumask
1462  * @flags: %SCX_PICK_IDLE_* flags
1463  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
1464  *
1465  * Pick and claim an idle cpu in @cpus_allowed. If none is available, pick any
1466  * CPU in @cpus_allowed. Guaranteed to succeed and returns the picked idle cpu
1467  * number if @cpus_allowed is not empty. -%EBUSY is returned if @cpus_allowed is
1468  * empty.
1469  *
1470  * If ops.update_idle() is implemented and %SCX_OPS_KEEP_BUILTIN_IDLE is not
1471  * set, this function can't tell which CPUs are idle and will always pick any
1472  * CPU.
1473  *
1474  * Always returns an error if %SCX_OPS_BUILTIN_IDLE_PER_NODE is set, use
1475  * scx_bpf_pick_any_cpu_node() instead.
1476  */
1477 __bpf_kfunc s32 scx_bpf_pick_any_cpu(const struct cpumask *cpus_allowed,
1478 				     u64 flags, const struct bpf_prog_aux *aux)
1479 {
1480 	struct scx_sched *sch;
1481 	s32 cpu;
1482 
1483 	guard(rcu)();
1484 
1485 	sch = scx_prog_sched(aux);
1486 	if (unlikely(!sch))
1487 		return -ENODEV;
1488 
1489 	if (static_branch_maybe(CONFIG_NUMA, &scx_builtin_idle_per_node)) {
1490 		scx_error(sch, "per-node idle tracking is enabled");
1491 		return -EBUSY;
1492 	}
1493 
1494 	if (static_branch_likely(&scx_builtin_idle_enabled)) {
1495 		cpu = scx_pick_idle_cpu(cpus_allowed, NUMA_NO_NODE, flags);
1496 		if (cpu >= 0)
1497 			return cpu;
1498 	}
1499 
1500 	cpu = cpumask_any_distribute(cpus_allowed);
1501 	if (cpu < nr_cpu_ids)
1502 		return cpu;
1503 	else
1504 		return -EBUSY;
1505 }
1506 
1507 __bpf_kfunc_end_defs();
1508 
1509 BTF_KFUNCS_START(scx_kfunc_ids_idle)
1510 BTF_ID_FLAGS(func, scx_bpf_cpu_node, KF_IMPLICIT_ARGS)
1511 BTF_ID_FLAGS(func, scx_bpf_get_idle_cpumask_node, KF_IMPLICIT_ARGS | KF_ACQUIRE)
1512 BTF_ID_FLAGS(func, scx_bpf_get_idle_cpumask, KF_IMPLICIT_ARGS | KF_ACQUIRE)
1513 BTF_ID_FLAGS(func, scx_bpf_get_idle_smtmask_node, KF_IMPLICIT_ARGS | KF_ACQUIRE)
1514 BTF_ID_FLAGS(func, scx_bpf_get_idle_smtmask, KF_IMPLICIT_ARGS | KF_ACQUIRE)
1515 BTF_ID_FLAGS(func, scx_bpf_put_idle_cpumask, KF_RELEASE)
1516 BTF_ID_FLAGS(func, scx_bpf_test_and_clear_cpu_idle, KF_IMPLICIT_ARGS)
1517 BTF_ID_FLAGS(func, scx_bpf_pick_idle_cpu_node, KF_IMPLICIT_ARGS | KF_RCU)
1518 BTF_ID_FLAGS(func, scx_bpf_pick_idle_cpu, KF_IMPLICIT_ARGS | KF_RCU)
1519 BTF_ID_FLAGS(func, scx_bpf_pick_any_cpu_node, KF_IMPLICIT_ARGS | KF_RCU)
1520 BTF_ID_FLAGS(func, scx_bpf_pick_any_cpu, KF_IMPLICIT_ARGS | KF_RCU)
1521 BTF_KFUNCS_END(scx_kfunc_ids_idle)
1522 
1523 static const struct btf_kfunc_id_set scx_kfunc_set_idle = {
1524 	.owner			= THIS_MODULE,
1525 	.set			= &scx_kfunc_ids_idle,
1526 	.filter			= scx_kfunc_context_filter,
1527 };
1528 
1529 /*
1530  * The select_cpu kfuncs internally call task_rq_lock() when invoked from an
1531  * rq-unlocked context, and thus cannot be safely called from arbitrary tracing
1532  * contexts where @p's pi_lock state is unknown. Keep them out of
1533  * BPF_PROG_TYPE_TRACING by registering them in their own set which is exposed
1534  * only to STRUCT_OPS and SYSCALL programs.
1535  *
1536  * These kfuncs are also members of scx_kfunc_ids_unlocked (see ext.c) because
1537  * they're callable from unlocked contexts in addition to ops.select_cpu() and
1538  * ops.enqueue().
1539  */
1540 BTF_KFUNCS_START(scx_kfunc_ids_select_cpu)
1541 BTF_ID_FLAGS(func, __scx_bpf_select_cpu_and, KF_IMPLICIT_ARGS | KF_RCU)
1542 BTF_ID_FLAGS(func, scx_bpf_select_cpu_and, KF_RCU)
1543 BTF_ID_FLAGS(func, scx_bpf_select_cpu_dfl, KF_IMPLICIT_ARGS | KF_RCU)
1544 BTF_KFUNCS_END(scx_kfunc_ids_select_cpu)
1545 
1546 static const struct btf_kfunc_id_set scx_kfunc_set_select_cpu = {
1547 	.owner			= THIS_MODULE,
1548 	.set			= &scx_kfunc_ids_select_cpu,
1549 	.filter			= scx_kfunc_context_filter,
1550 };
1551 
1552 int scx_idle_init(void)
1553 {
1554 	return register_btf_kfunc_id_set(BPF_PROG_TYPE_STRUCT_OPS, &scx_kfunc_set_idle) ?:
1555 	       register_btf_kfunc_id_set(BPF_PROG_TYPE_TRACING, &scx_kfunc_set_idle) ?:
1556 	       register_btf_kfunc_id_set(BPF_PROG_TYPE_SYSCALL, &scx_kfunc_set_idle) ?:
1557 	       register_btf_kfunc_id_set(BPF_PROG_TYPE_STRUCT_OPS, &scx_kfunc_set_select_cpu) ?:
1558 	       register_btf_kfunc_id_set(BPF_PROG_TYPE_SYSCALL, &scx_kfunc_set_select_cpu);
1559 }
1560