xref: /linux/kernel/sched/ext.c (revision 105dcd005be2ac1d5541921db8feb1d0f98d59d5)
1 /* SPDX-License-Identifier: GPL-2.0 */
2 /*
3  * BPF extensible scheduler class: Documentation/scheduler/sched-ext.rst
4  *
5  * Copyright (c) 2022 Meta Platforms, Inc. and affiliates.
6  * Copyright (c) 2022 Tejun Heo <tj@kernel.org>
7  * Copyright (c) 2022 David Vernet <dvernet@meta.com>
8  */
9 #include <linux/btf_ids.h>
10 #include "ext_idle.h"
11 
12 static DEFINE_RAW_SPINLOCK(scx_sched_lock);
13 
14 /*
15  * NOTE: sched_ext is in the process of growing multiple scheduler support and
16  * scx_root usage is in a transitional state. Naked dereferences are safe if the
17  * caller is one of the tasks attached to SCX and explicit RCU dereference is
18  * necessary otherwise. Naked scx_root dereferences trigger sparse warnings but
19  * are used as temporary markers to indicate that the dereferences need to be
20  * updated to point to the associated scheduler instances rather than scx_root.
21  */
22 struct scx_sched __rcu *scx_root;
23 
24 /*
25  * All scheds, writers must hold both scx_enable_mutex and scx_sched_lock.
26  * Readers can hold either or rcu_read_lock().
27  */
28 static LIST_HEAD(scx_sched_all);
29 
30 /*
31  * During exit, a task may schedule after losing its PIDs. When disabling the
32  * BPF scheduler, we need to be able to iterate tasks in every state to
33  * guarantee system safety. Maintain a dedicated task list which contains every
34  * task between its fork and eventual free.
35  */
36 static DEFINE_RAW_SPINLOCK(scx_tasks_lock);
37 static LIST_HEAD(scx_tasks);
38 
39 /* ops enable/disable */
40 static DEFINE_MUTEX(scx_enable_mutex);
41 DEFINE_STATIC_KEY_FALSE(__scx_enabled);
42 DEFINE_STATIC_PERCPU_RWSEM(scx_fork_rwsem);
43 static atomic_t scx_enable_state_var = ATOMIC_INIT(SCX_DISABLED);
44 static int scx_bypass_depth;
45 static cpumask_var_t scx_bypass_lb_donee_cpumask;
46 static cpumask_var_t scx_bypass_lb_resched_cpumask;
47 static bool scx_aborting;
48 static bool scx_init_task_enabled;
49 static bool scx_switching_all;
50 DEFINE_STATIC_KEY_FALSE(__scx_switched_all);
51 
52 /*
53  * Tracks whether scx_enable() called scx_bypass(true). Used to balance bypass
54  * depth on enable failure. Will be removed when bypass depth is moved into the
55  * sched instance.
56  */
57 static bool scx_bypassed_for_enable;
58 
59 static atomic_long_t scx_nr_rejected = ATOMIC_LONG_INIT(0);
60 static atomic_long_t scx_hotplug_seq = ATOMIC_LONG_INIT(0);
61 
62 /*
63  * A monotically increasing sequence number that is incremented every time a
64  * scheduler is enabled. This can be used by to check if any custom sched_ext
65  * scheduler has ever been used in the system.
66  */
67 static atomic_long_t scx_enable_seq = ATOMIC_LONG_INIT(0);
68 
69 /*
70  * The maximum amount of time in jiffies that a task may be runnable without
71  * being scheduled on a CPU. If this timeout is exceeded, it will trigger
72  * scx_error().
73  */
74 static unsigned long scx_watchdog_timeout;
75 
76 /*
77  * The last time the delayed work was run. This delayed work relies on
78  * ksoftirqd being able to run to service timer interrupts, so it's possible
79  * that this work itself could get wedged. To account for this, we check that
80  * it's not stalled in the timer tick, and trigger an error if it is.
81  */
82 static unsigned long scx_watchdog_timestamp = INITIAL_JIFFIES;
83 
84 static struct delayed_work scx_watchdog_work;
85 
86 /*
87  * For %SCX_KICK_WAIT: Each CPU has a pointer to an array of kick_sync sequence
88  * numbers. The arrays are allocated with kvzalloc() as size can exceed percpu
89  * allocator limits on large machines. O(nr_cpu_ids^2) allocation, allocated
90  * lazily when enabling and freed when disabling to avoid waste when sched_ext
91  * isn't active.
92  */
93 struct scx_kick_syncs {
94 	struct rcu_head		rcu;
95 	unsigned long		syncs[];
96 };
97 
98 static DEFINE_PER_CPU(struct scx_kick_syncs __rcu *, scx_kick_syncs);
99 
100 /*
101  * Direct dispatch marker.
102  *
103  * Non-NULL values are used for direct dispatch from enqueue path. A valid
104  * pointer points to the task currently being enqueued. An ERR_PTR value is used
105  * to indicate that direct dispatch has already happened.
106  */
107 static DEFINE_PER_CPU(struct task_struct *, direct_dispatch_task);
108 
109 static const struct rhashtable_params dsq_hash_params = {
110 	.key_len		= sizeof_field(struct scx_dispatch_q, id),
111 	.key_offset		= offsetof(struct scx_dispatch_q, id),
112 	.head_offset		= offsetof(struct scx_dispatch_q, hash_node),
113 };
114 
115 static LLIST_HEAD(dsqs_to_free);
116 
117 /* dispatch buf */
118 struct scx_dsp_buf_ent {
119 	struct task_struct	*task;
120 	unsigned long		qseq;
121 	u64			dsq_id;
122 	u64			enq_flags;
123 };
124 
125 static u32 scx_dsp_max_batch;
126 
127 struct scx_dsp_ctx {
128 	struct rq		*rq;
129 	u32			cursor;
130 	u32			nr_tasks;
131 	struct scx_dsp_buf_ent	buf[];
132 };
133 
134 static struct scx_dsp_ctx __percpu *scx_dsp_ctx;
135 
136 /* string formatting from BPF */
137 struct scx_bstr_buf {
138 	u64			data[MAX_BPRINTF_VARARGS];
139 	char			line[SCX_EXIT_MSG_LEN];
140 };
141 
142 static DEFINE_RAW_SPINLOCK(scx_exit_bstr_buf_lock);
143 static struct scx_bstr_buf scx_exit_bstr_buf;
144 
145 /* ops debug dump */
146 struct scx_dump_data {
147 	s32			cpu;
148 	bool			first;
149 	s32			cursor;
150 	struct seq_buf		*s;
151 	const char		*prefix;
152 	struct scx_bstr_buf	buf;
153 };
154 
155 static struct scx_dump_data scx_dump_data = {
156 	.cpu			= -1,
157 };
158 
159 /* /sys/kernel/sched_ext interface */
160 static struct kset *scx_kset;
161 
162 /*
163  * Parameters that can be adjusted through /sys/module/sched_ext/parameters.
164  * There usually is no reason to modify these as normal scheduler operation
165  * shouldn't be affected by them. The knobs are primarily for debugging.
166  */
167 static u64 scx_slice_dfl = SCX_SLICE_DFL;
168 static unsigned int scx_slice_bypass_us = SCX_SLICE_BYPASS / NSEC_PER_USEC;
169 static unsigned int scx_bypass_lb_intv_us = SCX_BYPASS_LB_DFL_INTV_US;
170 
171 static int set_slice_us(const char *val, const struct kernel_param *kp)
172 {
173 	return param_set_uint_minmax(val, kp, 100, 100 * USEC_PER_MSEC);
174 }
175 
176 static const struct kernel_param_ops slice_us_param_ops = {
177 	.set = set_slice_us,
178 	.get = param_get_uint,
179 };
180 
181 static int set_bypass_lb_intv_us(const char *val, const struct kernel_param *kp)
182 {
183 	return param_set_uint_minmax(val, kp, 0, 10 * USEC_PER_SEC);
184 }
185 
186 static const struct kernel_param_ops bypass_lb_intv_us_param_ops = {
187 	.set = set_bypass_lb_intv_us,
188 	.get = param_get_uint,
189 };
190 
191 #undef MODULE_PARAM_PREFIX
192 #define MODULE_PARAM_PREFIX	"sched_ext."
193 
194 module_param_cb(slice_bypass_us, &slice_us_param_ops, &scx_slice_bypass_us, 0600);
195 MODULE_PARM_DESC(slice_bypass_us, "bypass slice in microseconds, applied on [un]load (100us to 100ms)");
196 module_param_cb(bypass_lb_intv_us, &bypass_lb_intv_us_param_ops, &scx_bypass_lb_intv_us, 0600);
197 MODULE_PARM_DESC(bypass_lb_intv_us, "bypass load balance interval in microseconds (0 (disable) to 10s)");
198 
199 #undef MODULE_PARAM_PREFIX
200 
201 #define CREATE_TRACE_POINTS
202 #include <trace/events/sched_ext.h>
203 
204 static void process_ddsp_deferred_locals(struct rq *rq);
205 static bool task_dead_and_done(struct task_struct *p);
206 static u32 reenq_local(struct rq *rq);
207 static void scx_kick_cpu(struct scx_sched *sch, s32 cpu, u64 flags);
208 static void scx_disable(struct scx_sched *sch, enum scx_exit_kind kind);
209 static bool scx_vexit(struct scx_sched *sch, enum scx_exit_kind kind,
210 		      s64 exit_code, const char *fmt, va_list args);
211 
212 static __printf(4, 5) bool scx_exit(struct scx_sched *sch,
213 				    enum scx_exit_kind kind, s64 exit_code,
214 				    const char *fmt, ...)
215 {
216 	va_list args;
217 	bool ret;
218 
219 	va_start(args, fmt);
220 	ret = scx_vexit(sch, kind, exit_code, fmt, args);
221 	va_end(args);
222 
223 	return ret;
224 }
225 
226 #define scx_error(sch, fmt, args...)	scx_exit((sch), SCX_EXIT_ERROR, 0, fmt, ##args)
227 #define scx_verror(sch, fmt, args)	scx_vexit((sch), SCX_EXIT_ERROR, 0, fmt, args)
228 
229 #define SCX_HAS_OP(sch, op)	test_bit(SCX_OP_IDX(op), (sch)->has_op)
230 
231 static long jiffies_delta_msecs(unsigned long at, unsigned long now)
232 {
233 	if (time_after(at, now))
234 		return jiffies_to_msecs(at - now);
235 	else
236 		return -(long)jiffies_to_msecs(now - at);
237 }
238 
239 /* if the highest set bit is N, return a mask with bits [N+1, 31] set */
240 static u32 higher_bits(u32 flags)
241 {
242 	return ~((1 << fls(flags)) - 1);
243 }
244 
245 /* return the mask with only the highest bit set */
246 static u32 highest_bit(u32 flags)
247 {
248 	int bit = fls(flags);
249 	return ((u64)1 << bit) >> 1;
250 }
251 
252 static bool u32_before(u32 a, u32 b)
253 {
254 	return (s32)(a - b) < 0;
255 }
256 
257 #ifdef CONFIG_EXT_SUB_SCHED
258 /**
259  * scx_parent - Find the parent sched
260  * @sch: sched to find the parent of
261  *
262  * Returns the parent scheduler or %NULL if @sch is root.
263  */
264 static struct scx_sched *scx_parent(struct scx_sched *sch)
265 {
266 	if (sch->level)
267 		return sch->ancestors[sch->level - 1];
268 	else
269 		return NULL;
270 }
271 
272 /**
273  * scx_next_descendant_pre - find the next descendant for pre-order walk
274  * @pos: the current position (%NULL to initiate traversal)
275  * @root: sched whose descendants to walk
276  *
277  * To be used by scx_for_each_descendant_pre(). Find the next descendant to
278  * visit for pre-order traversal of @root's descendants. @root is included in
279  * the iteration and the first node to be visited.
280  */
281 static struct scx_sched *scx_next_descendant_pre(struct scx_sched *pos,
282 						 struct scx_sched *root)
283 {
284 	struct scx_sched *next;
285 
286 	lockdep_assert(lockdep_is_held(&scx_enable_mutex) ||
287 		       lockdep_is_held(&scx_sched_lock));
288 
289 	/* if first iteration, visit @root */
290 	if (!pos)
291 		return root;
292 
293 	/* visit the first child if exists */
294 	next = list_first_entry_or_null(&pos->children, struct scx_sched, sibling);
295 	if (next)
296 		return next;
297 
298 	/* no child, visit my or the closest ancestor's next sibling */
299 	while (pos != root) {
300 		if (!list_is_last(&pos->sibling, &scx_parent(pos)->children))
301 			return list_next_entry(pos, sibling);
302 		pos = scx_parent(pos);
303 	}
304 
305 	return NULL;
306 }
307 
308 static void scx_set_task_sched(struct task_struct *p, struct scx_sched *sch)
309 {
310 	rcu_assign_pointer(p->scx.sched, sch);
311 }
312 #else	/* CONFIG_EXT_SUB_SCHED */
313 static struct scx_sched *scx_parent(struct scx_sched *sch) { return NULL; }
314 static struct scx_sched *scx_next_descendant_pre(struct scx_sched *pos, struct scx_sched *root) { return pos ? NULL : root; }
315 static void scx_set_task_sched(struct task_struct *p, struct scx_sched *sch) {}
316 #endif	/* CONFIG_EXT_SUB_SCHED */
317 
318 /**
319  * scx_is_descendant - Test whether sched is a descendant
320  * @sch: sched to test
321  * @ancestor: ancestor sched to test against
322  *
323  * Test whether @sch is a descendant of @ancestor.
324  */
325 static bool scx_is_descendant(struct scx_sched *sch, struct scx_sched *ancestor)
326 {
327 	if (sch->level < ancestor->level)
328 		return false;
329 	return sch->ancestors[ancestor->level] == ancestor;
330 }
331 
332 /**
333  * scx_for_each_descendant_pre - pre-order walk of a sched's descendants
334  * @pos: iteration cursor
335  * @root: sched to walk the descendants of
336  *
337  * Walk @root's descendants. @root is included in the iteration and the first
338  * node to be visited. Must be called with either scx_enable_mutex or
339  * scx_sched_lock held.
340  */
341 #define scx_for_each_descendant_pre(pos, root)					\
342 	for ((pos) = scx_next_descendant_pre(NULL, (root)); (pos);		\
343 	     (pos) = scx_next_descendant_pre((pos), (root)))
344 
345 static struct scx_dispatch_q *find_global_dsq(struct scx_sched *sch,
346 					      struct task_struct *p)
347 {
348 	return sch->global_dsqs[cpu_to_node(task_cpu(p))];
349 }
350 
351 static struct scx_dispatch_q *find_user_dsq(struct scx_sched *sch, u64 dsq_id)
352 {
353 	return rhashtable_lookup(&sch->dsq_hash, &dsq_id, dsq_hash_params);
354 }
355 
356 static const struct sched_class *scx_setscheduler_class(struct task_struct *p)
357 {
358 	if (p->sched_class == &stop_sched_class)
359 		return &stop_sched_class;
360 
361 	return __setscheduler_class(p->policy, p->prio);
362 }
363 
364 /*
365  * scx_kf_mask enforcement. Some kfuncs can only be called from specific SCX
366  * ops. When invoking SCX ops, SCX_CALL_OP[_RET]() should be used to indicate
367  * the allowed kfuncs and those kfuncs should use scx_kf_allowed() to check
368  * whether it's running from an allowed context.
369  *
370  * @mask is constant, always inline to cull the mask calculations.
371  */
372 static __always_inline void scx_kf_allow(u32 mask)
373 {
374 	/* nesting is allowed only in increasing scx_kf_mask order */
375 	WARN_ONCE((mask | higher_bits(mask)) & current->scx.kf_mask,
376 		  "invalid nesting current->scx.kf_mask=0x%x mask=0x%x\n",
377 		  current->scx.kf_mask, mask);
378 	current->scx.kf_mask |= mask;
379 	barrier();
380 }
381 
382 static void scx_kf_disallow(u32 mask)
383 {
384 	barrier();
385 	current->scx.kf_mask &= ~mask;
386 }
387 
388 /*
389  * Track the rq currently locked.
390  *
391  * This allows kfuncs to safely operate on rq from any scx ops callback,
392  * knowing which rq is already locked.
393  */
394 DEFINE_PER_CPU(struct rq *, scx_locked_rq_state);
395 
396 static inline void update_locked_rq(struct rq *rq)
397 {
398 	/*
399 	 * Check whether @rq is actually locked. This can help expose bugs
400 	 * or incorrect assumptions about the context in which a kfunc or
401 	 * callback is executed.
402 	 */
403 	if (rq)
404 		lockdep_assert_rq_held(rq);
405 	__this_cpu_write(scx_locked_rq_state, rq);
406 }
407 
408 #define SCX_CALL_OP(sch, mask, op, rq, args...)					\
409 do {										\
410 	if (rq)									\
411 		update_locked_rq(rq);						\
412 	if (mask) {								\
413 		scx_kf_allow(mask);						\
414 		(sch)->ops.op(args);						\
415 		scx_kf_disallow(mask);						\
416 	} else {								\
417 		(sch)->ops.op(args);						\
418 	}									\
419 	if (rq)									\
420 		update_locked_rq(NULL);						\
421 } while (0)
422 
423 #define SCX_CALL_OP_RET(sch, mask, op, rq, args...)				\
424 ({										\
425 	__typeof__((sch)->ops.op(args)) __ret;					\
426 										\
427 	if (rq)									\
428 		update_locked_rq(rq);						\
429 	if (mask) {								\
430 		scx_kf_allow(mask);						\
431 		__ret = (sch)->ops.op(args);					\
432 		scx_kf_disallow(mask);						\
433 	} else {								\
434 		__ret = (sch)->ops.op(args);					\
435 	}									\
436 	if (rq)									\
437 		update_locked_rq(NULL);						\
438 	__ret;									\
439 })
440 
441 /*
442  * Some kfuncs are allowed only on the tasks that are subjects of the
443  * in-progress scx_ops operation for, e.g., locking guarantees. To enforce such
444  * restrictions, the following SCX_CALL_OP_*() variants should be used when
445  * invoking scx_ops operations that take task arguments. These can only be used
446  * for non-nesting operations due to the way the tasks are tracked.
447  *
448  * kfuncs which can only operate on such tasks can in turn use
449  * scx_kf_allowed_on_arg_tasks() to test whether the invocation is allowed on
450  * the specific task.
451  */
452 #define SCX_CALL_OP_TASK(sch, mask, op, rq, task, args...)			\
453 do {										\
454 	BUILD_BUG_ON((mask) & ~__SCX_KF_TERMINAL);				\
455 	current->scx.kf_tasks[0] = task;					\
456 	SCX_CALL_OP((sch), mask, op, rq, task, ##args);				\
457 	current->scx.kf_tasks[0] = NULL;					\
458 } while (0)
459 
460 #define SCX_CALL_OP_TASK_RET(sch, mask, op, rq, task, args...)			\
461 ({										\
462 	__typeof__((sch)->ops.op(task, ##args)) __ret;				\
463 	BUILD_BUG_ON((mask) & ~__SCX_KF_TERMINAL);				\
464 	current->scx.kf_tasks[0] = task;					\
465 	__ret = SCX_CALL_OP_RET((sch), mask, op, rq, task, ##args);		\
466 	current->scx.kf_tasks[0] = NULL;					\
467 	__ret;									\
468 })
469 
470 #define SCX_CALL_OP_2TASKS_RET(sch, mask, op, rq, task0, task1, args...)	\
471 ({										\
472 	__typeof__((sch)->ops.op(task0, task1, ##args)) __ret;			\
473 	BUILD_BUG_ON((mask) & ~__SCX_KF_TERMINAL);				\
474 	current->scx.kf_tasks[0] = task0;					\
475 	current->scx.kf_tasks[1] = task1;					\
476 	__ret = SCX_CALL_OP_RET((sch), mask, op, rq, task0, task1, ##args);	\
477 	current->scx.kf_tasks[0] = NULL;					\
478 	current->scx.kf_tasks[1] = NULL;					\
479 	__ret;									\
480 })
481 
482 /* @mask is constant, always inline to cull unnecessary branches */
483 static __always_inline bool scx_kf_allowed(struct scx_sched *sch, u32 mask)
484 {
485 	if (unlikely(!(current->scx.kf_mask & mask))) {
486 		scx_error(sch, "kfunc with mask 0x%x called from an operation only allowing 0x%x",
487 			  mask, current->scx.kf_mask);
488 		return false;
489 	}
490 
491 	/*
492 	 * Enforce nesting boundaries. e.g. A kfunc which can be called from
493 	 * DISPATCH must not be called if we're running DEQUEUE which is nested
494 	 * inside ops.dispatch(). We don't need to check boundaries for any
495 	 * blocking kfuncs as the verifier ensures they're only called from
496 	 * sleepable progs.
497 	 */
498 	if (unlikely(highest_bit(mask) == SCX_KF_CPU_RELEASE &&
499 		     (current->scx.kf_mask & higher_bits(SCX_KF_CPU_RELEASE)))) {
500 		scx_error(sch, "cpu_release kfunc called from a nested operation");
501 		return false;
502 	}
503 
504 	if (unlikely(highest_bit(mask) == SCX_KF_DISPATCH &&
505 		     (current->scx.kf_mask & higher_bits(SCX_KF_DISPATCH)))) {
506 		scx_error(sch, "dispatch kfunc called from a nested operation");
507 		return false;
508 	}
509 
510 	return true;
511 }
512 
513 /* see SCX_CALL_OP_TASK() */
514 static __always_inline bool scx_kf_allowed_on_arg_tasks(struct scx_sched *sch,
515 							u32 mask,
516 							struct task_struct *p)
517 {
518 	if (!scx_kf_allowed(sch, mask))
519 		return false;
520 
521 	if (unlikely((p != current->scx.kf_tasks[0] &&
522 		      p != current->scx.kf_tasks[1]))) {
523 		scx_error(sch, "called on a task not being operated on");
524 		return false;
525 	}
526 
527 	return true;
528 }
529 
530 /**
531  * nldsq_next_task - Iterate to the next task in a non-local DSQ
532  * @dsq: user dsq being iterated
533  * @cur: current position, %NULL to start iteration
534  * @rev: walk backwards
535  *
536  * Returns %NULL when iteration is finished.
537  */
538 static struct task_struct *nldsq_next_task(struct scx_dispatch_q *dsq,
539 					   struct task_struct *cur, bool rev)
540 {
541 	struct list_head *list_node;
542 	struct scx_dsq_list_node *dsq_lnode;
543 
544 	lockdep_assert_held(&dsq->lock);
545 
546 	if (cur)
547 		list_node = &cur->scx.dsq_list.node;
548 	else
549 		list_node = &dsq->list;
550 
551 	/* find the next task, need to skip BPF iteration cursors */
552 	do {
553 		if (rev)
554 			list_node = list_node->prev;
555 		else
556 			list_node = list_node->next;
557 
558 		if (list_node == &dsq->list)
559 			return NULL;
560 
561 		dsq_lnode = container_of(list_node, struct scx_dsq_list_node,
562 					 node);
563 	} while (dsq_lnode->flags & SCX_DSQ_LNODE_ITER_CURSOR);
564 
565 	return container_of(dsq_lnode, struct task_struct, scx.dsq_list);
566 }
567 
568 #define nldsq_for_each_task(p, dsq)						\
569 	for ((p) = nldsq_next_task((dsq), NULL, false); (p);			\
570 	     (p) = nldsq_next_task((dsq), (p), false))
571 
572 
573 /*
574  * BPF DSQ iterator. Tasks in a non-local DSQ can be iterated in [reverse]
575  * dispatch order. BPF-visible iterator is opaque and larger to allow future
576  * changes without breaking backward compatibility. Can be used with
577  * bpf_for_each(). See bpf_iter_scx_dsq_*().
578  */
579 enum scx_dsq_iter_flags {
580 	/* iterate in the reverse dispatch order */
581 	SCX_DSQ_ITER_REV		= 1U << 16,
582 
583 	__SCX_DSQ_ITER_HAS_SLICE	= 1U << 30,
584 	__SCX_DSQ_ITER_HAS_VTIME	= 1U << 31,
585 
586 	__SCX_DSQ_ITER_USER_FLAGS	= SCX_DSQ_ITER_REV,
587 	__SCX_DSQ_ITER_ALL_FLAGS	= __SCX_DSQ_ITER_USER_FLAGS |
588 					  __SCX_DSQ_ITER_HAS_SLICE |
589 					  __SCX_DSQ_ITER_HAS_VTIME,
590 };
591 
592 struct bpf_iter_scx_dsq_kern {
593 	struct scx_dsq_list_node	cursor;
594 	struct scx_dispatch_q		*dsq;
595 	u64				slice;
596 	u64				vtime;
597 } __attribute__((aligned(8)));
598 
599 struct bpf_iter_scx_dsq {
600 	u64				__opaque[6];
601 } __attribute__((aligned(8)));
602 
603 
604 /*
605  * SCX task iterator.
606  */
607 struct scx_task_iter {
608 	struct sched_ext_entity		cursor;
609 	struct task_struct		*locked_task;
610 	struct rq			*rq;
611 	struct rq_flags			rf;
612 	u32				cnt;
613 	bool				list_locked;
614 #ifdef CONFIG_EXT_SUB_SCHED
615 	struct cgroup			*cgrp;
616 	struct cgroup_subsys_state	*css_pos;
617 	struct css_task_iter		css_iter;
618 #endif
619 };
620 
621 /**
622  * scx_task_iter_start - Lock scx_tasks_lock and start a task iteration
623  * @iter: iterator to init
624  * @cgrp: Optional root of cgroup subhierarchy to iterate
625  *
626  * Initialize @iter. Once initialized, @iter must eventually be stopped with
627  * scx_task_iter_stop().
628  *
629  * If @cgrp is %NULL, scx_tasks is used for iteration and this function returns
630  * with scx_tasks_lock held and @iter->cursor inserted into scx_tasks.
631  *
632  * If @cgrp is not %NULL, @cgrp and its descendants' tasks are walked using
633  * @iter->css_iter. The caller must be holding cgroup_lock() to prevent cgroup
634  * task migrations.
635  *
636  * The two modes of iterations are largely independent and it's likely that
637  * scx_tasks can be removed in favor of always using cgroup iteration if
638  * CONFIG_SCHED_CLASS_EXT depends on CONFIG_CGROUPS.
639  *
640  * scx_tasks_lock and the rq lock may be released using scx_task_iter_unlock()
641  * between this and the first next() call or between any two next() calls. If
642  * the locks are released between two next() calls, the caller is responsible
643  * for ensuring that the task being iterated remains accessible either through
644  * RCU read lock or obtaining a reference count.
645  *
646  * All tasks which existed when the iteration started are guaranteed to be
647  * visited as long as they are not dead.
648  */
649 static void scx_task_iter_start(struct scx_task_iter *iter, struct cgroup *cgrp)
650 {
651 	memset(iter, 0, sizeof(*iter));
652 
653 #ifdef CONFIG_EXT_SUB_SCHED
654 	if (cgrp) {
655 		lockdep_assert_held(&cgroup_mutex);
656 		iter->cgrp = cgrp;
657 		iter->css_pos = css_next_descendant_pre(NULL, &iter->cgrp->self);
658 		css_task_iter_start(iter->css_pos, 0, &iter->css_iter);
659 		return;
660 	}
661 #endif
662 	raw_spin_lock_irq(&scx_tasks_lock);
663 
664 	iter->cursor = (struct sched_ext_entity){ .flags = SCX_TASK_CURSOR };
665 	list_add(&iter->cursor.tasks_node, &scx_tasks);
666 	iter->list_locked = true;
667 }
668 
669 static void __scx_task_iter_rq_unlock(struct scx_task_iter *iter)
670 {
671 	if (iter->locked_task) {
672 		__balance_callbacks(iter->rq, &iter->rf);
673 		task_rq_unlock(iter->rq, iter->locked_task, &iter->rf);
674 		iter->locked_task = NULL;
675 	}
676 }
677 
678 /**
679  * scx_task_iter_unlock - Unlock rq and scx_tasks_lock held by a task iterator
680  * @iter: iterator to unlock
681  *
682  * If @iter is in the middle of a locked iteration, it may be locking the rq of
683  * the task currently being visited in addition to scx_tasks_lock. Unlock both.
684  * This function can be safely called anytime during an iteration. The next
685  * iterator operation will automatically restore the necessary locking.
686  */
687 static void scx_task_iter_unlock(struct scx_task_iter *iter)
688 {
689 	__scx_task_iter_rq_unlock(iter);
690 	if (iter->list_locked) {
691 		iter->list_locked = false;
692 		raw_spin_unlock_irq(&scx_tasks_lock);
693 	}
694 }
695 
696 static void __scx_task_iter_maybe_relock(struct scx_task_iter *iter)
697 {
698 	if (!iter->list_locked) {
699 		raw_spin_lock_irq(&scx_tasks_lock);
700 		iter->list_locked = true;
701 	}
702 }
703 
704 /**
705  * scx_task_iter_stop - Stop a task iteration and unlock scx_tasks_lock
706  * @iter: iterator to exit
707  *
708  * Exit a previously initialized @iter. Must be called with scx_tasks_lock held
709  * which is released on return. If the iterator holds a task's rq lock, that rq
710  * lock is also released. See scx_task_iter_start() for details.
711  */
712 static void scx_task_iter_stop(struct scx_task_iter *iter)
713 {
714 #ifdef CONFIG_EXT_SUB_SCHED
715 	if (iter->cgrp) {
716 		if (iter->css_pos)
717 			css_task_iter_end(&iter->css_iter);
718 		__scx_task_iter_rq_unlock(iter);
719 		return;
720 	}
721 #endif
722 	__scx_task_iter_maybe_relock(iter);
723 	list_del_init(&iter->cursor.tasks_node);
724 	scx_task_iter_unlock(iter);
725 }
726 
727 /**
728  * scx_task_iter_next - Next task
729  * @iter: iterator to walk
730  *
731  * Visit the next task. See scx_task_iter_start() for details. Locks are dropped
732  * and re-acquired every %SCX_TASK_ITER_BATCH iterations to avoid causing stalls
733  * by holding scx_tasks_lock for too long.
734  */
735 static struct task_struct *scx_task_iter_next(struct scx_task_iter *iter)
736 {
737 	struct list_head *cursor = &iter->cursor.tasks_node;
738 	struct sched_ext_entity *pos;
739 
740 	if (!(++iter->cnt % SCX_TASK_ITER_BATCH)) {
741 		scx_task_iter_unlock(iter);
742 		cond_resched();
743 	}
744 
745 #ifdef CONFIG_EXT_SUB_SCHED
746 	if (iter->cgrp) {
747 		while (iter->css_pos) {
748 			struct task_struct *p;
749 
750 			p = css_task_iter_next(&iter->css_iter);
751 			if (p)
752 				return p;
753 
754 			css_task_iter_end(&iter->css_iter);
755 			iter->css_pos = css_next_descendant_pre(iter->css_pos,
756 								&iter->cgrp->self);
757 			if (iter->css_pos)
758 				css_task_iter_start(iter->css_pos, 0, &iter->css_iter);
759 		}
760 		return NULL;
761 	}
762 #endif
763 	__scx_task_iter_maybe_relock(iter);
764 
765 	list_for_each_entry(pos, cursor, tasks_node) {
766 		if (&pos->tasks_node == &scx_tasks)
767 			return NULL;
768 		if (!(pos->flags & SCX_TASK_CURSOR)) {
769 			list_move(cursor, &pos->tasks_node);
770 			return container_of(pos, struct task_struct, scx);
771 		}
772 	}
773 
774 	/* can't happen, should always terminate at scx_tasks above */
775 	BUG();
776 }
777 
778 /**
779  * scx_task_iter_next_locked - Next non-idle task with its rq locked
780  * @iter: iterator to walk
781  *
782  * Visit the non-idle task with its rq lock held. Allows callers to specify
783  * whether they would like to filter out dead tasks. See scx_task_iter_start()
784  * for details.
785  */
786 static struct task_struct *scx_task_iter_next_locked(struct scx_task_iter *iter)
787 {
788 	struct task_struct *p;
789 
790 	__scx_task_iter_rq_unlock(iter);
791 
792 	while ((p = scx_task_iter_next(iter))) {
793 		/*
794 		 * scx_task_iter is used to prepare and move tasks into SCX
795 		 * while loading the BPF scheduler and vice-versa while
796 		 * unloading. The init_tasks ("swappers") should be excluded
797 		 * from the iteration because:
798 		 *
799 		 * - It's unsafe to use __setschduler_prio() on an init_task to
800 		 *   determine the sched_class to use as it won't preserve its
801 		 *   idle_sched_class.
802 		 *
803 		 * - ops.init/exit_task() can easily be confused if called with
804 		 *   init_tasks as they, e.g., share PID 0.
805 		 *
806 		 * As init_tasks are never scheduled through SCX, they can be
807 		 * skipped safely. Note that is_idle_task() which tests %PF_IDLE
808 		 * doesn't work here:
809 		 *
810 		 * - %PF_IDLE may not be set for an init_task whose CPU hasn't
811 		 *   yet been onlined.
812 		 *
813 		 * - %PF_IDLE can be set on tasks that are not init_tasks. See
814 		 *   play_idle_precise() used by CONFIG_IDLE_INJECT.
815 		 *
816 		 * Test for idle_sched_class as only init_tasks are on it.
817 		 */
818 		if (p->sched_class != &idle_sched_class)
819 			break;
820 	}
821 	if (!p)
822 		return NULL;
823 
824 	iter->rq = task_rq_lock(p, &iter->rf);
825 	iter->locked_task = p;
826 
827 	return p;
828 }
829 
830 /**
831  * scx_add_event - Increase an event counter for 'name' by 'cnt'
832  * @sch: scx_sched to account events for
833  * @name: an event name defined in struct scx_event_stats
834  * @cnt: the number of the event occurred
835  *
836  * This can be used when preemption is not disabled.
837  */
838 #define scx_add_event(sch, name, cnt) do {					\
839 	this_cpu_add((sch)->pcpu->event_stats.name, (cnt));			\
840 	trace_sched_ext_event(#name, (cnt));					\
841 } while(0)
842 
843 /**
844  * __scx_add_event - Increase an event counter for 'name' by 'cnt'
845  * @sch: scx_sched to account events for
846  * @name: an event name defined in struct scx_event_stats
847  * @cnt: the number of the event occurred
848  *
849  * This should be used only when preemption is disabled.
850  */
851 #define __scx_add_event(sch, name, cnt) do {					\
852 	__this_cpu_add((sch)->pcpu->event_stats.name, (cnt));			\
853 	trace_sched_ext_event(#name, cnt);					\
854 } while(0)
855 
856 /**
857  * scx_agg_event - Aggregate an event counter 'kind' from 'src_e' to 'dst_e'
858  * @dst_e: destination event stats
859  * @src_e: source event stats
860  * @kind: a kind of event to be aggregated
861  */
862 #define scx_agg_event(dst_e, src_e, kind) do {					\
863 	(dst_e)->kind += READ_ONCE((src_e)->kind);				\
864 } while(0)
865 
866 /**
867  * scx_dump_event - Dump an event 'kind' in 'events' to 's'
868  * @s: output seq_buf
869  * @events: event stats
870  * @kind: a kind of event to dump
871  */
872 #define scx_dump_event(s, events, kind) do {					\
873 	dump_line(&(s), "%40s: %16lld", #kind, (events)->kind);			\
874 } while (0)
875 
876 
877 static void scx_read_events(struct scx_sched *sch,
878 			    struct scx_event_stats *events);
879 
880 static enum scx_enable_state scx_enable_state(void)
881 {
882 	return atomic_read(&scx_enable_state_var);
883 }
884 
885 static enum scx_enable_state scx_set_enable_state(enum scx_enable_state to)
886 {
887 	return atomic_xchg(&scx_enable_state_var, to);
888 }
889 
890 static bool scx_tryset_enable_state(enum scx_enable_state to,
891 				    enum scx_enable_state from)
892 {
893 	int from_v = from;
894 
895 	return atomic_try_cmpxchg(&scx_enable_state_var, &from_v, to);
896 }
897 
898 /**
899  * wait_ops_state - Busy-wait the specified ops state to end
900  * @p: target task
901  * @opss: state to wait the end of
902  *
903  * Busy-wait for @p to transition out of @opss. This can only be used when the
904  * state part of @opss is %SCX_QUEUEING or %SCX_DISPATCHING. This function also
905  * has load_acquire semantics to ensure that the caller can see the updates made
906  * in the enqueueing and dispatching paths.
907  */
908 static void wait_ops_state(struct task_struct *p, unsigned long opss)
909 {
910 	do {
911 		cpu_relax();
912 	} while (atomic_long_read_acquire(&p->scx.ops_state) == opss);
913 }
914 
915 static inline bool __cpu_valid(s32 cpu)
916 {
917 	return likely(cpu >= 0 && cpu < nr_cpu_ids && cpu_possible(cpu));
918 }
919 
920 /**
921  * ops_cpu_valid - Verify a cpu number, to be used on ops input args
922  * @sch: scx_sched to abort on error
923  * @cpu: cpu number which came from a BPF ops
924  * @where: extra information reported on error
925  *
926  * @cpu is a cpu number which came from the BPF scheduler and can be any value.
927  * Verify that it is in range and one of the possible cpus. If invalid, trigger
928  * an ops error.
929  */
930 static bool ops_cpu_valid(struct scx_sched *sch, s32 cpu, const char *where)
931 {
932 	if (__cpu_valid(cpu)) {
933 		return true;
934 	} else {
935 		scx_error(sch, "invalid CPU %d%s%s", cpu, where ? " " : "", where ?: "");
936 		return false;
937 	}
938 }
939 
940 /**
941  * ops_sanitize_err - Sanitize a -errno value
942  * @sch: scx_sched to error out on error
943  * @ops_name: operation to blame on failure
944  * @err: -errno value to sanitize
945  *
946  * Verify @err is a valid -errno. If not, trigger scx_error() and return
947  * -%EPROTO. This is necessary because returning a rogue -errno up the chain can
948  * cause misbehaviors. For an example, a large negative return from
949  * ops.init_task() triggers an oops when passed up the call chain because the
950  * value fails IS_ERR() test after being encoded with ERR_PTR() and then is
951  * handled as a pointer.
952  */
953 static int ops_sanitize_err(struct scx_sched *sch, const char *ops_name, s32 err)
954 {
955 	if (err < 0 && err >= -MAX_ERRNO)
956 		return err;
957 
958 	scx_error(sch, "ops.%s() returned an invalid errno %d", ops_name, err);
959 	return -EPROTO;
960 }
961 
962 static void run_deferred(struct rq *rq)
963 {
964 	process_ddsp_deferred_locals(rq);
965 
966 	if (local_read(&rq->scx.reenq_local_deferred)) {
967 		local_set(&rq->scx.reenq_local_deferred, 0);
968 		reenq_local(rq);
969 	}
970 }
971 
972 static void deferred_bal_cb_workfn(struct rq *rq)
973 {
974 	run_deferred(rq);
975 }
976 
977 static void deferred_irq_workfn(struct irq_work *irq_work)
978 {
979 	struct rq *rq = container_of(irq_work, struct rq, scx.deferred_irq_work);
980 
981 	raw_spin_rq_lock(rq);
982 	run_deferred(rq);
983 	raw_spin_rq_unlock(rq);
984 }
985 
986 /**
987  * schedule_deferred - Schedule execution of deferred actions on an rq
988  * @rq: target rq
989  *
990  * Schedule execution of deferred actions on @rq. Deferred actions are executed
991  * with @rq locked but unpinned, and thus can unlock @rq to e.g. migrate tasks
992  * to other rqs.
993  */
994 static void schedule_deferred(struct rq *rq)
995 {
996 	/*
997 	 * Queue an irq work. They are executed on IRQ re-enable which may take
998 	 * a bit longer than the scheduler hook in schedule_deferred_locked().
999 	 */
1000 	irq_work_queue(&rq->scx.deferred_irq_work);
1001 }
1002 
1003 /**
1004  * schedule_deferred_locked - Schedule execution of deferred actions on an rq
1005  * @rq: target rq
1006  *
1007  * Schedule execution of deferred actions on @rq. Equivalent to
1008  * schedule_deferred() but requires @rq to be locked and can be more efficient.
1009  */
1010 static void schedule_deferred_locked(struct rq *rq)
1011 {
1012 	lockdep_assert_rq_held(rq);
1013 
1014 	/*
1015 	 * If in the middle of waking up a task, task_woken_scx() will be called
1016 	 * afterwards which will then run the deferred actions, no need to
1017 	 * schedule anything.
1018 	 */
1019 	if (rq->scx.flags & SCX_RQ_IN_WAKEUP)
1020 		return;
1021 
1022 	/* Don't do anything if there already is a deferred operation. */
1023 	if (rq->scx.flags & SCX_RQ_BAL_CB_PENDING)
1024 		return;
1025 
1026 	/*
1027 	 * If in balance, the balance callbacks will be called before rq lock is
1028 	 * released. Schedule one.
1029 	 *
1030 	 *
1031 	 * We can't directly insert the callback into the
1032 	 * rq's list: The call can drop its lock and make the pending balance
1033 	 * callback visible to unrelated code paths that call rq_pin_lock().
1034 	 *
1035 	 * Just let balance_one() know that it must do it itself.
1036 	 */
1037 	if (rq->scx.flags & SCX_RQ_IN_BALANCE) {
1038 		rq->scx.flags |= SCX_RQ_BAL_CB_PENDING;
1039 		return;
1040 	}
1041 
1042 	/*
1043 	 * No scheduler hooks available. Use the generic irq_work path. The
1044 	 * above WAKEUP and BALANCE paths should cover most of the cases and the
1045 	 * time to IRQ re-enable shouldn't be long.
1046 	 */
1047 	schedule_deferred(rq);
1048 }
1049 
1050 /**
1051  * touch_core_sched - Update timestamp used for core-sched task ordering
1052  * @rq: rq to read clock from, must be locked
1053  * @p: task to update the timestamp for
1054  *
1055  * Update @p->scx.core_sched_at timestamp. This is used by scx_prio_less() to
1056  * implement global or local-DSQ FIFO ordering for core-sched. Should be called
1057  * when a task becomes runnable and its turn on the CPU ends (e.g. slice
1058  * exhaustion).
1059  */
1060 static void touch_core_sched(struct rq *rq, struct task_struct *p)
1061 {
1062 	lockdep_assert_rq_held(rq);
1063 
1064 #ifdef CONFIG_SCHED_CORE
1065 	/*
1066 	 * It's okay to update the timestamp spuriously. Use
1067 	 * sched_core_disabled() which is cheaper than enabled().
1068 	 *
1069 	 * As this is used to determine ordering between tasks of sibling CPUs,
1070 	 * it may be better to use per-core dispatch sequence instead.
1071 	 */
1072 	if (!sched_core_disabled())
1073 		p->scx.core_sched_at = sched_clock_cpu(cpu_of(rq));
1074 #endif
1075 }
1076 
1077 /**
1078  * touch_core_sched_dispatch - Update core-sched timestamp on dispatch
1079  * @rq: rq to read clock from, must be locked
1080  * @p: task being dispatched
1081  *
1082  * If the BPF scheduler implements custom core-sched ordering via
1083  * ops.core_sched_before(), @p->scx.core_sched_at is used to implement FIFO
1084  * ordering within each local DSQ. This function is called from dispatch paths
1085  * and updates @p->scx.core_sched_at if custom core-sched ordering is in effect.
1086  */
1087 static void touch_core_sched_dispatch(struct rq *rq, struct task_struct *p)
1088 {
1089 	lockdep_assert_rq_held(rq);
1090 
1091 #ifdef CONFIG_SCHED_CORE
1092 	if (unlikely(SCX_HAS_OP(scx_root, core_sched_before)))
1093 		touch_core_sched(rq, p);
1094 #endif
1095 }
1096 
1097 static void update_curr_scx(struct rq *rq)
1098 {
1099 	struct task_struct *curr = rq->curr;
1100 	s64 delta_exec;
1101 
1102 	delta_exec = update_curr_common(rq);
1103 	if (unlikely(delta_exec <= 0))
1104 		return;
1105 
1106 	if (curr->scx.slice != SCX_SLICE_INF) {
1107 		curr->scx.slice -= min_t(u64, curr->scx.slice, delta_exec);
1108 		if (!curr->scx.slice)
1109 			touch_core_sched(rq, curr);
1110 	}
1111 
1112 	dl_server_update(&rq->ext_server, delta_exec);
1113 }
1114 
1115 static bool scx_dsq_priq_less(struct rb_node *node_a,
1116 			      const struct rb_node *node_b)
1117 {
1118 	const struct task_struct *a =
1119 		container_of(node_a, struct task_struct, scx.dsq_priq);
1120 	const struct task_struct *b =
1121 		container_of(node_b, struct task_struct, scx.dsq_priq);
1122 
1123 	return time_before64(a->scx.dsq_vtime, b->scx.dsq_vtime);
1124 }
1125 
1126 static void dsq_mod_nr(struct scx_dispatch_q *dsq, s32 delta)
1127 {
1128 	/*
1129 	 * scx_bpf_dsq_nr_queued() reads ->nr without locking. Use READ_ONCE()
1130 	 * on the read side and WRITE_ONCE() on the write side to properly
1131 	 * annotate the concurrent lockless access and avoid KCSAN warnings.
1132 	 */
1133 	WRITE_ONCE(dsq->nr, READ_ONCE(dsq->nr) + delta);
1134 }
1135 
1136 static void refill_task_slice_dfl(struct scx_sched *sch, struct task_struct *p)
1137 {
1138 	p->scx.slice = READ_ONCE(scx_slice_dfl);
1139 	__scx_add_event(sch, SCX_EV_REFILL_SLICE_DFL, 1);
1140 }
1141 
1142 /*
1143  * Return true if @p is moving due to an internal SCX migration, false
1144  * otherwise.
1145  */
1146 static inline bool task_scx_migrating(struct task_struct *p)
1147 {
1148 	/*
1149 	 * We only need to check sticky_cpu: it is set to the destination
1150 	 * CPU in move_remote_task_to_local_dsq() before deactivate_task()
1151 	 * and cleared when the task is enqueued on the destination, so it
1152 	 * is only non-negative during an internal SCX migration.
1153 	 */
1154 	return p->scx.sticky_cpu >= 0;
1155 }
1156 
1157 /*
1158  * Call ops.dequeue() if the task is in BPF custody and not migrating.
1159  * Clears %SCX_TASK_IN_CUSTODY when the callback is invoked.
1160  */
1161 static void call_task_dequeue(struct scx_sched *sch, struct rq *rq,
1162 			      struct task_struct *p, u64 deq_flags)
1163 {
1164 	if (!(p->scx.flags & SCX_TASK_IN_CUSTODY) || task_scx_migrating(p))
1165 		return;
1166 
1167 	if (SCX_HAS_OP(sch, dequeue))
1168 		SCX_CALL_OP_TASK(sch, SCX_KF_REST, dequeue, rq, p, deq_flags);
1169 
1170 	p->scx.flags &= ~SCX_TASK_IN_CUSTODY;
1171 }
1172 
1173 static void local_dsq_post_enq(struct scx_dispatch_q *dsq, struct task_struct *p,
1174 			       u64 enq_flags)
1175 {
1176 	struct rq *rq = container_of(dsq, struct rq, scx.local_dsq);
1177 	bool preempt = false;
1178 
1179 	call_task_dequeue(scx_root, rq, p, 0);
1180 
1181 	/*
1182 	 * If @rq is in balance, the CPU is already vacant and looking for the
1183 	 * next task to run. No need to preempt or trigger resched after moving
1184 	 * @p into its local DSQ.
1185 	 */
1186 	if (rq->scx.flags & SCX_RQ_IN_BALANCE)
1187 		return;
1188 
1189 	if ((enq_flags & SCX_ENQ_PREEMPT) && p != rq->curr &&
1190 	    rq->curr->sched_class == &ext_sched_class) {
1191 		rq->curr->scx.slice = 0;
1192 		preempt = true;
1193 	}
1194 
1195 	if (preempt || sched_class_above(&ext_sched_class, rq->curr->sched_class))
1196 		resched_curr(rq);
1197 }
1198 
1199 static void dispatch_enqueue(struct scx_sched *sch, struct rq *rq,
1200 			     struct scx_dispatch_q *dsq, struct task_struct *p,
1201 			     u64 enq_flags)
1202 {
1203 	bool is_local = dsq->id == SCX_DSQ_LOCAL;
1204 
1205 	WARN_ON_ONCE(p->scx.dsq || !list_empty(&p->scx.dsq_list.node));
1206 	WARN_ON_ONCE((p->scx.dsq_flags & SCX_TASK_DSQ_ON_PRIQ) ||
1207 		     !RB_EMPTY_NODE(&p->scx.dsq_priq));
1208 
1209 	if (!is_local) {
1210 		raw_spin_lock_nested(&dsq->lock,
1211 			(enq_flags & SCX_ENQ_NESTED) ? SINGLE_DEPTH_NESTING : 0);
1212 
1213 		if (unlikely(dsq->id == SCX_DSQ_INVALID)) {
1214 			scx_error(sch, "attempting to dispatch to a destroyed dsq");
1215 			/* fall back to the global dsq */
1216 			raw_spin_unlock(&dsq->lock);
1217 			dsq = find_global_dsq(sch, p);
1218 			raw_spin_lock(&dsq->lock);
1219 		}
1220 	}
1221 
1222 	if (unlikely((dsq->id & SCX_DSQ_FLAG_BUILTIN) &&
1223 		     (enq_flags & SCX_ENQ_DSQ_PRIQ))) {
1224 		/*
1225 		 * SCX_DSQ_LOCAL and SCX_DSQ_GLOBAL DSQs always consume from
1226 		 * their FIFO queues. To avoid confusion and accidentally
1227 		 * starving vtime-dispatched tasks by FIFO-dispatched tasks, we
1228 		 * disallow any internal DSQ from doing vtime ordering of
1229 		 * tasks.
1230 		 */
1231 		scx_error(sch, "cannot use vtime ordering for built-in DSQs");
1232 		enq_flags &= ~SCX_ENQ_DSQ_PRIQ;
1233 	}
1234 
1235 	if (enq_flags & SCX_ENQ_DSQ_PRIQ) {
1236 		struct rb_node *rbp;
1237 
1238 		/*
1239 		 * A PRIQ DSQ shouldn't be using FIFO enqueueing. As tasks are
1240 		 * linked to both the rbtree and list on PRIQs, this can only be
1241 		 * tested easily when adding the first task.
1242 		 */
1243 		if (unlikely(RB_EMPTY_ROOT(&dsq->priq) &&
1244 			     nldsq_next_task(dsq, NULL, false)))
1245 			scx_error(sch, "DSQ ID 0x%016llx already had FIFO-enqueued tasks",
1246 				  dsq->id);
1247 
1248 		p->scx.dsq_flags |= SCX_TASK_DSQ_ON_PRIQ;
1249 		rb_add(&p->scx.dsq_priq, &dsq->priq, scx_dsq_priq_less);
1250 
1251 		/*
1252 		 * Find the previous task and insert after it on the list so
1253 		 * that @dsq->list is vtime ordered.
1254 		 */
1255 		rbp = rb_prev(&p->scx.dsq_priq);
1256 		if (rbp) {
1257 			struct task_struct *prev =
1258 				container_of(rbp, struct task_struct,
1259 					     scx.dsq_priq);
1260 			list_add(&p->scx.dsq_list.node, &prev->scx.dsq_list.node);
1261 			/* first task unchanged - no update needed */
1262 		} else {
1263 			list_add(&p->scx.dsq_list.node, &dsq->list);
1264 			/* not builtin and new task is at head - use fastpath */
1265 			rcu_assign_pointer(dsq->first_task, p);
1266 		}
1267 	} else {
1268 		/* a FIFO DSQ shouldn't be using PRIQ enqueuing */
1269 		if (unlikely(!RB_EMPTY_ROOT(&dsq->priq)))
1270 			scx_error(sch, "DSQ ID 0x%016llx already had PRIQ-enqueued tasks",
1271 				  dsq->id);
1272 
1273 		if (enq_flags & (SCX_ENQ_HEAD | SCX_ENQ_PREEMPT)) {
1274 			list_add(&p->scx.dsq_list.node, &dsq->list);
1275 			/* new task inserted at head - use fastpath */
1276 			if (!(dsq->id & SCX_DSQ_FLAG_BUILTIN))
1277 				rcu_assign_pointer(dsq->first_task, p);
1278 		} else {
1279 			bool was_empty;
1280 
1281 			was_empty = list_empty(&dsq->list);
1282 			list_add_tail(&p->scx.dsq_list.node, &dsq->list);
1283 			if (was_empty && !(dsq->id & SCX_DSQ_FLAG_BUILTIN))
1284 				rcu_assign_pointer(dsq->first_task, p);
1285 		}
1286 	}
1287 
1288 	/* seq records the order tasks are queued, used by BPF DSQ iterator */
1289 	WRITE_ONCE(dsq->seq, dsq->seq + 1);
1290 	p->scx.dsq_seq = dsq->seq;
1291 
1292 	dsq_mod_nr(dsq, 1);
1293 	p->scx.dsq = dsq;
1294 
1295 	/*
1296 	 * scx.ddsp_dsq_id and scx.ddsp_enq_flags are only relevant on the
1297 	 * direct dispatch path, but we clear them here because the direct
1298 	 * dispatch verdict may be overridden on the enqueue path during e.g.
1299 	 * bypass.
1300 	 */
1301 	p->scx.ddsp_dsq_id = SCX_DSQ_INVALID;
1302 	p->scx.ddsp_enq_flags = 0;
1303 
1304 	/*
1305 	 * Update custody and call ops.dequeue() before clearing ops_state:
1306 	 * once ops_state is cleared, waiters in ops_dequeue() can proceed
1307 	 * and dequeue_task_scx() will RMW p->scx.flags. If we clear
1308 	 * ops_state first, both sides would modify p->scx.flags
1309 	 * concurrently in a non-atomic way.
1310 	 */
1311 	if (is_local) {
1312 		local_dsq_post_enq(dsq, p, enq_flags);
1313 	} else {
1314 		/*
1315 		 * Task on global/bypass DSQ: leave custody, task on
1316 		 * non-terminal DSQ: enter custody.
1317 		 */
1318 		if (dsq->id == SCX_DSQ_GLOBAL || dsq->id == SCX_DSQ_BYPASS)
1319 			call_task_dequeue(sch, rq, p, 0);
1320 		else
1321 			p->scx.flags |= SCX_TASK_IN_CUSTODY;
1322 
1323 		raw_spin_unlock(&dsq->lock);
1324 	}
1325 
1326 	/*
1327 	 * We're transitioning out of QUEUEING or DISPATCHING. store_release to
1328 	 * match waiters' load_acquire.
1329 	 */
1330 	if (enq_flags & SCX_ENQ_CLEAR_OPSS)
1331 		atomic_long_set_release(&p->scx.ops_state, SCX_OPSS_NONE);
1332 }
1333 
1334 static void task_unlink_from_dsq(struct task_struct *p,
1335 				 struct scx_dispatch_q *dsq)
1336 {
1337 	WARN_ON_ONCE(list_empty(&p->scx.dsq_list.node));
1338 
1339 	if (p->scx.dsq_flags & SCX_TASK_DSQ_ON_PRIQ) {
1340 		rb_erase(&p->scx.dsq_priq, &dsq->priq);
1341 		RB_CLEAR_NODE(&p->scx.dsq_priq);
1342 		p->scx.dsq_flags &= ~SCX_TASK_DSQ_ON_PRIQ;
1343 	}
1344 
1345 	list_del_init(&p->scx.dsq_list.node);
1346 	dsq_mod_nr(dsq, -1);
1347 
1348 	if (!(dsq->id & SCX_DSQ_FLAG_BUILTIN) && dsq->first_task == p) {
1349 		struct task_struct *first_task;
1350 
1351 		first_task = nldsq_next_task(dsq, NULL, false);
1352 		rcu_assign_pointer(dsq->first_task, first_task);
1353 	}
1354 }
1355 
1356 static void dispatch_dequeue(struct rq *rq, struct task_struct *p)
1357 {
1358 	struct scx_dispatch_q *dsq = p->scx.dsq;
1359 	bool is_local = dsq == &rq->scx.local_dsq;
1360 
1361 	lockdep_assert_rq_held(rq);
1362 
1363 	if (!dsq) {
1364 		/*
1365 		 * If !dsq && on-list, @p is on @rq's ddsp_deferred_locals.
1366 		 * Unlinking is all that's needed to cancel.
1367 		 */
1368 		if (unlikely(!list_empty(&p->scx.dsq_list.node)))
1369 			list_del_init(&p->scx.dsq_list.node);
1370 
1371 		/*
1372 		 * When dispatching directly from the BPF scheduler to a local
1373 		 * DSQ, the task isn't associated with any DSQ but
1374 		 * @p->scx.holding_cpu may be set under the protection of
1375 		 * %SCX_OPSS_DISPATCHING.
1376 		 */
1377 		if (p->scx.holding_cpu >= 0)
1378 			p->scx.holding_cpu = -1;
1379 
1380 		return;
1381 	}
1382 
1383 	if (!is_local)
1384 		raw_spin_lock(&dsq->lock);
1385 
1386 	/*
1387 	 * Now that we hold @dsq->lock, @p->holding_cpu and @p->scx.dsq_* can't
1388 	 * change underneath us.
1389 	*/
1390 	if (p->scx.holding_cpu < 0) {
1391 		/* @p must still be on @dsq, dequeue */
1392 		task_unlink_from_dsq(p, dsq);
1393 	} else {
1394 		/*
1395 		 * We're racing against dispatch_to_local_dsq() which already
1396 		 * removed @p from @dsq and set @p->scx.holding_cpu. Clear the
1397 		 * holding_cpu which tells dispatch_to_local_dsq() that it lost
1398 		 * the race.
1399 		 */
1400 		WARN_ON_ONCE(!list_empty(&p->scx.dsq_list.node));
1401 		p->scx.holding_cpu = -1;
1402 	}
1403 	p->scx.dsq = NULL;
1404 
1405 	if (!is_local)
1406 		raw_spin_unlock(&dsq->lock);
1407 }
1408 
1409 /*
1410  * Abbreviated version of dispatch_dequeue() that can be used when both @p's rq
1411  * and dsq are locked.
1412  */
1413 static void dispatch_dequeue_locked(struct task_struct *p,
1414 				    struct scx_dispatch_q *dsq)
1415 {
1416 	lockdep_assert_rq_held(task_rq(p));
1417 	lockdep_assert_held(&dsq->lock);
1418 
1419 	task_unlink_from_dsq(p, dsq);
1420 	p->scx.dsq = NULL;
1421 }
1422 
1423 static struct scx_dispatch_q *find_dsq_for_dispatch(struct scx_sched *sch,
1424 						    struct rq *rq, u64 dsq_id,
1425 						    struct task_struct *p)
1426 {
1427 	struct scx_dispatch_q *dsq;
1428 
1429 	if (dsq_id == SCX_DSQ_LOCAL)
1430 		return &rq->scx.local_dsq;
1431 
1432 	if ((dsq_id & SCX_DSQ_LOCAL_ON) == SCX_DSQ_LOCAL_ON) {
1433 		s32 cpu = dsq_id & SCX_DSQ_LOCAL_CPU_MASK;
1434 
1435 		if (!ops_cpu_valid(sch, cpu, "in SCX_DSQ_LOCAL_ON dispatch verdict"))
1436 			return find_global_dsq(sch, p);
1437 
1438 		return &cpu_rq(cpu)->scx.local_dsq;
1439 	}
1440 
1441 	if (dsq_id == SCX_DSQ_GLOBAL)
1442 		dsq = find_global_dsq(sch, p);
1443 	else
1444 		dsq = find_user_dsq(sch, dsq_id);
1445 
1446 	if (unlikely(!dsq)) {
1447 		scx_error(sch, "non-existent DSQ 0x%llx for %s[%d]",
1448 			  dsq_id, p->comm, p->pid);
1449 		return find_global_dsq(sch, p);
1450 	}
1451 
1452 	return dsq;
1453 }
1454 
1455 static void mark_direct_dispatch(struct scx_sched *sch,
1456 				 struct task_struct *ddsp_task,
1457 				 struct task_struct *p, u64 dsq_id,
1458 				 u64 enq_flags)
1459 {
1460 	/*
1461 	 * Mark that dispatch already happened from ops.select_cpu() or
1462 	 * ops.enqueue() by spoiling direct_dispatch_task with a non-NULL value
1463 	 * which can never match a valid task pointer.
1464 	 */
1465 	__this_cpu_write(direct_dispatch_task, ERR_PTR(-ESRCH));
1466 
1467 	/* @p must match the task on the enqueue path */
1468 	if (unlikely(p != ddsp_task)) {
1469 		if (IS_ERR(ddsp_task))
1470 			scx_error(sch, "%s[%d] already direct-dispatched",
1471 				  p->comm, p->pid);
1472 		else
1473 			scx_error(sch, "scheduling for %s[%d] but trying to direct-dispatch %s[%d]",
1474 				  ddsp_task->comm, ddsp_task->pid,
1475 				  p->comm, p->pid);
1476 		return;
1477 	}
1478 
1479 	WARN_ON_ONCE(p->scx.ddsp_dsq_id != SCX_DSQ_INVALID);
1480 	WARN_ON_ONCE(p->scx.ddsp_enq_flags);
1481 
1482 	p->scx.ddsp_dsq_id = dsq_id;
1483 	p->scx.ddsp_enq_flags = enq_flags;
1484 }
1485 
1486 static void direct_dispatch(struct scx_sched *sch, struct task_struct *p,
1487 			    u64 enq_flags)
1488 {
1489 	struct rq *rq = task_rq(p);
1490 	struct scx_dispatch_q *dsq =
1491 		find_dsq_for_dispatch(sch, rq, p->scx.ddsp_dsq_id, p);
1492 
1493 	touch_core_sched_dispatch(rq, p);
1494 
1495 	p->scx.ddsp_enq_flags |= enq_flags;
1496 
1497 	/*
1498 	 * We are in the enqueue path with @rq locked and pinned, and thus can't
1499 	 * double lock a remote rq and enqueue to its local DSQ. For
1500 	 * DSQ_LOCAL_ON verdicts targeting the local DSQ of a remote CPU, defer
1501 	 * the enqueue so that it's executed when @rq can be unlocked.
1502 	 */
1503 	if (dsq->id == SCX_DSQ_LOCAL && dsq != &rq->scx.local_dsq) {
1504 		unsigned long opss;
1505 
1506 		opss = atomic_long_read(&p->scx.ops_state) & SCX_OPSS_STATE_MASK;
1507 
1508 		switch (opss & SCX_OPSS_STATE_MASK) {
1509 		case SCX_OPSS_NONE:
1510 			break;
1511 		case SCX_OPSS_QUEUEING:
1512 			/*
1513 			 * As @p was never passed to the BPF side, _release is
1514 			 * not strictly necessary. Still do it for consistency.
1515 			 */
1516 			atomic_long_set_release(&p->scx.ops_state, SCX_OPSS_NONE);
1517 			break;
1518 		default:
1519 			WARN_ONCE(true, "sched_ext: %s[%d] has invalid ops state 0x%lx in direct_dispatch()",
1520 				  p->comm, p->pid, opss);
1521 			atomic_long_set_release(&p->scx.ops_state, SCX_OPSS_NONE);
1522 			break;
1523 		}
1524 
1525 		WARN_ON_ONCE(p->scx.dsq || !list_empty(&p->scx.dsq_list.node));
1526 		list_add_tail(&p->scx.dsq_list.node,
1527 			      &rq->scx.ddsp_deferred_locals);
1528 		schedule_deferred_locked(rq);
1529 		return;
1530 	}
1531 
1532 	dispatch_enqueue(sch, rq, dsq, p,
1533 			 p->scx.ddsp_enq_flags | SCX_ENQ_CLEAR_OPSS);
1534 }
1535 
1536 static bool scx_rq_online(struct rq *rq)
1537 {
1538 	/*
1539 	 * Test both cpu_active() and %SCX_RQ_ONLINE. %SCX_RQ_ONLINE indicates
1540 	 * the online state as seen from the BPF scheduler. cpu_active() test
1541 	 * guarantees that, if this function returns %true, %SCX_RQ_ONLINE will
1542 	 * stay set until the current scheduling operation is complete even if
1543 	 * we aren't locking @rq.
1544 	 */
1545 	return likely((rq->scx.flags & SCX_RQ_ONLINE) && cpu_active(cpu_of(rq)));
1546 }
1547 
1548 static void do_enqueue_task(struct rq *rq, struct task_struct *p, u64 enq_flags,
1549 			    int sticky_cpu)
1550 {
1551 	struct scx_sched *sch = scx_task_sched(p);
1552 	struct task_struct **ddsp_taskp;
1553 	struct scx_dispatch_q *dsq;
1554 	unsigned long qseq;
1555 
1556 	WARN_ON_ONCE(!(p->scx.flags & SCX_TASK_QUEUED));
1557 
1558 	/* rq migration */
1559 	if (sticky_cpu == cpu_of(rq))
1560 		goto local_norefill;
1561 
1562 	/*
1563 	 * If !scx_rq_online(), we already told the BPF scheduler that the CPU
1564 	 * is offline and are just running the hotplug path. Don't bother the
1565 	 * BPF scheduler.
1566 	 */
1567 	if (!scx_rq_online(rq))
1568 		goto local;
1569 
1570 	if (scx_rq_bypassing(rq)) {
1571 		__scx_add_event(sch, SCX_EV_BYPASS_DISPATCH, 1);
1572 		goto bypass;
1573 	}
1574 
1575 	if (p->scx.ddsp_dsq_id != SCX_DSQ_INVALID)
1576 		goto direct;
1577 
1578 	/* see %SCX_OPS_ENQ_EXITING */
1579 	if (!(sch->ops.flags & SCX_OPS_ENQ_EXITING) &&
1580 	    unlikely(p->flags & PF_EXITING)) {
1581 		__scx_add_event(sch, SCX_EV_ENQ_SKIP_EXITING, 1);
1582 		goto local;
1583 	}
1584 
1585 	/* see %SCX_OPS_ENQ_MIGRATION_DISABLED */
1586 	if (!(sch->ops.flags & SCX_OPS_ENQ_MIGRATION_DISABLED) &&
1587 	    is_migration_disabled(p)) {
1588 		__scx_add_event(sch, SCX_EV_ENQ_SKIP_MIGRATION_DISABLED, 1);
1589 		goto local;
1590 	}
1591 
1592 	if (unlikely(!SCX_HAS_OP(sch, enqueue)))
1593 		goto global;
1594 
1595 	/* DSQ bypass didn't trigger, enqueue on the BPF scheduler */
1596 	qseq = rq->scx.ops_qseq++ << SCX_OPSS_QSEQ_SHIFT;
1597 
1598 	WARN_ON_ONCE(atomic_long_read(&p->scx.ops_state) != SCX_OPSS_NONE);
1599 	atomic_long_set(&p->scx.ops_state, SCX_OPSS_QUEUEING | qseq);
1600 
1601 	ddsp_taskp = this_cpu_ptr(&direct_dispatch_task);
1602 	WARN_ON_ONCE(*ddsp_taskp);
1603 	*ddsp_taskp = p;
1604 
1605 	SCX_CALL_OP_TASK(sch, SCX_KF_ENQUEUE, enqueue, rq, p, enq_flags);
1606 
1607 	*ddsp_taskp = NULL;
1608 	if (p->scx.ddsp_dsq_id != SCX_DSQ_INVALID)
1609 		goto direct;
1610 
1611 	/*
1612 	 * Task is now in BPF scheduler's custody. Set %SCX_TASK_IN_CUSTODY
1613 	 * so ops.dequeue() is called when it leaves custody.
1614 	 */
1615 	p->scx.flags |= SCX_TASK_IN_CUSTODY;
1616 
1617 	/*
1618 	 * If not directly dispatched, QUEUEING isn't clear yet and dispatch or
1619 	 * dequeue may be waiting. The store_release matches their load_acquire.
1620 	 */
1621 	atomic_long_set_release(&p->scx.ops_state, SCX_OPSS_QUEUED | qseq);
1622 	return;
1623 
1624 direct:
1625 	direct_dispatch(sch, p, enq_flags);
1626 	return;
1627 local_norefill:
1628 	dispatch_enqueue(sch, rq, &rq->scx.local_dsq, p, enq_flags);
1629 	return;
1630 local:
1631 	dsq = &rq->scx.local_dsq;
1632 	goto enqueue;
1633 global:
1634 	dsq = find_global_dsq(sch, p);
1635 	goto enqueue;
1636 bypass:
1637 	dsq = &task_rq(p)->scx.bypass_dsq;
1638 	goto enqueue;
1639 
1640 enqueue:
1641 	/*
1642 	 * For task-ordering, slice refill must be treated as implying the end
1643 	 * of the current slice. Otherwise, the longer @p stays on the CPU, the
1644 	 * higher priority it becomes from scx_prio_less()'s POV.
1645 	 */
1646 	touch_core_sched(rq, p);
1647 	refill_task_slice_dfl(sch, p);
1648 	dispatch_enqueue(sch, rq, dsq, p, enq_flags);
1649 }
1650 
1651 static bool task_runnable(const struct task_struct *p)
1652 {
1653 	return !list_empty(&p->scx.runnable_node);
1654 }
1655 
1656 static void set_task_runnable(struct rq *rq, struct task_struct *p)
1657 {
1658 	lockdep_assert_rq_held(rq);
1659 
1660 	if (p->scx.flags & SCX_TASK_RESET_RUNNABLE_AT) {
1661 		p->scx.runnable_at = jiffies;
1662 		p->scx.flags &= ~SCX_TASK_RESET_RUNNABLE_AT;
1663 	}
1664 
1665 	/*
1666 	 * list_add_tail() must be used. scx_bypass() depends on tasks being
1667 	 * appended to the runnable_list.
1668 	 */
1669 	list_add_tail(&p->scx.runnable_node, &rq->scx.runnable_list);
1670 }
1671 
1672 static void clr_task_runnable(struct task_struct *p, bool reset_runnable_at)
1673 {
1674 	list_del_init(&p->scx.runnable_node);
1675 	if (reset_runnable_at)
1676 		p->scx.flags |= SCX_TASK_RESET_RUNNABLE_AT;
1677 }
1678 
1679 static void enqueue_task_scx(struct rq *rq, struct task_struct *p, int enq_flags)
1680 {
1681 	struct scx_sched *sch = scx_task_sched(p);
1682 	int sticky_cpu = p->scx.sticky_cpu;
1683 
1684 	if (enq_flags & ENQUEUE_WAKEUP)
1685 		rq->scx.flags |= SCX_RQ_IN_WAKEUP;
1686 
1687 	enq_flags |= rq->scx.extra_enq_flags;
1688 
1689 	/*
1690 	 * Restoring a running task will be immediately followed by
1691 	 * set_next_task_scx() which expects the task to not be on the BPF
1692 	 * scheduler as tasks can only start running through local DSQs. Force
1693 	 * direct-dispatch into the local DSQ by setting the sticky_cpu.
1694 	 */
1695 	if (unlikely(enq_flags & ENQUEUE_RESTORE) && task_current(rq, p))
1696 		sticky_cpu = cpu_of(rq);
1697 
1698 	if (p->scx.flags & SCX_TASK_QUEUED) {
1699 		WARN_ON_ONCE(!task_runnable(p));
1700 		goto out;
1701 	}
1702 
1703 	set_task_runnable(rq, p);
1704 	p->scx.flags |= SCX_TASK_QUEUED;
1705 	rq->scx.nr_running++;
1706 	add_nr_running(rq, 1);
1707 
1708 	if (SCX_HAS_OP(sch, runnable) && !task_on_rq_migrating(p))
1709 		SCX_CALL_OP_TASK(sch, SCX_KF_REST, runnable, rq, p, enq_flags);
1710 
1711 	if (enq_flags & SCX_ENQ_WAKEUP)
1712 		touch_core_sched(rq, p);
1713 
1714 	/* Start dl_server if this is the first task being enqueued */
1715 	if (rq->scx.nr_running == 1)
1716 		dl_server_start(&rq->ext_server);
1717 
1718 	do_enqueue_task(rq, p, enq_flags, sticky_cpu);
1719 
1720 	if (sticky_cpu >= 0)
1721 		p->scx.sticky_cpu = -1;
1722 out:
1723 	rq->scx.flags &= ~SCX_RQ_IN_WAKEUP;
1724 
1725 	if ((enq_flags & SCX_ENQ_CPU_SELECTED) &&
1726 	    unlikely(cpu_of(rq) != p->scx.selected_cpu))
1727 		__scx_add_event(sch, SCX_EV_SELECT_CPU_FALLBACK, 1);
1728 }
1729 
1730 static void ops_dequeue(struct rq *rq, struct task_struct *p, u64 deq_flags)
1731 {
1732 	struct scx_sched *sch = scx_task_sched(p);
1733 	unsigned long opss;
1734 	u64 op_deq_flags = deq_flags;
1735 
1736 	/*
1737 	 * Set %SCX_DEQ_SCHED_CHANGE when the dequeue is due to a property
1738 	 * change (not sleep or core-sched pick).
1739 	 */
1740 	if (!(op_deq_flags & (DEQUEUE_SLEEP | SCX_DEQ_CORE_SCHED_EXEC)))
1741 		op_deq_flags |= SCX_DEQ_SCHED_CHANGE;
1742 
1743 	/* dequeue is always temporary, don't reset runnable_at */
1744 	clr_task_runnable(p, false);
1745 
1746 	/* acquire ensures that we see the preceding updates on QUEUED */
1747 	opss = atomic_long_read_acquire(&p->scx.ops_state);
1748 
1749 	switch (opss & SCX_OPSS_STATE_MASK) {
1750 	case SCX_OPSS_NONE:
1751 		break;
1752 	case SCX_OPSS_QUEUEING:
1753 		/*
1754 		 * QUEUEING is started and finished while holding @p's rq lock.
1755 		 * As we're holding the rq lock now, we shouldn't see QUEUEING.
1756 		 */
1757 		BUG();
1758 	case SCX_OPSS_QUEUED:
1759 		/* A queued task must always be in BPF scheduler's custody */
1760 		WARN_ON_ONCE(!(p->scx.flags & SCX_TASK_IN_CUSTODY));
1761 		if (atomic_long_try_cmpxchg(&p->scx.ops_state, &opss,
1762 					    SCX_OPSS_NONE))
1763 			break;
1764 		fallthrough;
1765 	case SCX_OPSS_DISPATCHING:
1766 		/*
1767 		 * If @p is being dispatched from the BPF scheduler to a DSQ,
1768 		 * wait for the transfer to complete so that @p doesn't get
1769 		 * added to its DSQ after dequeueing is complete.
1770 		 *
1771 		 * As we're waiting on DISPATCHING with the rq locked, the
1772 		 * dispatching side shouldn't try to lock the rq while
1773 		 * DISPATCHING is set. See dispatch_to_local_dsq().
1774 		 *
1775 		 * DISPATCHING shouldn't have qseq set and control can reach
1776 		 * here with NONE @opss from the above QUEUED case block.
1777 		 * Explicitly wait on %SCX_OPSS_DISPATCHING instead of @opss.
1778 		 */
1779 		wait_ops_state(p, SCX_OPSS_DISPATCHING);
1780 		BUG_ON(atomic_long_read(&p->scx.ops_state) != SCX_OPSS_NONE);
1781 		break;
1782 	}
1783 
1784 	/*
1785 	 * Call ops.dequeue() if the task is still in BPF custody.
1786 	 *
1787 	 * The code that clears ops_state to %SCX_OPSS_NONE does not always
1788 	 * clear %SCX_TASK_IN_CUSTODY: in dispatch_to_local_dsq(), when
1789 	 * we're moving a task that was in %SCX_OPSS_DISPATCHING to a
1790 	 * remote CPU's local DSQ, we only set ops_state to %SCX_OPSS_NONE
1791 	 * so that a concurrent dequeue can proceed, but we clear
1792 	 * %SCX_TASK_IN_CUSTODY only when we later enqueue or move the
1793 	 * task. So we can see NONE + IN_CUSTODY here and we must handle
1794 	 * it. Similarly, after waiting on %SCX_OPSS_DISPATCHING we see
1795 	 * NONE but the task may still have %SCX_TASK_IN_CUSTODY set until
1796 	 * it is enqueued on the destination.
1797 	 */
1798 	call_task_dequeue(sch, rq, p, op_deq_flags);
1799 }
1800 
1801 static bool dequeue_task_scx(struct rq *rq, struct task_struct *p, int deq_flags)
1802 {
1803 	struct scx_sched *sch = scx_task_sched(p);
1804 
1805 	if (!(p->scx.flags & SCX_TASK_QUEUED)) {
1806 		WARN_ON_ONCE(task_runnable(p));
1807 		return true;
1808 	}
1809 
1810 	ops_dequeue(rq, p, deq_flags);
1811 
1812 	/*
1813 	 * A currently running task which is going off @rq first gets dequeued
1814 	 * and then stops running. As we want running <-> stopping transitions
1815 	 * to be contained within runnable <-> quiescent transitions, trigger
1816 	 * ->stopping() early here instead of in put_prev_task_scx().
1817 	 *
1818 	 * @p may go through multiple stopping <-> running transitions between
1819 	 * here and put_prev_task_scx() if task attribute changes occur while
1820 	 * balance_one() leaves @rq unlocked. However, they don't contain any
1821 	 * information meaningful to the BPF scheduler and can be suppressed by
1822 	 * skipping the callbacks if the task is !QUEUED.
1823 	 */
1824 	if (SCX_HAS_OP(sch, stopping) && task_current(rq, p)) {
1825 		update_curr_scx(rq);
1826 		SCX_CALL_OP_TASK(sch, SCX_KF_REST, stopping, rq, p, false);
1827 	}
1828 
1829 	if (SCX_HAS_OP(sch, quiescent) && !task_on_rq_migrating(p))
1830 		SCX_CALL_OP_TASK(sch, SCX_KF_REST, quiescent, rq, p, deq_flags);
1831 
1832 	if (deq_flags & SCX_DEQ_SLEEP)
1833 		p->scx.flags |= SCX_TASK_DEQD_FOR_SLEEP;
1834 	else
1835 		p->scx.flags &= ~SCX_TASK_DEQD_FOR_SLEEP;
1836 
1837 	p->scx.flags &= ~SCX_TASK_QUEUED;
1838 	rq->scx.nr_running--;
1839 	sub_nr_running(rq, 1);
1840 
1841 	dispatch_dequeue(rq, p);
1842 	return true;
1843 }
1844 
1845 static void yield_task_scx(struct rq *rq)
1846 {
1847 	struct task_struct *p = rq->donor;
1848 	struct scx_sched *sch = scx_task_sched(p);
1849 
1850 	if (SCX_HAS_OP(sch, yield))
1851 		SCX_CALL_OP_2TASKS_RET(sch, SCX_KF_REST, yield, rq, p, NULL);
1852 	else
1853 		p->scx.slice = 0;
1854 }
1855 
1856 static bool yield_to_task_scx(struct rq *rq, struct task_struct *to)
1857 {
1858 	struct task_struct *from = rq->donor;
1859 	struct scx_sched *sch = scx_task_sched(from);
1860 
1861 	if (SCX_HAS_OP(sch, yield) && sch == scx_task_sched(to))
1862 		return SCX_CALL_OP_2TASKS_RET(sch, SCX_KF_REST, yield, rq,
1863 					      from, to);
1864 	else
1865 		return false;
1866 }
1867 
1868 static void move_local_task_to_local_dsq(struct task_struct *p, u64 enq_flags,
1869 					 struct scx_dispatch_q *src_dsq,
1870 					 struct rq *dst_rq)
1871 {
1872 	struct scx_dispatch_q *dst_dsq = &dst_rq->scx.local_dsq;
1873 
1874 	/* @dsq is locked and @p is on @dst_rq */
1875 	lockdep_assert_held(&src_dsq->lock);
1876 	lockdep_assert_rq_held(dst_rq);
1877 
1878 	WARN_ON_ONCE(p->scx.holding_cpu >= 0);
1879 
1880 	if (enq_flags & (SCX_ENQ_HEAD | SCX_ENQ_PREEMPT))
1881 		list_add(&p->scx.dsq_list.node, &dst_dsq->list);
1882 	else
1883 		list_add_tail(&p->scx.dsq_list.node, &dst_dsq->list);
1884 
1885 	dsq_mod_nr(dst_dsq, 1);
1886 	p->scx.dsq = dst_dsq;
1887 
1888 	local_dsq_post_enq(dst_dsq, p, enq_flags);
1889 }
1890 
1891 /**
1892  * move_remote_task_to_local_dsq - Move a task from a foreign rq to a local DSQ
1893  * @p: task to move
1894  * @enq_flags: %SCX_ENQ_*
1895  * @src_rq: rq to move the task from, locked on entry, released on return
1896  * @dst_rq: rq to move the task into, locked on return
1897  *
1898  * Move @p which is currently on @src_rq to @dst_rq's local DSQ.
1899  */
1900 static void move_remote_task_to_local_dsq(struct task_struct *p, u64 enq_flags,
1901 					  struct rq *src_rq, struct rq *dst_rq)
1902 {
1903 	lockdep_assert_rq_held(src_rq);
1904 
1905 	/*
1906 	 * Set sticky_cpu before deactivate_task() to properly mark the
1907 	 * beginning of an SCX-internal migration.
1908 	 */
1909 	p->scx.sticky_cpu = cpu_of(dst_rq);
1910 	deactivate_task(src_rq, p, 0);
1911 	set_task_cpu(p, cpu_of(dst_rq));
1912 
1913 	raw_spin_rq_unlock(src_rq);
1914 	raw_spin_rq_lock(dst_rq);
1915 
1916 	/*
1917 	 * We want to pass scx-specific enq_flags but activate_task() will
1918 	 * truncate the upper 32 bit. As we own @rq, we can pass them through
1919 	 * @rq->scx.extra_enq_flags instead.
1920 	 */
1921 	WARN_ON_ONCE(!cpumask_test_cpu(cpu_of(dst_rq), p->cpus_ptr));
1922 	WARN_ON_ONCE(dst_rq->scx.extra_enq_flags);
1923 	dst_rq->scx.extra_enq_flags = enq_flags;
1924 	activate_task(dst_rq, p, 0);
1925 	dst_rq->scx.extra_enq_flags = 0;
1926 }
1927 
1928 /*
1929  * Similar to kernel/sched/core.c::is_cpu_allowed(). However, there are two
1930  * differences:
1931  *
1932  * - is_cpu_allowed() asks "Can this task run on this CPU?" while
1933  *   task_can_run_on_remote_rq() asks "Can the BPF scheduler migrate the task to
1934  *   this CPU?".
1935  *
1936  *   While migration is disabled, is_cpu_allowed() has to say "yes" as the task
1937  *   must be allowed to finish on the CPU that it's currently on regardless of
1938  *   the CPU state. However, task_can_run_on_remote_rq() must say "no" as the
1939  *   BPF scheduler shouldn't attempt to migrate a task which has migration
1940  *   disabled.
1941  *
1942  * - The BPF scheduler is bypassed while the rq is offline and we can always say
1943  *   no to the BPF scheduler initiated migrations while offline.
1944  *
1945  * The caller must ensure that @p and @rq are on different CPUs.
1946  */
1947 static bool task_can_run_on_remote_rq(struct scx_sched *sch,
1948 				      struct task_struct *p, struct rq *rq,
1949 				      bool enforce)
1950 {
1951 	int cpu = cpu_of(rq);
1952 
1953 	WARN_ON_ONCE(task_cpu(p) == cpu);
1954 
1955 	/*
1956 	 * If @p has migration disabled, @p->cpus_ptr is updated to contain only
1957 	 * the pinned CPU in migrate_disable_switch() while @p is being switched
1958 	 * out. However, put_prev_task_scx() is called before @p->cpus_ptr is
1959 	 * updated and thus another CPU may see @p on a DSQ inbetween leading to
1960 	 * @p passing the below task_allowed_on_cpu() check while migration is
1961 	 * disabled.
1962 	 *
1963 	 * Test the migration disabled state first as the race window is narrow
1964 	 * and the BPF scheduler failing to check migration disabled state can
1965 	 * easily be masked if task_allowed_on_cpu() is done first.
1966 	 */
1967 	if (unlikely(is_migration_disabled(p))) {
1968 		if (enforce)
1969 			scx_error(sch, "SCX_DSQ_LOCAL[_ON] cannot move migration disabled %s[%d] from CPU %d to %d",
1970 				  p->comm, p->pid, task_cpu(p), cpu);
1971 		return false;
1972 	}
1973 
1974 	/*
1975 	 * We don't require the BPF scheduler to avoid dispatching to offline
1976 	 * CPUs mostly for convenience but also because CPUs can go offline
1977 	 * between scx_bpf_dsq_insert() calls and here. Trigger error iff the
1978 	 * picked CPU is outside the allowed mask.
1979 	 */
1980 	if (!task_allowed_on_cpu(p, cpu)) {
1981 		if (enforce)
1982 			scx_error(sch, "SCX_DSQ_LOCAL[_ON] target CPU %d not allowed for %s[%d]",
1983 				  cpu, p->comm, p->pid);
1984 		return false;
1985 	}
1986 
1987 	if (!scx_rq_online(rq)) {
1988 		if (enforce)
1989 			__scx_add_event(sch, SCX_EV_DISPATCH_LOCAL_DSQ_OFFLINE, 1);
1990 		return false;
1991 	}
1992 
1993 	return true;
1994 }
1995 
1996 /**
1997  * unlink_dsq_and_lock_src_rq() - Unlink task from its DSQ and lock its task_rq
1998  * @p: target task
1999  * @dsq: locked DSQ @p is currently on
2000  * @src_rq: rq @p is currently on, stable with @dsq locked
2001  *
2002  * Called with @dsq locked but no rq's locked. We want to move @p to a different
2003  * DSQ, including any local DSQ, but are not locking @src_rq. Locking @src_rq is
2004  * required when transferring into a local DSQ. Even when transferring into a
2005  * non-local DSQ, it's better to use the same mechanism to protect against
2006  * dequeues and maintain the invariant that @p->scx.dsq can only change while
2007  * @src_rq is locked, which e.g. scx_dump_task() depends on.
2008  *
2009  * We want to grab @src_rq but that can deadlock if we try while locking @dsq,
2010  * so we want to unlink @p from @dsq, drop its lock and then lock @src_rq. As
2011  * this may race with dequeue, which can't drop the rq lock or fail, do a little
2012  * dancing from our side.
2013  *
2014  * @p->scx.holding_cpu is set to this CPU before @dsq is unlocked. If @p gets
2015  * dequeued after we unlock @dsq but before locking @src_rq, the holding_cpu
2016  * would be cleared to -1. While other cpus may have updated it to different
2017  * values afterwards, as this operation can't be preempted or recurse, the
2018  * holding_cpu can never become this CPU again before we're done. Thus, we can
2019  * tell whether we lost to dequeue by testing whether the holding_cpu still
2020  * points to this CPU. See dispatch_dequeue() for the counterpart.
2021  *
2022  * On return, @dsq is unlocked and @src_rq is locked. Returns %true if @p is
2023  * still valid. %false if lost to dequeue.
2024  */
2025 static bool unlink_dsq_and_lock_src_rq(struct task_struct *p,
2026 				       struct scx_dispatch_q *dsq,
2027 				       struct rq *src_rq)
2028 {
2029 	s32 cpu = raw_smp_processor_id();
2030 
2031 	lockdep_assert_held(&dsq->lock);
2032 
2033 	WARN_ON_ONCE(p->scx.holding_cpu >= 0);
2034 	task_unlink_from_dsq(p, dsq);
2035 	p->scx.holding_cpu = cpu;
2036 
2037 	raw_spin_unlock(&dsq->lock);
2038 	raw_spin_rq_lock(src_rq);
2039 
2040 	/* task_rq couldn't have changed if we're still the holding cpu */
2041 	return likely(p->scx.holding_cpu == cpu) &&
2042 		!WARN_ON_ONCE(src_rq != task_rq(p));
2043 }
2044 
2045 static bool consume_remote_task(struct rq *this_rq, struct task_struct *p,
2046 				struct scx_dispatch_q *dsq, struct rq *src_rq)
2047 {
2048 	raw_spin_rq_unlock(this_rq);
2049 
2050 	if (unlink_dsq_and_lock_src_rq(p, dsq, src_rq)) {
2051 		move_remote_task_to_local_dsq(p, 0, src_rq, this_rq);
2052 		return true;
2053 	} else {
2054 		raw_spin_rq_unlock(src_rq);
2055 		raw_spin_rq_lock(this_rq);
2056 		return false;
2057 	}
2058 }
2059 
2060 /**
2061  * move_task_between_dsqs() - Move a task from one DSQ to another
2062  * @sch: scx_sched being operated on
2063  * @p: target task
2064  * @enq_flags: %SCX_ENQ_*
2065  * @src_dsq: DSQ @p is currently on, must not be a local DSQ
2066  * @dst_dsq: DSQ @p is being moved to, can be any DSQ
2067  *
2068  * Must be called with @p's task_rq and @src_dsq locked. If @dst_dsq is a local
2069  * DSQ and @p is on a different CPU, @p will be migrated and thus its task_rq
2070  * will change. As @p's task_rq is locked, this function doesn't need to use the
2071  * holding_cpu mechanism.
2072  *
2073  * On return, @src_dsq is unlocked and only @p's new task_rq, which is the
2074  * return value, is locked.
2075  */
2076 static struct rq *move_task_between_dsqs(struct scx_sched *sch,
2077 					 struct task_struct *p, u64 enq_flags,
2078 					 struct scx_dispatch_q *src_dsq,
2079 					 struct scx_dispatch_q *dst_dsq)
2080 {
2081 	struct rq *src_rq = task_rq(p), *dst_rq;
2082 
2083 	BUG_ON(src_dsq->id == SCX_DSQ_LOCAL);
2084 	lockdep_assert_held(&src_dsq->lock);
2085 	lockdep_assert_rq_held(src_rq);
2086 
2087 	if (dst_dsq->id == SCX_DSQ_LOCAL) {
2088 		dst_rq = container_of(dst_dsq, struct rq, scx.local_dsq);
2089 		if (src_rq != dst_rq &&
2090 		    unlikely(!task_can_run_on_remote_rq(sch, p, dst_rq, true))) {
2091 			dst_dsq = find_global_dsq(sch, p);
2092 			dst_rq = src_rq;
2093 		}
2094 	} else {
2095 		/* no need to migrate if destination is a non-local DSQ */
2096 		dst_rq = src_rq;
2097 	}
2098 
2099 	/*
2100 	 * Move @p into $dst_dsq. If $dst_dsq is the local DSQ of a different
2101 	 * CPU, @p will be migrated.
2102 	 */
2103 	if (dst_dsq->id == SCX_DSQ_LOCAL) {
2104 		/* @p is going from a non-local DSQ to a local DSQ */
2105 		if (src_rq == dst_rq) {
2106 			task_unlink_from_dsq(p, src_dsq);
2107 			move_local_task_to_local_dsq(p, enq_flags,
2108 						     src_dsq, dst_rq);
2109 			raw_spin_unlock(&src_dsq->lock);
2110 		} else {
2111 			raw_spin_unlock(&src_dsq->lock);
2112 			move_remote_task_to_local_dsq(p, enq_flags,
2113 						      src_rq, dst_rq);
2114 		}
2115 	} else {
2116 		/*
2117 		 * @p is going from a non-local DSQ to a non-local DSQ. As
2118 		 * $src_dsq is already locked, do an abbreviated dequeue.
2119 		 */
2120 		dispatch_dequeue_locked(p, src_dsq);
2121 		raw_spin_unlock(&src_dsq->lock);
2122 
2123 		dispatch_enqueue(sch, dst_rq, dst_dsq, p, enq_flags);
2124 	}
2125 
2126 	return dst_rq;
2127 }
2128 
2129 static bool consume_dispatch_q(struct scx_sched *sch, struct rq *rq,
2130 			       struct scx_dispatch_q *dsq)
2131 {
2132 	struct task_struct *p;
2133 retry:
2134 	/*
2135 	 * The caller can't expect to successfully consume a task if the task's
2136 	 * addition to @dsq isn't guaranteed to be visible somehow. Test
2137 	 * @dsq->list without locking and skip if it seems empty.
2138 	 */
2139 	if (list_empty(&dsq->list))
2140 		return false;
2141 
2142 	raw_spin_lock(&dsq->lock);
2143 
2144 	nldsq_for_each_task(p, dsq) {
2145 		struct rq *task_rq = task_rq(p);
2146 
2147 		/*
2148 		 * This loop can lead to multiple lockup scenarios, e.g. the BPF
2149 		 * scheduler can put an enormous number of affinitized tasks into
2150 		 * a contended DSQ, or the outer retry loop can repeatedly race
2151 		 * against scx_bypass() dequeueing tasks from @dsq trying to put
2152 		 * the system into the bypass mode. This can easily live-lock the
2153 		 * machine. If aborting, exit from all non-bypass DSQs.
2154 		 */
2155 		if (unlikely(READ_ONCE(scx_aborting)) && dsq->id != SCX_DSQ_BYPASS)
2156 			break;
2157 
2158 		if (rq == task_rq) {
2159 			task_unlink_from_dsq(p, dsq);
2160 			move_local_task_to_local_dsq(p, 0, dsq, rq);
2161 			raw_spin_unlock(&dsq->lock);
2162 			return true;
2163 		}
2164 
2165 		if (task_can_run_on_remote_rq(sch, p, rq, false)) {
2166 			if (likely(consume_remote_task(rq, p, dsq, task_rq)))
2167 				return true;
2168 			goto retry;
2169 		}
2170 	}
2171 
2172 	raw_spin_unlock(&dsq->lock);
2173 	return false;
2174 }
2175 
2176 static bool consume_global_dsq(struct scx_sched *sch, struct rq *rq)
2177 {
2178 	int node = cpu_to_node(cpu_of(rq));
2179 
2180 	return consume_dispatch_q(sch, rq, sch->global_dsqs[node]);
2181 }
2182 
2183 /**
2184  * dispatch_to_local_dsq - Dispatch a task to a local dsq
2185  * @sch: scx_sched being operated on
2186  * @rq: current rq which is locked
2187  * @dst_dsq: destination DSQ
2188  * @p: task to dispatch
2189  * @enq_flags: %SCX_ENQ_*
2190  *
2191  * We're holding @rq lock and want to dispatch @p to @dst_dsq which is a local
2192  * DSQ. This function performs all the synchronization dancing needed because
2193  * local DSQs are protected with rq locks.
2194  *
2195  * The caller must have exclusive ownership of @p (e.g. through
2196  * %SCX_OPSS_DISPATCHING).
2197  */
2198 static void dispatch_to_local_dsq(struct scx_sched *sch, struct rq *rq,
2199 				  struct scx_dispatch_q *dst_dsq,
2200 				  struct task_struct *p, u64 enq_flags)
2201 {
2202 	struct rq *src_rq = task_rq(p);
2203 	struct rq *dst_rq = container_of(dst_dsq, struct rq, scx.local_dsq);
2204 	struct rq *locked_rq = rq;
2205 
2206 	/*
2207 	 * We're synchronized against dequeue through DISPATCHING. As @p can't
2208 	 * be dequeued, its task_rq and cpus_allowed are stable too.
2209 	 *
2210 	 * If dispatching to @rq that @p is already on, no lock dancing needed.
2211 	 */
2212 	if (rq == src_rq && rq == dst_rq) {
2213 		dispatch_enqueue(sch, rq, dst_dsq, p,
2214 				 enq_flags | SCX_ENQ_CLEAR_OPSS);
2215 		return;
2216 	}
2217 
2218 	if (src_rq != dst_rq &&
2219 	    unlikely(!task_can_run_on_remote_rq(sch, p, dst_rq, true))) {
2220 		dispatch_enqueue(sch, rq, find_global_dsq(sch, p), p,
2221 				 enq_flags | SCX_ENQ_CLEAR_OPSS);
2222 		return;
2223 	}
2224 
2225 	/*
2226 	 * @p is on a possibly remote @src_rq which we need to lock to move the
2227 	 * task. If dequeue is in progress, it'd be locking @src_rq and waiting
2228 	 * on DISPATCHING, so we can't grab @src_rq lock while holding
2229 	 * DISPATCHING.
2230 	 *
2231 	 * As DISPATCHING guarantees that @p is wholly ours, we can pretend that
2232 	 * we're moving from a DSQ and use the same mechanism - mark the task
2233 	 * under transfer with holding_cpu, release DISPATCHING and then follow
2234 	 * the same protocol. See unlink_dsq_and_lock_src_rq().
2235 	 */
2236 	p->scx.holding_cpu = raw_smp_processor_id();
2237 
2238 	/* store_release ensures that dequeue sees the above */
2239 	atomic_long_set_release(&p->scx.ops_state, SCX_OPSS_NONE);
2240 
2241 	/* switch to @src_rq lock */
2242 	if (locked_rq != src_rq) {
2243 		raw_spin_rq_unlock(locked_rq);
2244 		locked_rq = src_rq;
2245 		raw_spin_rq_lock(src_rq);
2246 	}
2247 
2248 	/* task_rq couldn't have changed if we're still the holding cpu */
2249 	if (likely(p->scx.holding_cpu == raw_smp_processor_id()) &&
2250 	    !WARN_ON_ONCE(src_rq != task_rq(p))) {
2251 		/*
2252 		 * If @p is staying on the same rq, there's no need to go
2253 		 * through the full deactivate/activate cycle. Optimize by
2254 		 * abbreviating move_remote_task_to_local_dsq().
2255 		 */
2256 		if (src_rq == dst_rq) {
2257 			p->scx.holding_cpu = -1;
2258 			dispatch_enqueue(sch, dst_rq, &dst_rq->scx.local_dsq, p,
2259 					 enq_flags);
2260 		} else {
2261 			move_remote_task_to_local_dsq(p, enq_flags,
2262 						      src_rq, dst_rq);
2263 			/* task has been moved to dst_rq, which is now locked */
2264 			locked_rq = dst_rq;
2265 		}
2266 
2267 		/* if the destination CPU is idle, wake it up */
2268 		if (sched_class_above(p->sched_class, dst_rq->curr->sched_class))
2269 			resched_curr(dst_rq);
2270 	}
2271 
2272 	/* switch back to @rq lock */
2273 	if (locked_rq != rq) {
2274 		raw_spin_rq_unlock(locked_rq);
2275 		raw_spin_rq_lock(rq);
2276 	}
2277 }
2278 
2279 /**
2280  * finish_dispatch - Asynchronously finish dispatching a task
2281  * @rq: current rq which is locked
2282  * @p: task to finish dispatching
2283  * @qseq_at_dispatch: qseq when @p started getting dispatched
2284  * @dsq_id: destination DSQ ID
2285  * @enq_flags: %SCX_ENQ_*
2286  *
2287  * Dispatching to local DSQs may need to wait for queueing to complete or
2288  * require rq lock dancing. As we don't wanna do either while inside
2289  * ops.dispatch() to avoid locking order inversion, we split dispatching into
2290  * two parts. scx_bpf_dsq_insert() which is called by ops.dispatch() records the
2291  * task and its qseq. Once ops.dispatch() returns, this function is called to
2292  * finish up.
2293  *
2294  * There is no guarantee that @p is still valid for dispatching or even that it
2295  * was valid in the first place. Make sure that the task is still owned by the
2296  * BPF scheduler and claim the ownership before dispatching.
2297  */
2298 static void finish_dispatch(struct scx_sched *sch, struct rq *rq,
2299 			    struct task_struct *p,
2300 			    unsigned long qseq_at_dispatch,
2301 			    u64 dsq_id, u64 enq_flags)
2302 {
2303 	struct scx_dispatch_q *dsq;
2304 	unsigned long opss;
2305 
2306 	touch_core_sched_dispatch(rq, p);
2307 retry:
2308 	/*
2309 	 * No need for _acquire here. @p is accessed only after a successful
2310 	 * try_cmpxchg to DISPATCHING.
2311 	 */
2312 	opss = atomic_long_read(&p->scx.ops_state);
2313 
2314 	switch (opss & SCX_OPSS_STATE_MASK) {
2315 	case SCX_OPSS_DISPATCHING:
2316 	case SCX_OPSS_NONE:
2317 		/* someone else already got to it */
2318 		return;
2319 	case SCX_OPSS_QUEUED:
2320 		/*
2321 		 * If qseq doesn't match, @p has gone through at least one
2322 		 * dispatch/dequeue and re-enqueue cycle between
2323 		 * scx_bpf_dsq_insert() and here and we have no claim on it.
2324 		 */
2325 		if ((opss & SCX_OPSS_QSEQ_MASK) != qseq_at_dispatch)
2326 			return;
2327 
2328 		/*
2329 		 * While we know @p is accessible, we don't yet have a claim on
2330 		 * it - the BPF scheduler is allowed to dispatch tasks
2331 		 * spuriously and there can be a racing dequeue attempt. Let's
2332 		 * claim @p by atomically transitioning it from QUEUED to
2333 		 * DISPATCHING.
2334 		 */
2335 		if (likely(atomic_long_try_cmpxchg(&p->scx.ops_state, &opss,
2336 						   SCX_OPSS_DISPATCHING)))
2337 			break;
2338 		goto retry;
2339 	case SCX_OPSS_QUEUEING:
2340 		/*
2341 		 * do_enqueue_task() is in the process of transferring the task
2342 		 * to the BPF scheduler while holding @p's rq lock. As we aren't
2343 		 * holding any kernel or BPF resource that the enqueue path may
2344 		 * depend upon, it's safe to wait.
2345 		 */
2346 		wait_ops_state(p, opss);
2347 		goto retry;
2348 	}
2349 
2350 	BUG_ON(!(p->scx.flags & SCX_TASK_QUEUED));
2351 
2352 	dsq = find_dsq_for_dispatch(sch, this_rq(), dsq_id, p);
2353 
2354 	if (dsq->id == SCX_DSQ_LOCAL)
2355 		dispatch_to_local_dsq(sch, rq, dsq, p, enq_flags);
2356 	else
2357 		dispatch_enqueue(sch, rq, dsq, p, enq_flags | SCX_ENQ_CLEAR_OPSS);
2358 }
2359 
2360 static void flush_dispatch_buf(struct scx_sched *sch, struct rq *rq)
2361 {
2362 	struct scx_dsp_ctx *dspc = this_cpu_ptr(scx_dsp_ctx);
2363 	u32 u;
2364 
2365 	for (u = 0; u < dspc->cursor; u++) {
2366 		struct scx_dsp_buf_ent *ent = &dspc->buf[u];
2367 
2368 		finish_dispatch(sch, rq, ent->task, ent->qseq, ent->dsq_id,
2369 				ent->enq_flags);
2370 	}
2371 
2372 	dspc->nr_tasks += dspc->cursor;
2373 	dspc->cursor = 0;
2374 }
2375 
2376 static inline void maybe_queue_balance_callback(struct rq *rq)
2377 {
2378 	lockdep_assert_rq_held(rq);
2379 
2380 	if (!(rq->scx.flags & SCX_RQ_BAL_CB_PENDING))
2381 		return;
2382 
2383 	queue_balance_callback(rq, &rq->scx.deferred_bal_cb,
2384 				deferred_bal_cb_workfn);
2385 
2386 	rq->scx.flags &= ~SCX_RQ_BAL_CB_PENDING;
2387 }
2388 
2389 static int balance_one(struct rq *rq, struct task_struct *prev)
2390 {
2391 	struct scx_sched *sch = scx_root;
2392 	struct scx_dsp_ctx *dspc = this_cpu_ptr(scx_dsp_ctx);
2393 	bool prev_on_scx = prev->sched_class == &ext_sched_class;
2394 	bool prev_on_rq = prev->scx.flags & SCX_TASK_QUEUED;
2395 	int nr_loops = SCX_DSP_MAX_LOOPS;
2396 
2397 	lockdep_assert_rq_held(rq);
2398 	rq->scx.flags |= SCX_RQ_IN_BALANCE;
2399 	rq->scx.flags &= ~SCX_RQ_BAL_KEEP;
2400 
2401 	if ((sch->ops.flags & SCX_OPS_HAS_CPU_PREEMPT) &&
2402 	    unlikely(rq->scx.cpu_released)) {
2403 		/*
2404 		 * If the previous sched_class for the current CPU was not SCX,
2405 		 * notify the BPF scheduler that it again has control of the
2406 		 * core. This callback complements ->cpu_release(), which is
2407 		 * emitted in switch_class().
2408 		 */
2409 		if (SCX_HAS_OP(sch, cpu_acquire))
2410 			SCX_CALL_OP(sch, SCX_KF_REST, cpu_acquire, rq,
2411 				    cpu_of(rq), NULL);
2412 		rq->scx.cpu_released = false;
2413 	}
2414 
2415 	if (prev_on_scx) {
2416 		update_curr_scx(rq);
2417 
2418 		/*
2419 		 * If @prev is runnable & has slice left, it has priority and
2420 		 * fetching more just increases latency for the fetched tasks.
2421 		 * Tell pick_task_scx() to keep running @prev. If the BPF
2422 		 * scheduler wants to handle this explicitly, it should
2423 		 * implement ->cpu_release().
2424 		 *
2425 		 * See scx_disable_workfn() for the explanation on the bypassing
2426 		 * test.
2427 		 */
2428 		if (prev_on_rq && prev->scx.slice && !scx_rq_bypassing(rq)) {
2429 			rq->scx.flags |= SCX_RQ_BAL_KEEP;
2430 			goto has_tasks;
2431 		}
2432 	}
2433 
2434 	/* if there already are tasks to run, nothing to do */
2435 	if (rq->scx.local_dsq.nr)
2436 		goto has_tasks;
2437 
2438 	if (consume_global_dsq(sch, rq))
2439 		goto has_tasks;
2440 
2441 	if (scx_rq_bypassing(rq)) {
2442 		if (consume_dispatch_q(sch, rq, &rq->scx.bypass_dsq))
2443 			goto has_tasks;
2444 		else
2445 			goto no_tasks;
2446 	}
2447 
2448 	if (unlikely(!SCX_HAS_OP(sch, dispatch)) || !scx_rq_online(rq))
2449 		goto no_tasks;
2450 
2451 	dspc->rq = rq;
2452 
2453 	/*
2454 	 * The dispatch loop. Because flush_dispatch_buf() may drop the rq lock,
2455 	 * the local DSQ might still end up empty after a successful
2456 	 * ops.dispatch(). If the local DSQ is empty even after ops.dispatch()
2457 	 * produced some tasks, retry. The BPF scheduler may depend on this
2458 	 * looping behavior to simplify its implementation.
2459 	 */
2460 	do {
2461 		dspc->nr_tasks = 0;
2462 
2463 		SCX_CALL_OP(sch, SCX_KF_DISPATCH, dispatch, rq,
2464 			    cpu_of(rq), prev_on_scx ? prev : NULL);
2465 
2466 		flush_dispatch_buf(sch, rq);
2467 
2468 		if (prev_on_rq && prev->scx.slice) {
2469 			rq->scx.flags |= SCX_RQ_BAL_KEEP;
2470 			goto has_tasks;
2471 		}
2472 		if (rq->scx.local_dsq.nr)
2473 			goto has_tasks;
2474 		if (consume_global_dsq(sch, rq))
2475 			goto has_tasks;
2476 
2477 		/*
2478 		 * ops.dispatch() can trap us in this loop by repeatedly
2479 		 * dispatching ineligible tasks. Break out once in a while to
2480 		 * allow the watchdog to run. As IRQ can't be enabled in
2481 		 * balance(), we want to complete this scheduling cycle and then
2482 		 * start a new one. IOW, we want to call resched_curr() on the
2483 		 * next, most likely idle, task, not the current one. Use
2484 		 * scx_kick_cpu() for deferred kicking.
2485 		 */
2486 		if (unlikely(!--nr_loops)) {
2487 			scx_kick_cpu(sch, cpu_of(rq), 0);
2488 			break;
2489 		}
2490 	} while (dspc->nr_tasks);
2491 
2492 no_tasks:
2493 	/*
2494 	 * Didn't find another task to run. Keep running @prev unless
2495 	 * %SCX_OPS_ENQ_LAST is in effect.
2496 	 */
2497 	if (prev_on_rq &&
2498 	    (!(sch->ops.flags & SCX_OPS_ENQ_LAST) || scx_rq_bypassing(rq))) {
2499 		rq->scx.flags |= SCX_RQ_BAL_KEEP;
2500 		__scx_add_event(sch, SCX_EV_DISPATCH_KEEP_LAST, 1);
2501 		goto has_tasks;
2502 	}
2503 	rq->scx.flags &= ~SCX_RQ_IN_BALANCE;
2504 	return false;
2505 
2506 has_tasks:
2507 	rq->scx.flags &= ~SCX_RQ_IN_BALANCE;
2508 	return true;
2509 }
2510 
2511 static void process_ddsp_deferred_locals(struct rq *rq)
2512 {
2513 	struct task_struct *p;
2514 
2515 	lockdep_assert_rq_held(rq);
2516 
2517 	/*
2518 	 * Now that @rq can be unlocked, execute the deferred enqueueing of
2519 	 * tasks directly dispatched to the local DSQs of other CPUs. See
2520 	 * direct_dispatch(). Keep popping from the head instead of using
2521 	 * list_for_each_entry_safe() as dispatch_local_dsq() may unlock @rq
2522 	 * temporarily.
2523 	 */
2524 	while ((p = list_first_entry_or_null(&rq->scx.ddsp_deferred_locals,
2525 				struct task_struct, scx.dsq_list.node))) {
2526 		struct scx_sched *sch = scx_task_sched(p);
2527 		struct scx_dispatch_q *dsq;
2528 
2529 		list_del_init(&p->scx.dsq_list.node);
2530 
2531 		dsq = find_dsq_for_dispatch(sch, rq, p->scx.ddsp_dsq_id, p);
2532 		if (!WARN_ON_ONCE(dsq->id != SCX_DSQ_LOCAL))
2533 			dispatch_to_local_dsq(sch, rq, dsq, p,
2534 					      p->scx.ddsp_enq_flags);
2535 	}
2536 }
2537 
2538 static void set_next_task_scx(struct rq *rq, struct task_struct *p, bool first)
2539 {
2540 	struct scx_sched *sch = scx_task_sched(p);
2541 
2542 	if (p->scx.flags & SCX_TASK_QUEUED) {
2543 		/*
2544 		 * Core-sched might decide to execute @p before it is
2545 		 * dispatched. Call ops_dequeue() to notify the BPF scheduler.
2546 		 */
2547 		ops_dequeue(rq, p, SCX_DEQ_CORE_SCHED_EXEC);
2548 		dispatch_dequeue(rq, p);
2549 	}
2550 
2551 	p->se.exec_start = rq_clock_task(rq);
2552 
2553 	/* see dequeue_task_scx() on why we skip when !QUEUED */
2554 	if (SCX_HAS_OP(sch, running) && (p->scx.flags & SCX_TASK_QUEUED))
2555 		SCX_CALL_OP_TASK(sch, SCX_KF_REST, running, rq, p);
2556 
2557 	clr_task_runnable(p, true);
2558 
2559 	/*
2560 	 * @p is getting newly scheduled or got kicked after someone updated its
2561 	 * slice. Refresh whether tick can be stopped. See scx_can_stop_tick().
2562 	 */
2563 	if ((p->scx.slice == SCX_SLICE_INF) !=
2564 	    (bool)(rq->scx.flags & SCX_RQ_CAN_STOP_TICK)) {
2565 		if (p->scx.slice == SCX_SLICE_INF)
2566 			rq->scx.flags |= SCX_RQ_CAN_STOP_TICK;
2567 		else
2568 			rq->scx.flags &= ~SCX_RQ_CAN_STOP_TICK;
2569 
2570 		sched_update_tick_dependency(rq);
2571 
2572 		/*
2573 		 * For now, let's refresh the load_avgs just when transitioning
2574 		 * in and out of nohz. In the future, we might want to add a
2575 		 * mechanism which calls the following periodically on
2576 		 * tick-stopped CPUs.
2577 		 */
2578 		update_other_load_avgs(rq);
2579 	}
2580 }
2581 
2582 static enum scx_cpu_preempt_reason
2583 preempt_reason_from_class(const struct sched_class *class)
2584 {
2585 	if (class == &stop_sched_class)
2586 		return SCX_CPU_PREEMPT_STOP;
2587 	if (class == &dl_sched_class)
2588 		return SCX_CPU_PREEMPT_DL;
2589 	if (class == &rt_sched_class)
2590 		return SCX_CPU_PREEMPT_RT;
2591 	return SCX_CPU_PREEMPT_UNKNOWN;
2592 }
2593 
2594 static void switch_class(struct rq *rq, struct task_struct *next)
2595 {
2596 	struct scx_sched *sch = scx_root;
2597 	const struct sched_class *next_class = next->sched_class;
2598 
2599 	if (!(sch->ops.flags & SCX_OPS_HAS_CPU_PREEMPT))
2600 		return;
2601 
2602 	/*
2603 	 * The callback is conceptually meant to convey that the CPU is no
2604 	 * longer under the control of SCX. Therefore, don't invoke the callback
2605 	 * if the next class is below SCX (in which case the BPF scheduler has
2606 	 * actively decided not to schedule any tasks on the CPU).
2607 	 */
2608 	if (sched_class_above(&ext_sched_class, next_class))
2609 		return;
2610 
2611 	/*
2612 	 * At this point we know that SCX was preempted by a higher priority
2613 	 * sched_class, so invoke the ->cpu_release() callback if we have not
2614 	 * done so already. We only send the callback once between SCX being
2615 	 * preempted, and it regaining control of the CPU.
2616 	 *
2617 	 * ->cpu_release() complements ->cpu_acquire(), which is emitted the
2618 	 *  next time that balance_one() is invoked.
2619 	 */
2620 	if (!rq->scx.cpu_released) {
2621 		if (SCX_HAS_OP(sch, cpu_release)) {
2622 			struct scx_cpu_release_args args = {
2623 				.reason = preempt_reason_from_class(next_class),
2624 				.task = next,
2625 			};
2626 
2627 			SCX_CALL_OP(sch, SCX_KF_CPU_RELEASE, cpu_release, rq,
2628 				    cpu_of(rq), &args);
2629 		}
2630 		rq->scx.cpu_released = true;
2631 	}
2632 }
2633 
2634 static void put_prev_task_scx(struct rq *rq, struct task_struct *p,
2635 			      struct task_struct *next)
2636 {
2637 	struct scx_sched *sch = scx_task_sched(p);
2638 
2639 	/* see kick_cpus_irq_workfn() */
2640 	smp_store_release(&rq->scx.kick_sync, rq->scx.kick_sync + 1);
2641 
2642 	update_curr_scx(rq);
2643 
2644 	/* see dequeue_task_scx() on why we skip when !QUEUED */
2645 	if (SCX_HAS_OP(sch, stopping) && (p->scx.flags & SCX_TASK_QUEUED))
2646 		SCX_CALL_OP_TASK(sch, SCX_KF_REST, stopping, rq, p, true);
2647 
2648 	if (p->scx.flags & SCX_TASK_QUEUED) {
2649 		set_task_runnable(rq, p);
2650 
2651 		/*
2652 		 * If @p has slice left and is being put, @p is getting
2653 		 * preempted by a higher priority scheduler class or core-sched
2654 		 * forcing a different task. Leave it at the head of the local
2655 		 * DSQ.
2656 		 */
2657 		if (p->scx.slice && !scx_rq_bypassing(rq)) {
2658 			dispatch_enqueue(sch, rq, &rq->scx.local_dsq, p,
2659 					 SCX_ENQ_HEAD);
2660 			goto switch_class;
2661 		}
2662 
2663 		/*
2664 		 * If @p is runnable but we're about to enter a lower
2665 		 * sched_class, %SCX_OPS_ENQ_LAST must be set. Tell
2666 		 * ops.enqueue() that @p is the only one available for this cpu,
2667 		 * which should trigger an explicit follow-up scheduling event.
2668 		 */
2669 		if (next && sched_class_above(&ext_sched_class, next->sched_class)) {
2670 			WARN_ON_ONCE(!(sch->ops.flags & SCX_OPS_ENQ_LAST));
2671 			do_enqueue_task(rq, p, SCX_ENQ_LAST, -1);
2672 		} else {
2673 			do_enqueue_task(rq, p, 0, -1);
2674 		}
2675 	}
2676 
2677 switch_class:
2678 	if (next && next->sched_class != &ext_sched_class)
2679 		switch_class(rq, next);
2680 }
2681 
2682 static struct task_struct *first_local_task(struct rq *rq)
2683 {
2684 	return list_first_entry_or_null(&rq->scx.local_dsq.list,
2685 					struct task_struct, scx.dsq_list.node);
2686 }
2687 
2688 static struct task_struct *
2689 do_pick_task_scx(struct rq *rq, struct rq_flags *rf, bool force_scx)
2690 {
2691 	struct task_struct *prev = rq->curr;
2692 	bool keep_prev;
2693 	struct task_struct *p;
2694 
2695 	/* see kick_cpus_irq_workfn() */
2696 	smp_store_release(&rq->scx.kick_sync, rq->scx.kick_sync + 1);
2697 
2698 	rq_modified_begin(rq, &ext_sched_class);
2699 
2700 	rq_unpin_lock(rq, rf);
2701 	balance_one(rq, prev);
2702 	rq_repin_lock(rq, rf);
2703 	maybe_queue_balance_callback(rq);
2704 
2705 	/*
2706 	 * If any higher-priority sched class enqueued a runnable task on
2707 	 * this rq during balance_one(), abort and return RETRY_TASK, so
2708 	 * that the scheduler loop can restart.
2709 	 *
2710 	 * If @force_scx is true, always try to pick a SCHED_EXT task,
2711 	 * regardless of any higher-priority sched classes activity.
2712 	 */
2713 	if (!force_scx && rq_modified_above(rq, &ext_sched_class))
2714 		return RETRY_TASK;
2715 
2716 	keep_prev = rq->scx.flags & SCX_RQ_BAL_KEEP;
2717 	if (unlikely(keep_prev &&
2718 		     prev->sched_class != &ext_sched_class)) {
2719 		WARN_ON_ONCE(scx_enable_state() == SCX_ENABLED);
2720 		keep_prev = false;
2721 	}
2722 
2723 	/*
2724 	 * If balance_one() is telling us to keep running @prev, replenish slice
2725 	 * if necessary and keep running @prev. Otherwise, pop the first one
2726 	 * from the local DSQ.
2727 	 */
2728 	if (keep_prev) {
2729 		p = prev;
2730 		if (!p->scx.slice)
2731 			refill_task_slice_dfl(scx_task_sched(p), p);
2732 	} else {
2733 		p = first_local_task(rq);
2734 		if (!p)
2735 			return NULL;
2736 
2737 		if (unlikely(!p->scx.slice)) {
2738 			struct scx_sched *sch = scx_task_sched(p);
2739 
2740 			if (!scx_rq_bypassing(rq) && !sch->warned_zero_slice) {
2741 				printk_deferred(KERN_WARNING "sched_ext: %s[%d] has zero slice in %s()\n",
2742 						p->comm, p->pid, __func__);
2743 				sch->warned_zero_slice = true;
2744 			}
2745 			refill_task_slice_dfl(sch, p);
2746 		}
2747 	}
2748 
2749 	return p;
2750 }
2751 
2752 static struct task_struct *pick_task_scx(struct rq *rq, struct rq_flags *rf)
2753 {
2754 	return do_pick_task_scx(rq, rf, false);
2755 }
2756 
2757 /*
2758  * Select the next task to run from the ext scheduling class.
2759  *
2760  * Use do_pick_task_scx() directly with @force_scx enabled, since the
2761  * dl_server must always select a sched_ext task.
2762  */
2763 static struct task_struct *
2764 ext_server_pick_task(struct sched_dl_entity *dl_se, struct rq_flags *rf)
2765 {
2766 	if (!scx_enabled())
2767 		return NULL;
2768 
2769 	return do_pick_task_scx(dl_se->rq, rf, true);
2770 }
2771 
2772 /*
2773  * Initialize the ext server deadline entity.
2774  */
2775 void ext_server_init(struct rq *rq)
2776 {
2777 	struct sched_dl_entity *dl_se = &rq->ext_server;
2778 
2779 	init_dl_entity(dl_se);
2780 
2781 	dl_server_init(dl_se, rq, ext_server_pick_task);
2782 }
2783 
2784 #ifdef CONFIG_SCHED_CORE
2785 /**
2786  * scx_prio_less - Task ordering for core-sched
2787  * @a: task A
2788  * @b: task B
2789  * @in_fi: in forced idle state
2790  *
2791  * Core-sched is implemented as an additional scheduling layer on top of the
2792  * usual sched_class'es and needs to find out the expected task ordering. For
2793  * SCX, core-sched calls this function to interrogate the task ordering.
2794  *
2795  * Unless overridden by ops.core_sched_before(), @p->scx.core_sched_at is used
2796  * to implement the default task ordering. The older the timestamp, the higher
2797  * priority the task - the global FIFO ordering matching the default scheduling
2798  * behavior.
2799  *
2800  * When ops.core_sched_before() is enabled, @p->scx.core_sched_at is used to
2801  * implement FIFO ordering within each local DSQ. See pick_task_scx().
2802  */
2803 bool scx_prio_less(const struct task_struct *a, const struct task_struct *b,
2804 		   bool in_fi)
2805 {
2806 	struct scx_sched *sch = scx_root;
2807 
2808 	/*
2809 	 * The const qualifiers are dropped from task_struct pointers when
2810 	 * calling ops.core_sched_before(). Accesses are controlled by the
2811 	 * verifier.
2812 	 */
2813 	if (SCX_HAS_OP(sch, core_sched_before) &&
2814 	    !scx_rq_bypassing(task_rq(a)))
2815 		return SCX_CALL_OP_2TASKS_RET(sch, SCX_KF_REST, core_sched_before,
2816 					      NULL,
2817 					      (struct task_struct *)a,
2818 					      (struct task_struct *)b);
2819 	else
2820 		return time_after64(a->scx.core_sched_at, b->scx.core_sched_at);
2821 }
2822 #endif	/* CONFIG_SCHED_CORE */
2823 
2824 static int select_task_rq_scx(struct task_struct *p, int prev_cpu, int wake_flags)
2825 {
2826 	struct scx_sched *sch = scx_task_sched(p);
2827 	bool rq_bypass;
2828 
2829 	/*
2830 	 * sched_exec() calls with %WF_EXEC when @p is about to exec(2) as it
2831 	 * can be a good migration opportunity with low cache and memory
2832 	 * footprint. Returning a CPU different than @prev_cpu triggers
2833 	 * immediate rq migration. However, for SCX, as the current rq
2834 	 * association doesn't dictate where the task is going to run, this
2835 	 * doesn't fit well. If necessary, we can later add a dedicated method
2836 	 * which can decide to preempt self to force it through the regular
2837 	 * scheduling path.
2838 	 */
2839 	if (unlikely(wake_flags & WF_EXEC))
2840 		return prev_cpu;
2841 
2842 	rq_bypass = scx_rq_bypassing(task_rq(p));
2843 	if (likely(SCX_HAS_OP(sch, select_cpu)) && !rq_bypass) {
2844 		s32 cpu;
2845 		struct task_struct **ddsp_taskp;
2846 
2847 		ddsp_taskp = this_cpu_ptr(&direct_dispatch_task);
2848 		WARN_ON_ONCE(*ddsp_taskp);
2849 		*ddsp_taskp = p;
2850 
2851 		cpu = SCX_CALL_OP_TASK_RET(sch,
2852 					   SCX_KF_ENQUEUE | SCX_KF_SELECT_CPU,
2853 					   select_cpu, NULL, p, prev_cpu,
2854 					   wake_flags);
2855 		p->scx.selected_cpu = cpu;
2856 		*ddsp_taskp = NULL;
2857 		if (ops_cpu_valid(sch, cpu, "from ops.select_cpu()"))
2858 			return cpu;
2859 		else
2860 			return prev_cpu;
2861 	} else {
2862 		s32 cpu;
2863 
2864 		cpu = scx_select_cpu_dfl(p, prev_cpu, wake_flags, NULL, 0);
2865 		if (cpu >= 0) {
2866 			refill_task_slice_dfl(sch, p);
2867 			p->scx.ddsp_dsq_id = SCX_DSQ_LOCAL;
2868 		} else {
2869 			cpu = prev_cpu;
2870 		}
2871 		p->scx.selected_cpu = cpu;
2872 
2873 		if (rq_bypass)
2874 			__scx_add_event(sch, SCX_EV_BYPASS_DISPATCH, 1);
2875 		return cpu;
2876 	}
2877 }
2878 
2879 static void task_woken_scx(struct rq *rq, struct task_struct *p)
2880 {
2881 	run_deferred(rq);
2882 }
2883 
2884 static void set_cpus_allowed_scx(struct task_struct *p,
2885 				 struct affinity_context *ac)
2886 {
2887 	struct scx_sched *sch = scx_task_sched(p);
2888 
2889 	set_cpus_allowed_common(p, ac);
2890 
2891 	if (task_dead_and_done(p))
2892 		return;
2893 
2894 	/*
2895 	 * The effective cpumask is stored in @p->cpus_ptr which may temporarily
2896 	 * differ from the configured one in @p->cpus_mask. Always tell the bpf
2897 	 * scheduler the effective one.
2898 	 *
2899 	 * Fine-grained memory write control is enforced by BPF making the const
2900 	 * designation pointless. Cast it away when calling the operation.
2901 	 */
2902 	if (SCX_HAS_OP(sch, set_cpumask))
2903 		SCX_CALL_OP_TASK(sch, SCX_KF_REST, set_cpumask, NULL,
2904 				 p, (struct cpumask *)p->cpus_ptr);
2905 }
2906 
2907 static void handle_hotplug(struct rq *rq, bool online)
2908 {
2909 	struct scx_sched *sch = scx_root;
2910 	int cpu = cpu_of(rq);
2911 
2912 	atomic_long_inc(&scx_hotplug_seq);
2913 
2914 	/*
2915 	 * scx_root updates are protected by cpus_read_lock() and will stay
2916 	 * stable here. Note that we can't depend on scx_enabled() test as the
2917 	 * hotplug ops need to be enabled before __scx_enabled is set.
2918 	 */
2919 	if (unlikely(!sch))
2920 		return;
2921 
2922 	if (scx_enabled())
2923 		scx_idle_update_selcpu_topology(&sch->ops);
2924 
2925 	if (online && SCX_HAS_OP(sch, cpu_online))
2926 		SCX_CALL_OP(sch, SCX_KF_UNLOCKED, cpu_online, NULL, cpu);
2927 	else if (!online && SCX_HAS_OP(sch, cpu_offline))
2928 		SCX_CALL_OP(sch, SCX_KF_UNLOCKED, cpu_offline, NULL, cpu);
2929 	else
2930 		scx_exit(sch, SCX_EXIT_UNREG_KERN,
2931 			 SCX_ECODE_ACT_RESTART | SCX_ECODE_RSN_HOTPLUG,
2932 			 "cpu %d going %s, exiting scheduler", cpu,
2933 			 online ? "online" : "offline");
2934 }
2935 
2936 void scx_rq_activate(struct rq *rq)
2937 {
2938 	handle_hotplug(rq, true);
2939 }
2940 
2941 void scx_rq_deactivate(struct rq *rq)
2942 {
2943 	handle_hotplug(rq, false);
2944 }
2945 
2946 static void rq_online_scx(struct rq *rq)
2947 {
2948 	rq->scx.flags |= SCX_RQ_ONLINE;
2949 }
2950 
2951 static void rq_offline_scx(struct rq *rq)
2952 {
2953 	rq->scx.flags &= ~SCX_RQ_ONLINE;
2954 }
2955 
2956 
2957 static bool check_rq_for_timeouts(struct rq *rq)
2958 {
2959 	struct scx_sched *sch;
2960 	struct task_struct *p;
2961 	struct rq_flags rf;
2962 	bool timed_out = false;
2963 
2964 	rq_lock_irqsave(rq, &rf);
2965 	sch = rcu_dereference_bh(scx_root);
2966 	if (unlikely(!sch))
2967 		goto out_unlock;
2968 
2969 	list_for_each_entry(p, &rq->scx.runnable_list, scx.runnable_node) {
2970 		unsigned long last_runnable = p->scx.runnable_at;
2971 
2972 		if (unlikely(time_after(jiffies,
2973 					last_runnable + READ_ONCE(scx_watchdog_timeout)))) {
2974 			u32 dur_ms = jiffies_to_msecs(jiffies - last_runnable);
2975 
2976 			scx_exit(sch, SCX_EXIT_ERROR_STALL, 0,
2977 				 "%s[%d] failed to run for %u.%03us",
2978 				 p->comm, p->pid, dur_ms / 1000, dur_ms % 1000);
2979 			timed_out = true;
2980 			break;
2981 		}
2982 	}
2983 out_unlock:
2984 	rq_unlock_irqrestore(rq, &rf);
2985 	return timed_out;
2986 }
2987 
2988 static void scx_watchdog_workfn(struct work_struct *work)
2989 {
2990 	int cpu;
2991 
2992 	WRITE_ONCE(scx_watchdog_timestamp, jiffies);
2993 
2994 	for_each_online_cpu(cpu) {
2995 		if (unlikely(check_rq_for_timeouts(cpu_rq(cpu))))
2996 			break;
2997 
2998 		cond_resched();
2999 	}
3000 	queue_delayed_work(system_unbound_wq, to_delayed_work(work),
3001 			   READ_ONCE(scx_watchdog_timeout) / 2);
3002 }
3003 
3004 void scx_tick(struct rq *rq)
3005 {
3006 	struct scx_sched *sch;
3007 	unsigned long last_check;
3008 
3009 	if (!scx_enabled())
3010 		return;
3011 
3012 	sch = rcu_dereference_bh(scx_root);
3013 	if (unlikely(!sch))
3014 		return;
3015 
3016 	last_check = READ_ONCE(scx_watchdog_timestamp);
3017 	if (unlikely(time_after(jiffies,
3018 				last_check + READ_ONCE(scx_watchdog_timeout)))) {
3019 		u32 dur_ms = jiffies_to_msecs(jiffies - last_check);
3020 
3021 		scx_exit(sch, SCX_EXIT_ERROR_STALL, 0,
3022 			 "watchdog failed to check in for %u.%03us",
3023 			 dur_ms / 1000, dur_ms % 1000);
3024 	}
3025 
3026 	update_other_load_avgs(rq);
3027 }
3028 
3029 static void task_tick_scx(struct rq *rq, struct task_struct *curr, int queued)
3030 {
3031 	struct scx_sched *sch = scx_task_sched(curr);
3032 
3033 	update_curr_scx(rq);
3034 
3035 	/*
3036 	 * While disabling, always resched and refresh core-sched timestamp as
3037 	 * we can't trust the slice management or ops.core_sched_before().
3038 	 */
3039 	if (scx_rq_bypassing(rq)) {
3040 		curr->scx.slice = 0;
3041 		touch_core_sched(rq, curr);
3042 	} else if (SCX_HAS_OP(sch, tick)) {
3043 		SCX_CALL_OP_TASK(sch, SCX_KF_REST, tick, rq, curr);
3044 	}
3045 
3046 	if (!curr->scx.slice)
3047 		resched_curr(rq);
3048 }
3049 
3050 #ifdef CONFIG_EXT_GROUP_SCHED
3051 static struct cgroup *tg_cgrp(struct task_group *tg)
3052 {
3053 	/*
3054 	 * If CGROUP_SCHED is disabled, @tg is NULL. If @tg is an autogroup,
3055 	 * @tg->css.cgroup is NULL. In both cases, @tg can be treated as the
3056 	 * root cgroup.
3057 	 */
3058 	if (tg && tg->css.cgroup)
3059 		return tg->css.cgroup;
3060 	else
3061 		return &cgrp_dfl_root.cgrp;
3062 }
3063 
3064 #define SCX_INIT_TASK_ARGS_CGROUP(tg)		.cgroup = tg_cgrp(tg),
3065 
3066 #else	/* CONFIG_EXT_GROUP_SCHED */
3067 
3068 #define SCX_INIT_TASK_ARGS_CGROUP(tg)
3069 
3070 #endif	/* CONFIG_EXT_GROUP_SCHED */
3071 
3072 static enum scx_task_state scx_get_task_state(const struct task_struct *p)
3073 {
3074 	return (p->scx.flags & SCX_TASK_STATE_MASK) >> SCX_TASK_STATE_SHIFT;
3075 }
3076 
3077 static void scx_set_task_state(struct task_struct *p, enum scx_task_state state)
3078 {
3079 	enum scx_task_state prev_state = scx_get_task_state(p);
3080 	bool warn = false;
3081 
3082 	BUILD_BUG_ON(SCX_TASK_NR_STATES > (1 << SCX_TASK_STATE_BITS));
3083 
3084 	switch (state) {
3085 	case SCX_TASK_NONE:
3086 		break;
3087 	case SCX_TASK_INIT:
3088 		warn = prev_state != SCX_TASK_NONE;
3089 		break;
3090 	case SCX_TASK_READY:
3091 		warn = prev_state == SCX_TASK_NONE;
3092 		break;
3093 	case SCX_TASK_ENABLED:
3094 		warn = prev_state != SCX_TASK_READY;
3095 		break;
3096 	default:
3097 		warn = true;
3098 		return;
3099 	}
3100 
3101 	WARN_ONCE(warn, "sched_ext: Invalid task state transition %d -> %d for %s[%d]",
3102 		  prev_state, state, p->comm, p->pid);
3103 
3104 	p->scx.flags &= ~SCX_TASK_STATE_MASK;
3105 	p->scx.flags |= state << SCX_TASK_STATE_SHIFT;
3106 }
3107 
3108 static int scx_init_task(struct task_struct *p, struct task_group *tg, bool fork)
3109 {
3110 	struct scx_sched *sch = scx_root;
3111 	int ret;
3112 
3113 	p->scx.disallow = false;
3114 
3115 	if (SCX_HAS_OP(sch, init_task)) {
3116 		struct scx_init_task_args args = {
3117 			SCX_INIT_TASK_ARGS_CGROUP(tg)
3118 			.fork = fork,
3119 		};
3120 
3121 		ret = SCX_CALL_OP_RET(sch, SCX_KF_UNLOCKED, init_task, NULL,
3122 				      p, &args);
3123 		if (unlikely(ret)) {
3124 			ret = ops_sanitize_err(sch, "init_task", ret);
3125 			return ret;
3126 		}
3127 	}
3128 
3129 	scx_set_task_state(p, SCX_TASK_INIT);
3130 
3131 	if (p->scx.disallow) {
3132 		if (unlikely(scx_parent(sch))) {
3133 			scx_error(sch, "non-root ops.init_task() set task->scx.disallow for %s[%d]",
3134 				  p->comm, p->pid);
3135 		} else if (unlikely(fork)) {
3136 			scx_error(sch, "ops.init_task() set task->scx.disallow for %s[%d] during fork",
3137 				  p->comm, p->pid);
3138 		} else {
3139 			struct rq *rq;
3140 			struct rq_flags rf;
3141 
3142 			rq = task_rq_lock(p, &rf);
3143 
3144 			/*
3145 			 * We're in the load path and @p->policy will be applied
3146 			 * right after. Reverting @p->policy here and rejecting
3147 			 * %SCHED_EXT transitions from scx_check_setscheduler()
3148 			 * guarantees that if ops.init_task() sets @p->disallow,
3149 			 * @p can never be in SCX.
3150 			 */
3151 			if (p->policy == SCHED_EXT) {
3152 				p->policy = SCHED_NORMAL;
3153 				atomic_long_inc(&scx_nr_rejected);
3154 			}
3155 
3156 			task_rq_unlock(rq, p, &rf);
3157 		}
3158 	}
3159 
3160 	p->scx.flags |= SCX_TASK_RESET_RUNNABLE_AT;
3161 	return 0;
3162 }
3163 
3164 static void scx_enable_task(struct task_struct *p)
3165 {
3166 	struct scx_sched *sch = scx_root;
3167 	struct rq *rq = task_rq(p);
3168 	u32 weight;
3169 
3170 	lockdep_assert_rq_held(rq);
3171 
3172 	/*
3173 	 * Verify the task is not in BPF scheduler's custody. If flag
3174 	 * transitions are consistent, the flag should always be clear
3175 	 * here.
3176 	 */
3177 	WARN_ON_ONCE(p->scx.flags & SCX_TASK_IN_CUSTODY);
3178 
3179 	/*
3180 	 * Set the weight before calling ops.enable() so that the scheduler
3181 	 * doesn't see a stale value if they inspect the task struct.
3182 	 */
3183 	if (task_has_idle_policy(p))
3184 		weight = WEIGHT_IDLEPRIO;
3185 	else
3186 		weight = sched_prio_to_weight[p->static_prio - MAX_RT_PRIO];
3187 
3188 	p->scx.weight = sched_weight_to_cgroup(weight);
3189 
3190 	if (SCX_HAS_OP(sch, enable))
3191 		SCX_CALL_OP_TASK(sch, SCX_KF_REST, enable, rq, p);
3192 	scx_set_task_state(p, SCX_TASK_ENABLED);
3193 
3194 	if (SCX_HAS_OP(sch, set_weight))
3195 		SCX_CALL_OP_TASK(sch, SCX_KF_REST, set_weight, rq,
3196 				 p, p->scx.weight);
3197 }
3198 
3199 static void scx_disable_task(struct task_struct *p)
3200 {
3201 	struct scx_sched *sch = scx_root;
3202 	struct rq *rq = task_rq(p);
3203 
3204 	lockdep_assert_rq_held(rq);
3205 	WARN_ON_ONCE(scx_get_task_state(p) != SCX_TASK_ENABLED);
3206 
3207 	if (SCX_HAS_OP(sch, disable))
3208 		SCX_CALL_OP_TASK(sch, SCX_KF_REST, disable, rq, p);
3209 	scx_set_task_state(p, SCX_TASK_READY);
3210 
3211 	/*
3212 	 * Verify the task is not in BPF scheduler's custody. If flag
3213 	 * transitions are consistent, the flag should always be clear
3214 	 * here.
3215 	 */
3216 	WARN_ON_ONCE(p->scx.flags & SCX_TASK_IN_CUSTODY);
3217 }
3218 
3219 static void scx_exit_task(struct task_struct *p)
3220 {
3221 	struct scx_sched *sch = scx_task_sched(p);
3222 	struct scx_exit_task_args args = {
3223 		.cancelled = false,
3224 	};
3225 
3226 	lockdep_assert_held(&p->pi_lock);
3227 	lockdep_assert_rq_held(task_rq(p));
3228 
3229 	switch (scx_get_task_state(p)) {
3230 	case SCX_TASK_NONE:
3231 		return;
3232 	case SCX_TASK_INIT:
3233 		args.cancelled = true;
3234 		break;
3235 	case SCX_TASK_READY:
3236 		break;
3237 	case SCX_TASK_ENABLED:
3238 		scx_disable_task(p);
3239 		break;
3240 	default:
3241 		WARN_ON_ONCE(true);
3242 		return;
3243 	}
3244 
3245 	if (SCX_HAS_OP(sch, exit_task))
3246 		SCX_CALL_OP_TASK(sch, SCX_KF_REST, exit_task, task_rq(p),
3247 				 p, &args);
3248 	scx_set_task_sched(p, NULL);
3249 	scx_set_task_state(p, SCX_TASK_NONE);
3250 }
3251 
3252 void init_scx_entity(struct sched_ext_entity *scx)
3253 {
3254 	memset(scx, 0, sizeof(*scx));
3255 	INIT_LIST_HEAD(&scx->dsq_list.node);
3256 	RB_CLEAR_NODE(&scx->dsq_priq);
3257 	scx->sticky_cpu = -1;
3258 	scx->holding_cpu = -1;
3259 	INIT_LIST_HEAD(&scx->runnable_node);
3260 	scx->runnable_at = jiffies;
3261 	scx->ddsp_dsq_id = SCX_DSQ_INVALID;
3262 	scx->slice = READ_ONCE(scx_slice_dfl);
3263 }
3264 
3265 void scx_pre_fork(struct task_struct *p)
3266 {
3267 	/*
3268 	 * BPF scheduler enable/disable paths want to be able to iterate and
3269 	 * update all tasks which can become complex when racing forks. As
3270 	 * enable/disable are very cold paths, let's use a percpu_rwsem to
3271 	 * exclude forks.
3272 	 */
3273 	percpu_down_read(&scx_fork_rwsem);
3274 }
3275 
3276 int scx_fork(struct task_struct *p, struct kernel_clone_args *kargs)
3277 {
3278 	s32 ret;
3279 
3280 	percpu_rwsem_assert_held(&scx_fork_rwsem);
3281 
3282 	if (scx_init_task_enabled) {
3283 		ret = scx_init_task(p, task_group(p), true);
3284 		if (!ret)
3285 			scx_set_task_sched(p, scx_root);
3286 		return ret;
3287 	}
3288 
3289 	return 0;
3290 }
3291 
3292 void scx_post_fork(struct task_struct *p)
3293 {
3294 	if (scx_init_task_enabled) {
3295 		scx_set_task_state(p, SCX_TASK_READY);
3296 
3297 		/*
3298 		 * Enable the task immediately if it's running on sched_ext.
3299 		 * Otherwise, it'll be enabled in switching_to_scx() if and
3300 		 * when it's ever configured to run with a SCHED_EXT policy.
3301 		 */
3302 		if (p->sched_class == &ext_sched_class) {
3303 			struct rq_flags rf;
3304 			struct rq *rq;
3305 
3306 			rq = task_rq_lock(p, &rf);
3307 			scx_enable_task(p);
3308 			task_rq_unlock(rq, p, &rf);
3309 		}
3310 	}
3311 
3312 	raw_spin_lock_irq(&scx_tasks_lock);
3313 	list_add_tail(&p->scx.tasks_node, &scx_tasks);
3314 	raw_spin_unlock_irq(&scx_tasks_lock);
3315 
3316 	percpu_up_read(&scx_fork_rwsem);
3317 }
3318 
3319 void scx_cancel_fork(struct task_struct *p)
3320 {
3321 	if (scx_enabled()) {
3322 		struct rq *rq;
3323 		struct rq_flags rf;
3324 
3325 		rq = task_rq_lock(p, &rf);
3326 		WARN_ON_ONCE(scx_get_task_state(p) >= SCX_TASK_READY);
3327 		scx_exit_task(p);
3328 		task_rq_unlock(rq, p, &rf);
3329 	}
3330 
3331 	percpu_up_read(&scx_fork_rwsem);
3332 }
3333 
3334 /**
3335  * task_dead_and_done - Is a task dead and done running?
3336  * @p: target task
3337  *
3338  * Once sched_ext_dead() removes the dead task from scx_tasks and exits it, the
3339  * task no longer exists from SCX's POV. However, certain sched_class ops may be
3340  * invoked on these dead tasks leading to failures - e.g. sched_setscheduler()
3341  * may try to switch a task which finished sched_ext_dead() back into SCX
3342  * triggering invalid SCX task state transitions and worse.
3343  *
3344  * Once a task has finished the final switch, sched_ext_dead() is the only thing
3345  * that needs to happen on the task. Use this test to short-circuit sched_class
3346  * operations which may be called on dead tasks.
3347  */
3348 static bool task_dead_and_done(struct task_struct *p)
3349 {
3350 	struct rq *rq = task_rq(p);
3351 
3352 	lockdep_assert_rq_held(rq);
3353 
3354 	/*
3355 	 * In do_task_dead(), a dying task sets %TASK_DEAD with preemption
3356 	 * disabled and __schedule(). If @p has %TASK_DEAD set and off CPU, @p
3357 	 * won't ever run again.
3358 	 */
3359 	return unlikely(READ_ONCE(p->__state) == TASK_DEAD) &&
3360 		!task_on_cpu(rq, p);
3361 }
3362 
3363 void sched_ext_dead(struct task_struct *p)
3364 {
3365 	unsigned long flags;
3366 
3367 	/*
3368 	 * By the time control reaches here, @p has %TASK_DEAD set, switched out
3369 	 * for the last time and then dropped the rq lock - task_dead_and_done()
3370 	 * should be returning %true nullifying the straggling sched_class ops.
3371 	 * Remove from scx_tasks and exit @p.
3372 	 */
3373 	raw_spin_lock_irqsave(&scx_tasks_lock, flags);
3374 	list_del_init(&p->scx.tasks_node);
3375 	raw_spin_unlock_irqrestore(&scx_tasks_lock, flags);
3376 
3377 	/*
3378 	 * @p is off scx_tasks and wholly ours. scx_root_enable()'s READY ->
3379 	 * ENABLED transitions can't race us. Disable ops for @p.
3380 	 */
3381 	if (scx_get_task_state(p) != SCX_TASK_NONE) {
3382 		struct rq_flags rf;
3383 		struct rq *rq;
3384 
3385 		rq = task_rq_lock(p, &rf);
3386 		scx_exit_task(p);
3387 		task_rq_unlock(rq, p, &rf);
3388 	}
3389 }
3390 
3391 static void reweight_task_scx(struct rq *rq, struct task_struct *p,
3392 			      const struct load_weight *lw)
3393 {
3394 	struct scx_sched *sch = scx_task_sched(p);
3395 
3396 	lockdep_assert_rq_held(task_rq(p));
3397 
3398 	if (task_dead_and_done(p))
3399 		return;
3400 
3401 	p->scx.weight = sched_weight_to_cgroup(scale_load_down(lw->weight));
3402 	if (SCX_HAS_OP(sch, set_weight))
3403 		SCX_CALL_OP_TASK(sch, SCX_KF_REST, set_weight, rq,
3404 				 p, p->scx.weight);
3405 }
3406 
3407 static void prio_changed_scx(struct rq *rq, struct task_struct *p, u64 oldprio)
3408 {
3409 }
3410 
3411 static void switching_to_scx(struct rq *rq, struct task_struct *p)
3412 {
3413 	struct scx_sched *sch = scx_task_sched(p);
3414 
3415 	if (task_dead_and_done(p))
3416 		return;
3417 
3418 	scx_enable_task(p);
3419 
3420 	/*
3421 	 * set_cpus_allowed_scx() is not called while @p is associated with a
3422 	 * different scheduler class. Keep the BPF scheduler up-to-date.
3423 	 */
3424 	if (SCX_HAS_OP(sch, set_cpumask))
3425 		SCX_CALL_OP_TASK(sch, SCX_KF_REST, set_cpumask, rq,
3426 				 p, (struct cpumask *)p->cpus_ptr);
3427 }
3428 
3429 static void switched_from_scx(struct rq *rq, struct task_struct *p)
3430 {
3431 	if (task_dead_and_done(p))
3432 		return;
3433 
3434 	scx_disable_task(p);
3435 }
3436 
3437 static void wakeup_preempt_scx(struct rq *rq, struct task_struct *p, int wake_flags) {}
3438 
3439 static void switched_to_scx(struct rq *rq, struct task_struct *p) {}
3440 
3441 int scx_check_setscheduler(struct task_struct *p, int policy)
3442 {
3443 	lockdep_assert_rq_held(task_rq(p));
3444 
3445 	/* if disallow, reject transitioning into SCX */
3446 	if (scx_enabled() && READ_ONCE(p->scx.disallow) &&
3447 	    p->policy != policy && policy == SCHED_EXT)
3448 		return -EACCES;
3449 
3450 	return 0;
3451 }
3452 
3453 #ifdef CONFIG_NO_HZ_FULL
3454 bool scx_can_stop_tick(struct rq *rq)
3455 {
3456 	struct task_struct *p = rq->curr;
3457 
3458 	if (scx_rq_bypassing(rq))
3459 		return false;
3460 
3461 	if (p->sched_class != &ext_sched_class)
3462 		return true;
3463 
3464 	/*
3465 	 * @rq can dispatch from different DSQs, so we can't tell whether it
3466 	 * needs the tick or not by looking at nr_running. Allow stopping ticks
3467 	 * iff the BPF scheduler indicated so. See set_next_task_scx().
3468 	 */
3469 	return rq->scx.flags & SCX_RQ_CAN_STOP_TICK;
3470 }
3471 #endif
3472 
3473 #ifdef CONFIG_EXT_GROUP_SCHED
3474 
3475 DEFINE_STATIC_PERCPU_RWSEM(scx_cgroup_ops_rwsem);
3476 static bool scx_cgroup_enabled;
3477 
3478 void scx_tg_init(struct task_group *tg)
3479 {
3480 	tg->scx.weight = CGROUP_WEIGHT_DFL;
3481 	tg->scx.bw_period_us = default_bw_period_us();
3482 	tg->scx.bw_quota_us = RUNTIME_INF;
3483 	tg->scx.idle = false;
3484 }
3485 
3486 int scx_tg_online(struct task_group *tg)
3487 {
3488 	struct scx_sched *sch = scx_root;
3489 	int ret = 0;
3490 
3491 	WARN_ON_ONCE(tg->scx.flags & (SCX_TG_ONLINE | SCX_TG_INITED));
3492 
3493 	if (scx_cgroup_enabled) {
3494 		if (SCX_HAS_OP(sch, cgroup_init)) {
3495 			struct scx_cgroup_init_args args =
3496 				{ .weight = tg->scx.weight,
3497 				  .bw_period_us = tg->scx.bw_period_us,
3498 				  .bw_quota_us = tg->scx.bw_quota_us,
3499 				  .bw_burst_us = tg->scx.bw_burst_us };
3500 
3501 			ret = SCX_CALL_OP_RET(sch, SCX_KF_UNLOCKED, cgroup_init,
3502 					      NULL, tg->css.cgroup, &args);
3503 			if (ret)
3504 				ret = ops_sanitize_err(sch, "cgroup_init", ret);
3505 		}
3506 		if (ret == 0)
3507 			tg->scx.flags |= SCX_TG_ONLINE | SCX_TG_INITED;
3508 	} else {
3509 		tg->scx.flags |= SCX_TG_ONLINE;
3510 	}
3511 
3512 	return ret;
3513 }
3514 
3515 void scx_tg_offline(struct task_group *tg)
3516 {
3517 	struct scx_sched *sch = scx_root;
3518 
3519 	WARN_ON_ONCE(!(tg->scx.flags & SCX_TG_ONLINE));
3520 
3521 	if (scx_cgroup_enabled && SCX_HAS_OP(sch, cgroup_exit) &&
3522 	    (tg->scx.flags & SCX_TG_INITED))
3523 		SCX_CALL_OP(sch, SCX_KF_UNLOCKED, cgroup_exit, NULL,
3524 			    tg->css.cgroup);
3525 	tg->scx.flags &= ~(SCX_TG_ONLINE | SCX_TG_INITED);
3526 }
3527 
3528 int scx_cgroup_can_attach(struct cgroup_taskset *tset)
3529 {
3530 	struct scx_sched *sch = scx_root;
3531 	struct cgroup_subsys_state *css;
3532 	struct task_struct *p;
3533 	int ret;
3534 
3535 	if (!scx_cgroup_enabled)
3536 		return 0;
3537 
3538 	cgroup_taskset_for_each(p, css, tset) {
3539 		struct cgroup *from = tg_cgrp(task_group(p));
3540 		struct cgroup *to = tg_cgrp(css_tg(css));
3541 
3542 		WARN_ON_ONCE(p->scx.cgrp_moving_from);
3543 
3544 		/*
3545 		 * sched_move_task() omits identity migrations. Let's match the
3546 		 * behavior so that ops.cgroup_prep_move() and ops.cgroup_move()
3547 		 * always match one-to-one.
3548 		 */
3549 		if (from == to)
3550 			continue;
3551 
3552 		if (SCX_HAS_OP(sch, cgroup_prep_move)) {
3553 			ret = SCX_CALL_OP_RET(sch, SCX_KF_UNLOCKED,
3554 					      cgroup_prep_move, NULL,
3555 					      p, from, css->cgroup);
3556 			if (ret)
3557 				goto err;
3558 		}
3559 
3560 		p->scx.cgrp_moving_from = from;
3561 	}
3562 
3563 	return 0;
3564 
3565 err:
3566 	cgroup_taskset_for_each(p, css, tset) {
3567 		if (SCX_HAS_OP(sch, cgroup_cancel_move) &&
3568 		    p->scx.cgrp_moving_from)
3569 			SCX_CALL_OP(sch, SCX_KF_UNLOCKED, cgroup_cancel_move, NULL,
3570 				    p, p->scx.cgrp_moving_from, css->cgroup);
3571 		p->scx.cgrp_moving_from = NULL;
3572 	}
3573 
3574 	return ops_sanitize_err(sch, "cgroup_prep_move", ret);
3575 }
3576 
3577 void scx_cgroup_move_task(struct task_struct *p)
3578 {
3579 	struct scx_sched *sch = scx_root;
3580 
3581 	if (!scx_cgroup_enabled)
3582 		return;
3583 
3584 	/*
3585 	 * @p must have ops.cgroup_prep_move() called on it and thus
3586 	 * cgrp_moving_from set.
3587 	 */
3588 	if (SCX_HAS_OP(sch, cgroup_move) &&
3589 	    !WARN_ON_ONCE(!p->scx.cgrp_moving_from))
3590 		SCX_CALL_OP_TASK(sch, SCX_KF_UNLOCKED, cgroup_move, NULL,
3591 				 p, p->scx.cgrp_moving_from,
3592 				 tg_cgrp(task_group(p)));
3593 	p->scx.cgrp_moving_from = NULL;
3594 }
3595 
3596 void scx_cgroup_cancel_attach(struct cgroup_taskset *tset)
3597 {
3598 	struct scx_sched *sch = scx_root;
3599 	struct cgroup_subsys_state *css;
3600 	struct task_struct *p;
3601 
3602 	if (!scx_cgroup_enabled)
3603 		return;
3604 
3605 	cgroup_taskset_for_each(p, css, tset) {
3606 		if (SCX_HAS_OP(sch, cgroup_cancel_move) &&
3607 		    p->scx.cgrp_moving_from)
3608 			SCX_CALL_OP(sch, SCX_KF_UNLOCKED, cgroup_cancel_move, NULL,
3609 				    p, p->scx.cgrp_moving_from, css->cgroup);
3610 		p->scx.cgrp_moving_from = NULL;
3611 	}
3612 }
3613 
3614 void scx_group_set_weight(struct task_group *tg, unsigned long weight)
3615 {
3616 	struct scx_sched *sch = scx_root;
3617 
3618 	percpu_down_read(&scx_cgroup_ops_rwsem);
3619 
3620 	if (scx_cgroup_enabled && SCX_HAS_OP(sch, cgroup_set_weight) &&
3621 	    tg->scx.weight != weight)
3622 		SCX_CALL_OP(sch, SCX_KF_UNLOCKED, cgroup_set_weight, NULL,
3623 			    tg_cgrp(tg), weight);
3624 
3625 	tg->scx.weight = weight;
3626 
3627 	percpu_up_read(&scx_cgroup_ops_rwsem);
3628 }
3629 
3630 void scx_group_set_idle(struct task_group *tg, bool idle)
3631 {
3632 	struct scx_sched *sch = scx_root;
3633 
3634 	percpu_down_read(&scx_cgroup_ops_rwsem);
3635 
3636 	if (scx_cgroup_enabled && SCX_HAS_OP(sch, cgroup_set_idle))
3637 		SCX_CALL_OP(sch, SCX_KF_UNLOCKED, cgroup_set_idle, NULL,
3638 			    tg_cgrp(tg), idle);
3639 
3640 	/* Update the task group's idle state */
3641 	tg->scx.idle = idle;
3642 
3643 	percpu_up_read(&scx_cgroup_ops_rwsem);
3644 }
3645 
3646 void scx_group_set_bandwidth(struct task_group *tg,
3647 			     u64 period_us, u64 quota_us, u64 burst_us)
3648 {
3649 	struct scx_sched *sch = scx_root;
3650 
3651 	percpu_down_read(&scx_cgroup_ops_rwsem);
3652 
3653 	if (scx_cgroup_enabled && SCX_HAS_OP(sch, cgroup_set_bandwidth) &&
3654 	    (tg->scx.bw_period_us != period_us ||
3655 	     tg->scx.bw_quota_us != quota_us ||
3656 	     tg->scx.bw_burst_us != burst_us))
3657 		SCX_CALL_OP(sch, SCX_KF_UNLOCKED, cgroup_set_bandwidth, NULL,
3658 			    tg_cgrp(tg), period_us, quota_us, burst_us);
3659 
3660 	tg->scx.bw_period_us = period_us;
3661 	tg->scx.bw_quota_us = quota_us;
3662 	tg->scx.bw_burst_us = burst_us;
3663 
3664 	percpu_up_read(&scx_cgroup_ops_rwsem);
3665 }
3666 #endif	/* CONFIG_EXT_GROUP_SCHED */
3667 
3668 #if defined(CONFIG_EXT_GROUP_SCHED) || defined(CONFIG_EXT_SUB_SCHED)
3669 static struct cgroup *root_cgroup(void)
3670 {
3671 	return &cgrp_dfl_root.cgrp;
3672 }
3673 
3674 static struct cgroup *sch_cgroup(struct scx_sched *sch)
3675 {
3676 	return sch->cgrp;
3677 }
3678 
3679 /* for each descendant of @cgrp including self, set ->scx_sched to @sch */
3680 static void set_cgroup_sched(struct cgroup *cgrp, struct scx_sched *sch)
3681 {
3682 	struct cgroup *pos;
3683 	struct cgroup_subsys_state *css;
3684 
3685 	cgroup_for_each_live_descendant_pre(pos, css, cgrp)
3686 		rcu_assign_pointer(pos->scx_sched, sch);
3687 }
3688 
3689 static void scx_cgroup_lock(void)
3690 {
3691 #ifdef CONFIG_EXT_GROUP_SCHED
3692 	percpu_down_write(&scx_cgroup_ops_rwsem);
3693 #endif
3694 	cgroup_lock();
3695 }
3696 
3697 static void scx_cgroup_unlock(void)
3698 {
3699 	cgroup_unlock();
3700 #ifdef CONFIG_EXT_GROUP_SCHED
3701 	percpu_up_write(&scx_cgroup_ops_rwsem);
3702 #endif
3703 }
3704 #else	/* CONFIG_EXT_GROUP_SCHED || CONFIG_EXT_SUB_SCHED */
3705 static struct cgroup *root_cgroup(void) { return NULL; }
3706 static struct cgroup *sch_cgroup(struct scx_sched *sch) { return NULL; }
3707 static void set_cgroup_sched(struct cgroup *cgrp, struct scx_sched *sch) {}
3708 static void scx_cgroup_lock(void) {}
3709 static void scx_cgroup_unlock(void) {}
3710 #endif	/* CONFIG_EXT_GROUP_SCHED || CONFIG_EXT_SUB_SCHED */
3711 
3712 /*
3713  * Omitted operations:
3714  *
3715  * - wakeup_preempt: NOOP as it isn't useful in the wakeup path because the task
3716  *   isn't tied to the CPU at that point. Preemption is implemented by resetting
3717  *   the victim task's slice to 0 and triggering reschedule on the target CPU.
3718  *
3719  * - migrate_task_rq: Unnecessary as task to cpu mapping is transient.
3720  *
3721  * - task_fork/dead: We need fork/dead notifications for all tasks regardless of
3722  *   their current sched_class. Call them directly from sched core instead.
3723  */
3724 DEFINE_SCHED_CLASS(ext) = {
3725 	.enqueue_task		= enqueue_task_scx,
3726 	.dequeue_task		= dequeue_task_scx,
3727 	.yield_task		= yield_task_scx,
3728 	.yield_to_task		= yield_to_task_scx,
3729 
3730 	.wakeup_preempt		= wakeup_preempt_scx,
3731 
3732 	.pick_task		= pick_task_scx,
3733 
3734 	.put_prev_task		= put_prev_task_scx,
3735 	.set_next_task		= set_next_task_scx,
3736 
3737 	.select_task_rq		= select_task_rq_scx,
3738 	.task_woken		= task_woken_scx,
3739 	.set_cpus_allowed	= set_cpus_allowed_scx,
3740 
3741 	.rq_online		= rq_online_scx,
3742 	.rq_offline		= rq_offline_scx,
3743 
3744 	.task_tick		= task_tick_scx,
3745 
3746 	.switching_to		= switching_to_scx,
3747 	.switched_from		= switched_from_scx,
3748 	.switched_to		= switched_to_scx,
3749 	.reweight_task		= reweight_task_scx,
3750 	.prio_changed		= prio_changed_scx,
3751 
3752 	.update_curr		= update_curr_scx,
3753 
3754 #ifdef CONFIG_UCLAMP_TASK
3755 	.uclamp_enabled		= 1,
3756 #endif
3757 };
3758 
3759 static void init_dsq(struct scx_dispatch_q *dsq, u64 dsq_id,
3760 		     struct scx_sched *sch)
3761 {
3762 	memset(dsq, 0, sizeof(*dsq));
3763 
3764 	raw_spin_lock_init(&dsq->lock);
3765 	INIT_LIST_HEAD(&dsq->list);
3766 	dsq->id = dsq_id;
3767 	dsq->sched = sch;
3768 }
3769 
3770 static void free_dsq_irq_workfn(struct irq_work *irq_work)
3771 {
3772 	struct llist_node *to_free = llist_del_all(&dsqs_to_free);
3773 	struct scx_dispatch_q *dsq, *tmp_dsq;
3774 
3775 	llist_for_each_entry_safe(dsq, tmp_dsq, to_free, free_node)
3776 		kfree_rcu(dsq, rcu);
3777 }
3778 
3779 static DEFINE_IRQ_WORK(free_dsq_irq_work, free_dsq_irq_workfn);
3780 
3781 static void destroy_dsq(struct scx_sched *sch, u64 dsq_id)
3782 {
3783 	struct scx_dispatch_q *dsq;
3784 	unsigned long flags;
3785 
3786 	rcu_read_lock();
3787 
3788 	dsq = find_user_dsq(sch, dsq_id);
3789 	if (!dsq)
3790 		goto out_unlock_rcu;
3791 
3792 	raw_spin_lock_irqsave(&dsq->lock, flags);
3793 
3794 	if (dsq->nr) {
3795 		scx_error(sch, "attempting to destroy in-use dsq 0x%016llx (nr=%u)",
3796 			  dsq->id, dsq->nr);
3797 		goto out_unlock_dsq;
3798 	}
3799 
3800 	if (rhashtable_remove_fast(&sch->dsq_hash, &dsq->hash_node,
3801 				   dsq_hash_params))
3802 		goto out_unlock_dsq;
3803 
3804 	/*
3805 	 * Mark dead by invalidating ->id to prevent dispatch_enqueue() from
3806 	 * queueing more tasks. As this function can be called from anywhere,
3807 	 * freeing is bounced through an irq work to avoid nesting RCU
3808 	 * operations inside scheduler locks.
3809 	 */
3810 	dsq->id = SCX_DSQ_INVALID;
3811 	if (llist_add(&dsq->free_node, &dsqs_to_free))
3812 		irq_work_queue(&free_dsq_irq_work);
3813 
3814 out_unlock_dsq:
3815 	raw_spin_unlock_irqrestore(&dsq->lock, flags);
3816 out_unlock_rcu:
3817 	rcu_read_unlock();
3818 }
3819 
3820 #ifdef CONFIG_EXT_GROUP_SCHED
3821 static void scx_cgroup_exit(struct scx_sched *sch)
3822 {
3823 	struct cgroup_subsys_state *css;
3824 
3825 	scx_cgroup_enabled = false;
3826 
3827 	/*
3828 	 * scx_tg_on/offline() are excluded through cgroup_lock(). If we walk
3829 	 * cgroups and exit all the inited ones, all online cgroups are exited.
3830 	 */
3831 	css_for_each_descendant_post(css, &root_task_group.css) {
3832 		struct task_group *tg = css_tg(css);
3833 
3834 		if (!(tg->scx.flags & SCX_TG_INITED))
3835 			continue;
3836 		tg->scx.flags &= ~SCX_TG_INITED;
3837 
3838 		if (!sch->ops.cgroup_exit)
3839 			continue;
3840 
3841 		SCX_CALL_OP(sch, SCX_KF_UNLOCKED, cgroup_exit, NULL,
3842 			    css->cgroup);
3843 	}
3844 }
3845 
3846 static int scx_cgroup_init(struct scx_sched *sch)
3847 {
3848 	struct cgroup_subsys_state *css;
3849 	int ret;
3850 
3851 	/*
3852 	 * scx_tg_on/offline() are excluded through cgroup_lock(). If we walk
3853 	 * cgroups and init, all online cgroups are initialized.
3854 	 */
3855 	css_for_each_descendant_pre(css, &root_task_group.css) {
3856 		struct task_group *tg = css_tg(css);
3857 		struct scx_cgroup_init_args args = {
3858 			.weight = tg->scx.weight,
3859 			.bw_period_us = tg->scx.bw_period_us,
3860 			.bw_quota_us = tg->scx.bw_quota_us,
3861 			.bw_burst_us = tg->scx.bw_burst_us,
3862 		};
3863 
3864 		if ((tg->scx.flags &
3865 		     (SCX_TG_ONLINE | SCX_TG_INITED)) != SCX_TG_ONLINE)
3866 			continue;
3867 
3868 		if (!sch->ops.cgroup_init) {
3869 			tg->scx.flags |= SCX_TG_INITED;
3870 			continue;
3871 		}
3872 
3873 		ret = SCX_CALL_OP_RET(sch, SCX_KF_UNLOCKED, cgroup_init, NULL,
3874 				      css->cgroup, &args);
3875 		if (ret) {
3876 			scx_error(sch, "ops.cgroup_init() failed (%d)", ret);
3877 			return ret;
3878 		}
3879 		tg->scx.flags |= SCX_TG_INITED;
3880 	}
3881 
3882 	WARN_ON_ONCE(scx_cgroup_enabled);
3883 	scx_cgroup_enabled = true;
3884 
3885 	return 0;
3886 }
3887 
3888 #else
3889 static void scx_cgroup_exit(struct scx_sched *sch) {}
3890 static int scx_cgroup_init(struct scx_sched *sch) { return 0; }
3891 #endif
3892 
3893 
3894 /********************************************************************************
3895  * Sysfs interface and ops enable/disable.
3896  */
3897 
3898 #define SCX_ATTR(_name)								\
3899 	static struct kobj_attribute scx_attr_##_name = {			\
3900 		.attr = { .name = __stringify(_name), .mode = 0444 },		\
3901 		.show = scx_attr_##_name##_show,				\
3902 	}
3903 
3904 static ssize_t scx_attr_state_show(struct kobject *kobj,
3905 				   struct kobj_attribute *ka, char *buf)
3906 {
3907 	return sysfs_emit(buf, "%s\n", scx_enable_state_str[scx_enable_state()]);
3908 }
3909 SCX_ATTR(state);
3910 
3911 static ssize_t scx_attr_switch_all_show(struct kobject *kobj,
3912 					struct kobj_attribute *ka, char *buf)
3913 {
3914 	return sysfs_emit(buf, "%d\n", READ_ONCE(scx_switching_all));
3915 }
3916 SCX_ATTR(switch_all);
3917 
3918 static ssize_t scx_attr_nr_rejected_show(struct kobject *kobj,
3919 					 struct kobj_attribute *ka, char *buf)
3920 {
3921 	return sysfs_emit(buf, "%ld\n", atomic_long_read(&scx_nr_rejected));
3922 }
3923 SCX_ATTR(nr_rejected);
3924 
3925 static ssize_t scx_attr_hotplug_seq_show(struct kobject *kobj,
3926 					 struct kobj_attribute *ka, char *buf)
3927 {
3928 	return sysfs_emit(buf, "%ld\n", atomic_long_read(&scx_hotplug_seq));
3929 }
3930 SCX_ATTR(hotplug_seq);
3931 
3932 static ssize_t scx_attr_enable_seq_show(struct kobject *kobj,
3933 					struct kobj_attribute *ka, char *buf)
3934 {
3935 	return sysfs_emit(buf, "%ld\n", atomic_long_read(&scx_enable_seq));
3936 }
3937 SCX_ATTR(enable_seq);
3938 
3939 static struct attribute *scx_global_attrs[] = {
3940 	&scx_attr_state.attr,
3941 	&scx_attr_switch_all.attr,
3942 	&scx_attr_nr_rejected.attr,
3943 	&scx_attr_hotplug_seq.attr,
3944 	&scx_attr_enable_seq.attr,
3945 	NULL,
3946 };
3947 
3948 static const struct attribute_group scx_global_attr_group = {
3949 	.attrs = scx_global_attrs,
3950 };
3951 
3952 static void free_exit_info(struct scx_exit_info *ei);
3953 
3954 static void scx_sched_free_rcu_work(struct work_struct *work)
3955 {
3956 	struct rcu_work *rcu_work = to_rcu_work(work);
3957 	struct scx_sched *sch = container_of(rcu_work, struct scx_sched, rcu_work);
3958 	struct rhashtable_iter rht_iter;
3959 	struct scx_dispatch_q *dsq;
3960 	int node;
3961 
3962 	irq_work_sync(&sch->error_irq_work);
3963 	kthread_destroy_worker(sch->helper);
3964 
3965 #ifdef CONFIG_EXT_SUB_SCHED
3966 	kfree(sch->cgrp_path);
3967 	if (sch_cgroup(sch))
3968 		cgroup_put(sch_cgroup(sch));
3969 #endif	/* CONFIG_EXT_SUB_SCHED */
3970 
3971 	free_percpu(sch->pcpu);
3972 
3973 	for_each_node_state(node, N_POSSIBLE)
3974 		kfree(sch->global_dsqs[node]);
3975 	kfree(sch->global_dsqs);
3976 
3977 	rhashtable_walk_enter(&sch->dsq_hash, &rht_iter);
3978 	do {
3979 		rhashtable_walk_start(&rht_iter);
3980 
3981 		while ((dsq = rhashtable_walk_next(&rht_iter)) && !IS_ERR(dsq))
3982 			destroy_dsq(sch, dsq->id);
3983 
3984 		rhashtable_walk_stop(&rht_iter);
3985 	} while (dsq == ERR_PTR(-EAGAIN));
3986 	rhashtable_walk_exit(&rht_iter);
3987 
3988 	rhashtable_free_and_destroy(&sch->dsq_hash, NULL, NULL);
3989 	free_exit_info(sch->exit_info);
3990 	kfree(sch);
3991 }
3992 
3993 static void scx_kobj_release(struct kobject *kobj)
3994 {
3995 	struct scx_sched *sch = container_of(kobj, struct scx_sched, kobj);
3996 
3997 	INIT_RCU_WORK(&sch->rcu_work, scx_sched_free_rcu_work);
3998 	queue_rcu_work(system_unbound_wq, &sch->rcu_work);
3999 }
4000 
4001 static ssize_t scx_attr_ops_show(struct kobject *kobj,
4002 				 struct kobj_attribute *ka, char *buf)
4003 {
4004 	struct scx_sched *sch = container_of(kobj, struct scx_sched, kobj);
4005 
4006 	return sysfs_emit(buf, "%s\n", sch->ops.name);
4007 }
4008 SCX_ATTR(ops);
4009 
4010 #define scx_attr_event_show(buf, at, events, kind) ({				\
4011 	sysfs_emit_at(buf, at, "%s %llu\n", #kind, (events)->kind);		\
4012 })
4013 
4014 static ssize_t scx_attr_events_show(struct kobject *kobj,
4015 				    struct kobj_attribute *ka, char *buf)
4016 {
4017 	struct scx_sched *sch = container_of(kobj, struct scx_sched, kobj);
4018 	struct scx_event_stats events;
4019 	int at = 0;
4020 
4021 	scx_read_events(sch, &events);
4022 	at += scx_attr_event_show(buf, at, &events, SCX_EV_SELECT_CPU_FALLBACK);
4023 	at += scx_attr_event_show(buf, at, &events, SCX_EV_DISPATCH_LOCAL_DSQ_OFFLINE);
4024 	at += scx_attr_event_show(buf, at, &events, SCX_EV_DISPATCH_KEEP_LAST);
4025 	at += scx_attr_event_show(buf, at, &events, SCX_EV_ENQ_SKIP_EXITING);
4026 	at += scx_attr_event_show(buf, at, &events, SCX_EV_ENQ_SKIP_MIGRATION_DISABLED);
4027 	at += scx_attr_event_show(buf, at, &events, SCX_EV_REFILL_SLICE_DFL);
4028 	at += scx_attr_event_show(buf, at, &events, SCX_EV_BYPASS_DURATION);
4029 	at += scx_attr_event_show(buf, at, &events, SCX_EV_BYPASS_DISPATCH);
4030 	at += scx_attr_event_show(buf, at, &events, SCX_EV_BYPASS_ACTIVATE);
4031 	return at;
4032 }
4033 SCX_ATTR(events);
4034 
4035 static struct attribute *scx_sched_attrs[] = {
4036 	&scx_attr_ops.attr,
4037 	&scx_attr_events.attr,
4038 	NULL,
4039 };
4040 ATTRIBUTE_GROUPS(scx_sched);
4041 
4042 static const struct kobj_type scx_ktype = {
4043 	.release = scx_kobj_release,
4044 	.sysfs_ops = &kobj_sysfs_ops,
4045 	.default_groups = scx_sched_groups,
4046 };
4047 
4048 static int scx_uevent(const struct kobject *kobj, struct kobj_uevent_env *env)
4049 {
4050 	const struct scx_sched *sch = container_of(kobj, struct scx_sched, kobj);
4051 
4052 	return add_uevent_var(env, "SCXOPS=%s", sch->ops.name);
4053 }
4054 
4055 static const struct kset_uevent_ops scx_uevent_ops = {
4056 	.uevent = scx_uevent,
4057 };
4058 
4059 /*
4060  * Used by sched_fork() and __setscheduler_prio() to pick the matching
4061  * sched_class. dl/rt are already handled.
4062  */
4063 bool task_should_scx(int policy)
4064 {
4065 	if (!scx_enabled() || unlikely(scx_enable_state() == SCX_DISABLING))
4066 		return false;
4067 	if (READ_ONCE(scx_switching_all))
4068 		return true;
4069 	return policy == SCHED_EXT;
4070 }
4071 
4072 bool scx_allow_ttwu_queue(const struct task_struct *p)
4073 {
4074 	struct scx_sched *sch;
4075 
4076 	if (!scx_enabled())
4077 		return true;
4078 
4079 	sch = scx_task_sched(p);
4080 	if (unlikely(!sch))
4081 		return true;
4082 
4083 	if (sch->ops.flags & SCX_OPS_ALLOW_QUEUED_WAKEUP)
4084 		return true;
4085 
4086 	if (unlikely(p->sched_class != &ext_sched_class))
4087 		return true;
4088 
4089 	return false;
4090 }
4091 
4092 /**
4093  * handle_lockup - sched_ext common lockup handler
4094  * @fmt: format string
4095  *
4096  * Called on system stall or lockup condition and initiates abort of sched_ext
4097  * if enabled, which may resolve the reported lockup.
4098  *
4099  * Returns %true if sched_ext is enabled and abort was initiated, which may
4100  * resolve the lockup. %false if sched_ext is not enabled or abort was already
4101  * initiated by someone else.
4102  */
4103 static __printf(1, 2) bool handle_lockup(const char *fmt, ...)
4104 {
4105 	struct scx_sched *sch;
4106 	va_list args;
4107 	bool ret;
4108 
4109 	guard(rcu)();
4110 
4111 	sch = rcu_dereference(scx_root);
4112 	if (unlikely(!sch))
4113 		return false;
4114 
4115 	switch (scx_enable_state()) {
4116 	case SCX_ENABLING:
4117 	case SCX_ENABLED:
4118 		va_start(args, fmt);
4119 		ret = scx_verror(sch, fmt, args);
4120 		va_end(args);
4121 		return ret;
4122 	default:
4123 		return false;
4124 	}
4125 }
4126 
4127 /**
4128  * scx_rcu_cpu_stall - sched_ext RCU CPU stall handler
4129  *
4130  * While there are various reasons why RCU CPU stalls can occur on a system
4131  * that may not be caused by the current BPF scheduler, try kicking out the
4132  * current scheduler in an attempt to recover the system to a good state before
4133  * issuing panics.
4134  *
4135  * Returns %true if sched_ext is enabled and abort was initiated, which may
4136  * resolve the reported RCU stall. %false if sched_ext is not enabled or someone
4137  * else already initiated abort.
4138  */
4139 bool scx_rcu_cpu_stall(void)
4140 {
4141 	return handle_lockup("RCU CPU stall detected!");
4142 }
4143 
4144 /**
4145  * scx_softlockup - sched_ext softlockup handler
4146  * @dur_s: number of seconds of CPU stuck due to soft lockup
4147  *
4148  * On some multi-socket setups (e.g. 2x Intel 8480c), the BPF scheduler can
4149  * live-lock the system by making many CPUs target the same DSQ to the point
4150  * where soft-lockup detection triggers. This function is called from
4151  * soft-lockup watchdog when the triggering point is close and tries to unjam
4152  * the system and aborting the BPF scheduler.
4153  */
4154 void scx_softlockup(u32 dur_s)
4155 {
4156 	if (!handle_lockup("soft lockup - CPU %d stuck for %us", smp_processor_id(), dur_s))
4157 		return;
4158 
4159 	printk_deferred(KERN_ERR "sched_ext: Soft lockup - CPU %d stuck for %us, disabling BPF scheduler\n",
4160 			smp_processor_id(), dur_s);
4161 }
4162 
4163 /**
4164  * scx_hardlockup - sched_ext hardlockup handler
4165  *
4166  * A poorly behaving BPF scheduler can trigger hard lockup by e.g. putting
4167  * numerous affinitized tasks in a single queue and directing all CPUs at it.
4168  * Try kicking out the current scheduler in an attempt to recover the system to
4169  * a good state before taking more drastic actions.
4170  *
4171  * Returns %true if sched_ext is enabled and abort was initiated, which may
4172  * resolve the reported hardlockdup. %false if sched_ext is not enabled or
4173  * someone else already initiated abort.
4174  */
4175 bool scx_hardlockup(int cpu)
4176 {
4177 	if (!handle_lockup("hard lockup - CPU %d", cpu))
4178 		return false;
4179 
4180 	printk_deferred(KERN_ERR "sched_ext: Hard lockup - CPU %d, disabling BPF scheduler\n",
4181 			cpu);
4182 	return true;
4183 }
4184 
4185 static u32 bypass_lb_cpu(struct scx_sched *sch, struct rq *rq,
4186 			 struct cpumask *donee_mask, struct cpumask *resched_mask,
4187 			 u32 nr_donor_target, u32 nr_donee_target)
4188 {
4189 	struct scx_dispatch_q *donor_dsq = &rq->scx.bypass_dsq;
4190 	struct task_struct *p, *n;
4191 	struct scx_dsq_list_node cursor = INIT_DSQ_LIST_CURSOR(cursor, 0, 0);
4192 	s32 delta = READ_ONCE(donor_dsq->nr) - nr_donor_target;
4193 	u32 nr_balanced = 0, min_delta_us;
4194 
4195 	/*
4196 	 * All we want to guarantee is reasonable forward progress. No reason to
4197 	 * fine tune. Assuming every task on @donor_dsq runs their full slice,
4198 	 * consider offloading iff the total queued duration is over the
4199 	 * threshold.
4200 	 */
4201 	min_delta_us = READ_ONCE(scx_bypass_lb_intv_us) / SCX_BYPASS_LB_MIN_DELTA_DIV;
4202 	if (delta < DIV_ROUND_UP(min_delta_us, READ_ONCE(scx_slice_bypass_us)))
4203 		return 0;
4204 
4205 	raw_spin_rq_lock_irq(rq);
4206 	raw_spin_lock(&donor_dsq->lock);
4207 	list_add(&cursor.node, &donor_dsq->list);
4208 resume:
4209 	n = container_of(&cursor, struct task_struct, scx.dsq_list);
4210 	n = nldsq_next_task(donor_dsq, n, false);
4211 
4212 	while ((p = n)) {
4213 		struct rq *donee_rq;
4214 		struct scx_dispatch_q *donee_dsq;
4215 		int donee;
4216 
4217 		n = nldsq_next_task(donor_dsq, n, false);
4218 
4219 		if (donor_dsq->nr <= nr_donor_target)
4220 			break;
4221 
4222 		if (cpumask_empty(donee_mask))
4223 			break;
4224 
4225 		donee = cpumask_any_and_distribute(donee_mask, p->cpus_ptr);
4226 		if (donee >= nr_cpu_ids)
4227 			continue;
4228 
4229 		donee_rq = cpu_rq(donee);
4230 		donee_dsq = &donee_rq->scx.bypass_dsq;
4231 
4232 		/*
4233 		 * $p's rq is not locked but $p's DSQ lock protects its
4234 		 * scheduling properties making this test safe.
4235 		 */
4236 		if (!task_can_run_on_remote_rq(sch, p, donee_rq, false))
4237 			continue;
4238 
4239 		/*
4240 		 * Moving $p from one non-local DSQ to another. The source rq
4241 		 * and DSQ are already locked. Do an abbreviated dequeue and
4242 		 * then perform enqueue without unlocking $donor_dsq.
4243 		 *
4244 		 * We don't want to drop and reacquire the lock on each
4245 		 * iteration as @donor_dsq can be very long and potentially
4246 		 * highly contended. Donee DSQs are less likely to be contended.
4247 		 * The nested locking is safe as only this LB moves tasks
4248 		 * between bypass DSQs.
4249 		 */
4250 		dispatch_dequeue_locked(p, donor_dsq);
4251 		dispatch_enqueue(sch, donee_rq, donee_dsq, p, SCX_ENQ_NESTED);
4252 
4253 		/*
4254 		 * $donee might have been idle and need to be woken up. No need
4255 		 * to be clever. Kick every CPU that receives tasks.
4256 		 */
4257 		cpumask_set_cpu(donee, resched_mask);
4258 
4259 		if (READ_ONCE(donee_dsq->nr) >= nr_donee_target)
4260 			cpumask_clear_cpu(donee, donee_mask);
4261 
4262 		nr_balanced++;
4263 		if (!(nr_balanced % SCX_BYPASS_LB_BATCH) && n) {
4264 			list_move_tail(&cursor.node, &n->scx.dsq_list.node);
4265 			raw_spin_unlock(&donor_dsq->lock);
4266 			raw_spin_rq_unlock_irq(rq);
4267 			cpu_relax();
4268 			raw_spin_rq_lock_irq(rq);
4269 			raw_spin_lock(&donor_dsq->lock);
4270 			goto resume;
4271 		}
4272 	}
4273 
4274 	list_del_init(&cursor.node);
4275 	raw_spin_unlock(&donor_dsq->lock);
4276 	raw_spin_rq_unlock_irq(rq);
4277 
4278 	return nr_balanced;
4279 }
4280 
4281 static void bypass_lb_node(struct scx_sched *sch, int node)
4282 {
4283 	const struct cpumask *node_mask = cpumask_of_node(node);
4284 	struct cpumask *donee_mask = scx_bypass_lb_donee_cpumask;
4285 	struct cpumask *resched_mask = scx_bypass_lb_resched_cpumask;
4286 	u32 nr_tasks = 0, nr_cpus = 0, nr_balanced = 0;
4287 	u32 nr_target, nr_donor_target;
4288 	u32 before_min = U32_MAX, before_max = 0;
4289 	u32 after_min = U32_MAX, after_max = 0;
4290 	int cpu;
4291 
4292 	/* count the target tasks and CPUs */
4293 	for_each_cpu_and(cpu, cpu_online_mask, node_mask) {
4294 		u32 nr = READ_ONCE(cpu_rq(cpu)->scx.bypass_dsq.nr);
4295 
4296 		nr_tasks += nr;
4297 		nr_cpus++;
4298 
4299 		before_min = min(nr, before_min);
4300 		before_max = max(nr, before_max);
4301 	}
4302 
4303 	if (!nr_cpus)
4304 		return;
4305 
4306 	/*
4307 	 * We don't want CPUs to have more than $nr_donor_target tasks and
4308 	 * balancing to fill donee CPUs upto $nr_target. Once targets are
4309 	 * calculated, find the donee CPUs.
4310 	 */
4311 	nr_target = DIV_ROUND_UP(nr_tasks, nr_cpus);
4312 	nr_donor_target = DIV_ROUND_UP(nr_target * SCX_BYPASS_LB_DONOR_PCT, 100);
4313 
4314 	cpumask_clear(donee_mask);
4315 	for_each_cpu_and(cpu, cpu_online_mask, node_mask) {
4316 		if (READ_ONCE(cpu_rq(cpu)->scx.bypass_dsq.nr) < nr_target)
4317 			cpumask_set_cpu(cpu, donee_mask);
4318 	}
4319 
4320 	/* iterate !donee CPUs and see if they should be offloaded */
4321 	cpumask_clear(resched_mask);
4322 	for_each_cpu_and(cpu, cpu_online_mask, node_mask) {
4323 		struct rq *rq = cpu_rq(cpu);
4324 		struct scx_dispatch_q *donor_dsq = &rq->scx.bypass_dsq;
4325 
4326 		if (cpumask_empty(donee_mask))
4327 			break;
4328 		if (cpumask_test_cpu(cpu, donee_mask))
4329 			continue;
4330 		if (READ_ONCE(donor_dsq->nr) <= nr_donor_target)
4331 			continue;
4332 
4333 		nr_balanced += bypass_lb_cpu(sch, rq, donee_mask, resched_mask,
4334 					     nr_donor_target, nr_target);
4335 	}
4336 
4337 	for_each_cpu(cpu, resched_mask)
4338 		resched_cpu(cpu);
4339 
4340 	for_each_cpu_and(cpu, cpu_online_mask, node_mask) {
4341 		u32 nr = READ_ONCE(cpu_rq(cpu)->scx.bypass_dsq.nr);
4342 
4343 		after_min = min(nr, after_min);
4344 		after_max = max(nr, after_max);
4345 
4346 	}
4347 
4348 	trace_sched_ext_bypass_lb(node, nr_cpus, nr_tasks, nr_balanced,
4349 				  before_min, before_max, after_min, after_max);
4350 }
4351 
4352 /*
4353  * In bypass mode, all tasks are put on the per-CPU bypass DSQs. If the machine
4354  * is over-saturated and the BPF scheduler skewed tasks into few CPUs, some
4355  * bypass DSQs can be overloaded. If there are enough tasks to saturate other
4356  * lightly loaded CPUs, such imbalance can lead to very high execution latency
4357  * on the overloaded CPUs and thus to hung tasks and RCU stalls. To avoid such
4358  * outcomes, a simple load balancing mechanism is implemented by the following
4359  * timer which runs periodically while bypass mode is in effect.
4360  */
4361 static void scx_bypass_lb_timerfn(struct timer_list *timer)
4362 {
4363 	struct scx_sched *sch;
4364 	int node;
4365 	u32 intv_us;
4366 
4367 	sch = rcu_dereference_all(scx_root);
4368 	if (unlikely(!sch) || !READ_ONCE(scx_bypass_depth))
4369 		return;
4370 
4371 	for_each_node_with_cpus(node)
4372 		bypass_lb_node(sch, node);
4373 
4374 	intv_us = READ_ONCE(scx_bypass_lb_intv_us);
4375 	if (intv_us)
4376 		mod_timer(timer, jiffies + usecs_to_jiffies(intv_us));
4377 }
4378 
4379 static DEFINE_TIMER(scx_bypass_lb_timer, scx_bypass_lb_timerfn);
4380 
4381 /**
4382  * scx_bypass - [Un]bypass scx_ops and guarantee forward progress
4383  * @bypass: true for bypass, false for unbypass
4384  *
4385  * Bypassing guarantees that all runnable tasks make forward progress without
4386  * trusting the BPF scheduler. We can't grab any mutexes or rwsems as they might
4387  * be held by tasks that the BPF scheduler is forgetting to run, which
4388  * unfortunately also excludes toggling the static branches.
4389  *
4390  * Let's work around by overriding a couple ops and modifying behaviors based on
4391  * the DISABLING state and then cycling the queued tasks through dequeue/enqueue
4392  * to force global FIFO scheduling.
4393  *
4394  * - ops.select_cpu() is ignored and the default select_cpu() is used.
4395  *
4396  * - ops.enqueue() is ignored and tasks are queued in simple global FIFO order.
4397  *   %SCX_OPS_ENQ_LAST is also ignored.
4398  *
4399  * - ops.dispatch() is ignored.
4400  *
4401  * - balance_one() does not set %SCX_RQ_BAL_KEEP on non-zero slice as slice
4402  *   can't be trusted. Whenever a tick triggers, the running task is rotated to
4403  *   the tail of the queue with core_sched_at touched.
4404  *
4405  * - pick_next_task() suppresses zero slice warning.
4406  *
4407  * - scx_kick_cpu() is disabled to avoid irq_work malfunction during PM
4408  *   operations.
4409  *
4410  * - scx_prio_less() reverts to the default core_sched_at order.
4411  */
4412 static void scx_bypass(bool bypass)
4413 {
4414 	static DEFINE_RAW_SPINLOCK(bypass_lock);
4415 	static unsigned long bypass_timestamp;
4416 	struct scx_sched *sch;
4417 	unsigned long flags;
4418 	int cpu;
4419 
4420 	raw_spin_lock_irqsave(&bypass_lock, flags);
4421 	sch = rcu_dereference_bh(scx_root);
4422 
4423 	if (bypass) {
4424 		u32 intv_us;
4425 
4426 		WRITE_ONCE(scx_bypass_depth, scx_bypass_depth + 1);
4427 		WARN_ON_ONCE(scx_bypass_depth <= 0);
4428 		if (scx_bypass_depth != 1)
4429 			goto unlock;
4430 		WRITE_ONCE(scx_slice_dfl, READ_ONCE(scx_slice_bypass_us) * NSEC_PER_USEC);
4431 		bypass_timestamp = ktime_get_ns();
4432 		if (sch)
4433 			scx_add_event(sch, SCX_EV_BYPASS_ACTIVATE, 1);
4434 
4435 		intv_us = READ_ONCE(scx_bypass_lb_intv_us);
4436 		if (intv_us && !timer_pending(&scx_bypass_lb_timer)) {
4437 			scx_bypass_lb_timer.expires =
4438 				jiffies + usecs_to_jiffies(intv_us);
4439 			add_timer_global(&scx_bypass_lb_timer);
4440 		}
4441 	} else {
4442 		WRITE_ONCE(scx_bypass_depth, scx_bypass_depth - 1);
4443 		WARN_ON_ONCE(scx_bypass_depth < 0);
4444 		if (scx_bypass_depth != 0)
4445 			goto unlock;
4446 		WRITE_ONCE(scx_slice_dfl, SCX_SLICE_DFL);
4447 		if (sch)
4448 			scx_add_event(sch, SCX_EV_BYPASS_DURATION,
4449 				      ktime_get_ns() - bypass_timestamp);
4450 	}
4451 
4452 	/*
4453 	 * No task property is changing. We just need to make sure all currently
4454 	 * queued tasks are re-queued according to the new scx_rq_bypassing()
4455 	 * state. As an optimization, walk each rq's runnable_list instead of
4456 	 * the scx_tasks list.
4457 	 *
4458 	 * This function can't trust the scheduler and thus can't use
4459 	 * cpus_read_lock(). Walk all possible CPUs instead of online.
4460 	 */
4461 	for_each_possible_cpu(cpu) {
4462 		struct rq *rq = cpu_rq(cpu);
4463 		struct task_struct *p, *n;
4464 
4465 		raw_spin_rq_lock(rq);
4466 
4467 		if (bypass) {
4468 			WARN_ON_ONCE(rq->scx.flags & SCX_RQ_BYPASSING);
4469 			rq->scx.flags |= SCX_RQ_BYPASSING;
4470 		} else {
4471 			WARN_ON_ONCE(!(rq->scx.flags & SCX_RQ_BYPASSING));
4472 			rq->scx.flags &= ~SCX_RQ_BYPASSING;
4473 		}
4474 
4475 		/*
4476 		 * We need to guarantee that no tasks are on the BPF scheduler
4477 		 * while bypassing. Either we see enabled or the enable path
4478 		 * sees scx_rq_bypassing() before moving tasks to SCX.
4479 		 */
4480 		if (!scx_enabled()) {
4481 			raw_spin_rq_unlock(rq);
4482 			continue;
4483 		}
4484 
4485 		/*
4486 		 * The use of list_for_each_entry_safe_reverse() is required
4487 		 * because each task is going to be removed from and added back
4488 		 * to the runnable_list during iteration. Because they're added
4489 		 * to the tail of the list, safe reverse iteration can still
4490 		 * visit all nodes.
4491 		 */
4492 		list_for_each_entry_safe_reverse(p, n, &rq->scx.runnable_list,
4493 						 scx.runnable_node) {
4494 			/* cycling deq/enq is enough, see the function comment */
4495 			scoped_guard (sched_change, p, DEQUEUE_SAVE | DEQUEUE_MOVE) {
4496 				/* nothing */ ;
4497 			}
4498 		}
4499 
4500 		/* resched to restore ticks and idle state */
4501 		if (cpu_online(cpu) || cpu == smp_processor_id())
4502 			resched_curr(rq);
4503 
4504 		raw_spin_rq_unlock(rq);
4505 	}
4506 
4507 unlock:
4508 	raw_spin_unlock_irqrestore(&bypass_lock, flags);
4509 }
4510 
4511 static void free_exit_info(struct scx_exit_info *ei)
4512 {
4513 	kvfree(ei->dump);
4514 	kfree(ei->msg);
4515 	kfree(ei->bt);
4516 	kfree(ei);
4517 }
4518 
4519 static struct scx_exit_info *alloc_exit_info(size_t exit_dump_len)
4520 {
4521 	struct scx_exit_info *ei;
4522 
4523 	ei = kzalloc_obj(*ei);
4524 	if (!ei)
4525 		return NULL;
4526 
4527 	ei->bt = kzalloc_objs(ei->bt[0], SCX_EXIT_BT_LEN);
4528 	ei->msg = kzalloc(SCX_EXIT_MSG_LEN, GFP_KERNEL);
4529 	ei->dump = kvzalloc(exit_dump_len, GFP_KERNEL);
4530 
4531 	if (!ei->bt || !ei->msg || !ei->dump) {
4532 		free_exit_info(ei);
4533 		return NULL;
4534 	}
4535 
4536 	return ei;
4537 }
4538 
4539 static const char *scx_exit_reason(enum scx_exit_kind kind)
4540 {
4541 	switch (kind) {
4542 	case SCX_EXIT_UNREG:
4543 		return "unregistered from user space";
4544 	case SCX_EXIT_UNREG_BPF:
4545 		return "unregistered from BPF";
4546 	case SCX_EXIT_UNREG_KERN:
4547 		return "unregistered from the main kernel";
4548 	case SCX_EXIT_SYSRQ:
4549 		return "disabled by sysrq-S";
4550 	case SCX_EXIT_PARENT:
4551 		return "parent exiting";
4552 	case SCX_EXIT_ERROR:
4553 		return "runtime error";
4554 	case SCX_EXIT_ERROR_BPF:
4555 		return "scx_bpf_error";
4556 	case SCX_EXIT_ERROR_STALL:
4557 		return "runnable task stall";
4558 	default:
4559 		return "<UNKNOWN>";
4560 	}
4561 }
4562 
4563 static void free_kick_syncs(void)
4564 {
4565 	int cpu;
4566 
4567 	for_each_possible_cpu(cpu) {
4568 		struct scx_kick_syncs **ksyncs = per_cpu_ptr(&scx_kick_syncs, cpu);
4569 		struct scx_kick_syncs *to_free;
4570 
4571 		to_free = rcu_replace_pointer(*ksyncs, NULL, true);
4572 		if (to_free)
4573 			kvfree_rcu(to_free, rcu);
4574 	}
4575 }
4576 
4577 #ifdef CONFIG_EXT_SUB_SCHED
4578 static DECLARE_WAIT_QUEUE_HEAD(scx_unlink_waitq);
4579 
4580 static void drain_descendants(struct scx_sched *sch)
4581 {
4582 	/*
4583 	 * Child scheds that finished the critical part of disabling will take
4584 	 * themselves off @sch->children. Wait for it to drain. As propagation
4585 	 * is recursive, empty @sch->children means that all proper descendant
4586 	 * scheds reached unlinking stage.
4587 	 */
4588 	wait_event(scx_unlink_waitq, list_empty(&sch->children));
4589 }
4590 
4591 static void scx_sub_disable(struct scx_sched *sch)
4592 {
4593 	struct scx_sched *parent = scx_parent(sch);
4594 
4595 	drain_descendants(sch);
4596 
4597 	mutex_lock(&scx_enable_mutex);
4598 	percpu_down_write(&scx_fork_rwsem);
4599 	scx_cgroup_lock();
4600 
4601 	set_cgroup_sched(sch_cgroup(sch), parent);
4602 
4603 	/* TODO - perform actual disabling here */
4604 
4605 	scx_cgroup_unlock();
4606 	percpu_up_write(&scx_fork_rwsem);
4607 
4608 	raw_spin_lock_irq(&scx_sched_lock);
4609 	list_del_init(&sch->sibling);
4610 	list_del_rcu(&sch->all);
4611 	raw_spin_unlock_irq(&scx_sched_lock);
4612 
4613 	mutex_unlock(&scx_enable_mutex);
4614 
4615 	/*
4616 	 * @sch is now unlinked from the parent's children list. Notify and call
4617 	 * ops.sub_detach/exit(). Note that ops.sub_detach/exit() must be called
4618 	 * after unlinking and releasing all locks. See scx_claim_exit().
4619 	 */
4620 	wake_up_all(&scx_unlink_waitq);
4621 
4622 	if (sch->ops.sub_detach && sch->sub_attached) {
4623 		struct scx_sub_detach_args sub_detach_args = {
4624 			.ops = &sch->ops,
4625 			.cgroup_path = sch->cgrp_path,
4626 		};
4627 		SCX_CALL_OP(parent, SCX_KF_UNLOCKED, sub_detach, NULL,
4628 			    &sub_detach_args);
4629 	}
4630 
4631 	if (sch->ops.exit)
4632 		SCX_CALL_OP(sch, SCX_KF_UNLOCKED, exit, NULL, sch->exit_info);
4633 	kobject_del(&sch->kobj);
4634 }
4635 #else	/* CONFIG_EXT_SUB_SCHED */
4636 static void drain_descendants(struct scx_sched *sch) { }
4637 static void scx_sub_disable(struct scx_sched *sch) { }
4638 #endif	/* CONFIG_EXT_SUB_SCHED */
4639 
4640 static void scx_root_disable(struct scx_sched *sch)
4641 {
4642 	struct scx_exit_info *ei = sch->exit_info;
4643 	struct scx_task_iter sti;
4644 	struct task_struct *p;
4645 	int cpu;
4646 
4647 	/* guarantee forward progress and wait for descendants to be disabled */
4648 	scx_bypass(true);
4649 	WRITE_ONCE(scx_aborting, false);
4650 	drain_descendants(sch);
4651 
4652 	switch (scx_set_enable_state(SCX_DISABLING)) {
4653 	case SCX_DISABLING:
4654 		WARN_ONCE(true, "sched_ext: duplicate disabling instance?");
4655 		break;
4656 	case SCX_DISABLED:
4657 		pr_warn("sched_ext: ops error detected without ops (%s)\n",
4658 			sch->exit_info->msg);
4659 		WARN_ON_ONCE(scx_set_enable_state(SCX_DISABLED) != SCX_DISABLING);
4660 		goto done;
4661 	default:
4662 		break;
4663 	}
4664 
4665 	/*
4666 	 * Here, every runnable task is guaranteed to make forward progress and
4667 	 * we can safely use blocking synchronization constructs. Actually
4668 	 * disable ops.
4669 	 */
4670 	mutex_lock(&scx_enable_mutex);
4671 
4672 	static_branch_disable(&__scx_switched_all);
4673 	WRITE_ONCE(scx_switching_all, false);
4674 
4675 	/*
4676 	 * Shut down cgroup support before tasks so that the cgroup attach path
4677 	 * doesn't race against scx_exit_task().
4678 	 */
4679 	scx_cgroup_lock();
4680 	scx_cgroup_exit(sch);
4681 	scx_cgroup_unlock();
4682 
4683 	/*
4684 	 * The BPF scheduler is going away. All tasks including %TASK_DEAD ones
4685 	 * must be switched out and exited synchronously.
4686 	 */
4687 	percpu_down_write(&scx_fork_rwsem);
4688 
4689 	scx_init_task_enabled = false;
4690 
4691 	scx_task_iter_start(&sti, NULL);
4692 	while ((p = scx_task_iter_next_locked(&sti))) {
4693 		unsigned int queue_flags = DEQUEUE_SAVE | DEQUEUE_MOVE | DEQUEUE_NOCLOCK;
4694 		const struct sched_class *old_class = p->sched_class;
4695 		const struct sched_class *new_class = scx_setscheduler_class(p);
4696 
4697 		update_rq_clock(task_rq(p));
4698 
4699 		if (old_class != new_class)
4700 			queue_flags |= DEQUEUE_CLASS;
4701 
4702 		scoped_guard (sched_change, p, queue_flags) {
4703 			p->sched_class = new_class;
4704 		}
4705 
4706 		scx_exit_task(p);
4707 	}
4708 	scx_task_iter_stop(&sti);
4709 
4710 	scx_cgroup_lock();
4711 	set_cgroup_sched(sch_cgroup(sch), NULL);
4712 	scx_cgroup_unlock();
4713 
4714 	percpu_up_write(&scx_fork_rwsem);
4715 
4716 	/*
4717 	 * Invalidate all the rq clocks to prevent getting outdated
4718 	 * rq clocks from a previous scx scheduler.
4719 	 */
4720 	for_each_possible_cpu(cpu) {
4721 		struct rq *rq = cpu_rq(cpu);
4722 		scx_rq_clock_invalidate(rq);
4723 	}
4724 
4725 	/* no task is on scx, turn off all the switches and flush in-progress calls */
4726 	static_branch_disable(&__scx_enabled);
4727 	bitmap_zero(sch->has_op, SCX_OPI_END);
4728 	scx_idle_disable();
4729 	synchronize_rcu();
4730 
4731 	if (ei->kind >= SCX_EXIT_ERROR) {
4732 		pr_err("sched_ext: BPF scheduler \"%s\" disabled (%s)\n",
4733 		       sch->ops.name, ei->reason);
4734 
4735 		if (ei->msg[0] != '\0')
4736 			pr_err("sched_ext: %s: %s\n", sch->ops.name, ei->msg);
4737 #ifdef CONFIG_STACKTRACE
4738 		stack_trace_print(ei->bt, ei->bt_len, 2);
4739 #endif
4740 	} else {
4741 		pr_info("sched_ext: BPF scheduler \"%s\" disabled (%s)\n",
4742 			sch->ops.name, ei->reason);
4743 	}
4744 
4745 	if (sch->ops.exit)
4746 		SCX_CALL_OP(sch, SCX_KF_UNLOCKED, exit, NULL, ei);
4747 
4748 	cancel_delayed_work_sync(&scx_watchdog_work);
4749 
4750 	raw_spin_lock_irq(&scx_sched_lock);
4751 	list_del_rcu(&sch->all);
4752 	raw_spin_unlock_irq(&scx_sched_lock);
4753 
4754 	/*
4755 	 * scx_root clearing must be inside cpus_read_lock(). See
4756 	 * handle_hotplug().
4757 	 */
4758 	cpus_read_lock();
4759 	RCU_INIT_POINTER(scx_root, NULL);
4760 	cpus_read_unlock();
4761 
4762 	/*
4763 	 * Delete the kobject from the hierarchy synchronously. Otherwise, sysfs
4764 	 * could observe an object of the same name still in the hierarchy when
4765 	 * the next scheduler is loaded.
4766 	 */
4767 	kobject_del(&sch->kobj);
4768 
4769 	free_percpu(scx_dsp_ctx);
4770 	scx_dsp_ctx = NULL;
4771 	scx_dsp_max_batch = 0;
4772 	free_kick_syncs();
4773 
4774 	if (scx_bypassed_for_enable) {
4775 		scx_bypassed_for_enable = false;
4776 		scx_bypass(false);
4777 	}
4778 
4779 	mutex_unlock(&scx_enable_mutex);
4780 
4781 	WARN_ON_ONCE(scx_set_enable_state(SCX_DISABLED) != SCX_DISABLING);
4782 done:
4783 	scx_bypass(false);
4784 }
4785 
4786 /*
4787  * Claim the exit on @sch. The caller must ensure that the helper kthread work
4788  * is kicked before the current task can be preempted. Once exit_kind is
4789  * claimed, scx_error() can no longer trigger, so if the current task gets
4790  * preempted and the BPF scheduler fails to schedule it back, the helper work
4791  * will never be kicked and the whole system can wedge.
4792  */
4793 static bool scx_claim_exit(struct scx_sched *sch, enum scx_exit_kind kind)
4794 {
4795 	int none = SCX_EXIT_NONE;
4796 
4797 	lockdep_assert_preemption_disabled();
4798 
4799 	if (WARN_ON_ONCE(kind == SCX_EXIT_NONE || kind == SCX_EXIT_DONE))
4800 		kind = SCX_EXIT_ERROR;
4801 
4802 	if (!atomic_try_cmpxchg(&sch->exit_kind, &none, kind))
4803 		return false;
4804 
4805 	/*
4806 	 * Some CPUs may be trapped in the dispatch paths. Set the aborting
4807 	 * flag to break potential live-lock scenarios, ensuring we can
4808 	 * successfully reach scx_bypass().
4809 	 */
4810 	WRITE_ONCE(scx_aborting, true);
4811 
4812 	/*
4813 	 * Propagate exits to descendants immediately. Each has a dedicated
4814 	 * helper kthread and can run in parallel. While most of disabling is
4815 	 * serialized, running them in separate threads allows parallelizing
4816 	 * ops.exit(), which can take arbitrarily long prolonging bypass mode.
4817 	 *
4818 	 * This doesn't cause recursions as propagation only takes place for
4819 	 * non-propagation exits.
4820 	 */
4821 	if (kind != SCX_EXIT_PARENT) {
4822 		scoped_guard (raw_spinlock_irqsave, &scx_sched_lock) {
4823 			struct scx_sched *pos;
4824 			scx_for_each_descendant_pre(pos, sch)
4825 				scx_disable(pos, SCX_EXIT_PARENT);
4826 		}
4827 	}
4828 
4829 	return true;
4830 }
4831 
4832 static void scx_disable_workfn(struct kthread_work *work)
4833 {
4834 	struct scx_sched *sch = container_of(work, struct scx_sched, disable_work);
4835 	struct scx_exit_info *ei = sch->exit_info;
4836 	int kind;
4837 
4838 	kind = atomic_read(&sch->exit_kind);
4839 	while (true) {
4840 		if (kind == SCX_EXIT_DONE)	/* already disabled? */
4841 			return;
4842 		WARN_ON_ONCE(kind == SCX_EXIT_NONE);
4843 		if (atomic_try_cmpxchg(&sch->exit_kind, &kind, SCX_EXIT_DONE))
4844 			break;
4845 	}
4846 	ei->kind = kind;
4847 	ei->reason = scx_exit_reason(ei->kind);
4848 
4849 	if (scx_parent(sch))
4850 		scx_sub_disable(sch);
4851 	else
4852 		scx_root_disable(sch);
4853 }
4854 
4855 static void scx_disable(struct scx_sched *sch, enum scx_exit_kind kind)
4856 {
4857 	guard(preempt)();
4858 	if (scx_claim_exit(sch, kind))
4859 		kthread_queue_work(sch->helper, &sch->disable_work);
4860 }
4861 
4862 static void dump_newline(struct seq_buf *s)
4863 {
4864 	trace_sched_ext_dump("");
4865 
4866 	/* @s may be zero sized and seq_buf triggers WARN if so */
4867 	if (s->size)
4868 		seq_buf_putc(s, '\n');
4869 }
4870 
4871 static __printf(2, 3) void dump_line(struct seq_buf *s, const char *fmt, ...)
4872 {
4873 	va_list args;
4874 
4875 #ifdef CONFIG_TRACEPOINTS
4876 	if (trace_sched_ext_dump_enabled()) {
4877 		/* protected by scx_dump_state()::dump_lock */
4878 		static char line_buf[SCX_EXIT_MSG_LEN];
4879 
4880 		va_start(args, fmt);
4881 		vscnprintf(line_buf, sizeof(line_buf), fmt, args);
4882 		va_end(args);
4883 
4884 		trace_sched_ext_dump(line_buf);
4885 	}
4886 #endif
4887 	/* @s may be zero sized and seq_buf triggers WARN if so */
4888 	if (s->size) {
4889 		va_start(args, fmt);
4890 		seq_buf_vprintf(s, fmt, args);
4891 		va_end(args);
4892 
4893 		seq_buf_putc(s, '\n');
4894 	}
4895 }
4896 
4897 static void dump_stack_trace(struct seq_buf *s, const char *prefix,
4898 			     const unsigned long *bt, unsigned int len)
4899 {
4900 	unsigned int i;
4901 
4902 	for (i = 0; i < len; i++)
4903 		dump_line(s, "%s%pS", prefix, (void *)bt[i]);
4904 }
4905 
4906 static void ops_dump_init(struct seq_buf *s, const char *prefix)
4907 {
4908 	struct scx_dump_data *dd = &scx_dump_data;
4909 
4910 	lockdep_assert_irqs_disabled();
4911 
4912 	dd->cpu = smp_processor_id();		/* allow scx_bpf_dump() */
4913 	dd->first = true;
4914 	dd->cursor = 0;
4915 	dd->s = s;
4916 	dd->prefix = prefix;
4917 }
4918 
4919 static void ops_dump_flush(void)
4920 {
4921 	struct scx_dump_data *dd = &scx_dump_data;
4922 	char *line = dd->buf.line;
4923 
4924 	if (!dd->cursor)
4925 		return;
4926 
4927 	/*
4928 	 * There's something to flush and this is the first line. Insert a blank
4929 	 * line to distinguish ops dump.
4930 	 */
4931 	if (dd->first) {
4932 		dump_newline(dd->s);
4933 		dd->first = false;
4934 	}
4935 
4936 	/*
4937 	 * There may be multiple lines in $line. Scan and emit each line
4938 	 * separately.
4939 	 */
4940 	while (true) {
4941 		char *end = line;
4942 		char c;
4943 
4944 		while (*end != '\n' && *end != '\0')
4945 			end++;
4946 
4947 		/*
4948 		 * If $line overflowed, it may not have newline at the end.
4949 		 * Always emit with a newline.
4950 		 */
4951 		c = *end;
4952 		*end = '\0';
4953 		dump_line(dd->s, "%s%s", dd->prefix, line);
4954 		if (c == '\0')
4955 			break;
4956 
4957 		/* move to the next line */
4958 		end++;
4959 		if (*end == '\0')
4960 			break;
4961 		line = end;
4962 	}
4963 
4964 	dd->cursor = 0;
4965 }
4966 
4967 static void ops_dump_exit(void)
4968 {
4969 	ops_dump_flush();
4970 	scx_dump_data.cpu = -1;
4971 }
4972 
4973 static void scx_dump_task(struct seq_buf *s, struct scx_dump_ctx *dctx,
4974 			  struct task_struct *p, char marker)
4975 {
4976 	static unsigned long bt[SCX_EXIT_BT_LEN];
4977 	struct scx_sched *sch = scx_root;
4978 	char dsq_id_buf[19] = "(n/a)";
4979 	unsigned long ops_state = atomic_long_read(&p->scx.ops_state);
4980 	unsigned int bt_len = 0;
4981 
4982 	if (p->scx.dsq)
4983 		scnprintf(dsq_id_buf, sizeof(dsq_id_buf), "0x%llx",
4984 			  (unsigned long long)p->scx.dsq->id);
4985 
4986 	dump_newline(s);
4987 	dump_line(s, " %c%c %s[%d] %+ldms",
4988 		  marker, task_state_to_char(p), p->comm, p->pid,
4989 		  jiffies_delta_msecs(p->scx.runnable_at, dctx->at_jiffies));
4990 	dump_line(s, "      scx_state/flags=%u/0x%x dsq_flags=0x%x ops_state/qseq=%lu/%lu",
4991 		  scx_get_task_state(p), p->scx.flags & ~SCX_TASK_STATE_MASK,
4992 		  p->scx.dsq_flags, ops_state & SCX_OPSS_STATE_MASK,
4993 		  ops_state >> SCX_OPSS_QSEQ_SHIFT);
4994 	dump_line(s, "      sticky/holding_cpu=%d/%d dsq_id=%s",
4995 		  p->scx.sticky_cpu, p->scx.holding_cpu, dsq_id_buf);
4996 	dump_line(s, "      dsq_vtime=%llu slice=%llu weight=%u",
4997 		  p->scx.dsq_vtime, p->scx.slice, p->scx.weight);
4998 	dump_line(s, "      cpus=%*pb no_mig=%u", cpumask_pr_args(p->cpus_ptr),
4999 		  p->migration_disabled);
5000 
5001 	if (SCX_HAS_OP(sch, dump_task)) {
5002 		ops_dump_init(s, "    ");
5003 		SCX_CALL_OP(sch, SCX_KF_REST, dump_task, NULL, dctx, p);
5004 		ops_dump_exit();
5005 	}
5006 
5007 #ifdef CONFIG_STACKTRACE
5008 	bt_len = stack_trace_save_tsk(p, bt, SCX_EXIT_BT_LEN, 1);
5009 #endif
5010 	if (bt_len) {
5011 		dump_newline(s);
5012 		dump_stack_trace(s, "    ", bt, bt_len);
5013 	}
5014 }
5015 
5016 static void scx_dump_state(struct scx_exit_info *ei, size_t dump_len)
5017 {
5018 	static DEFINE_SPINLOCK(dump_lock);
5019 	static const char trunc_marker[] = "\n\n~~~~ TRUNCATED ~~~~\n";
5020 	struct scx_sched *sch = scx_root;
5021 	struct scx_dump_ctx dctx = {
5022 		.kind = ei->kind,
5023 		.exit_code = ei->exit_code,
5024 		.reason = ei->reason,
5025 		.at_ns = ktime_get_ns(),
5026 		.at_jiffies = jiffies,
5027 	};
5028 	struct seq_buf s;
5029 	struct scx_event_stats events;
5030 	unsigned long flags;
5031 	char *buf;
5032 	int cpu;
5033 
5034 	spin_lock_irqsave(&dump_lock, flags);
5035 
5036 	seq_buf_init(&s, ei->dump, dump_len);
5037 
5038 	if (ei->kind == SCX_EXIT_NONE) {
5039 		dump_line(&s, "Debug dump triggered by %s", ei->reason);
5040 	} else {
5041 		dump_line(&s, "%s[%d] triggered exit kind %d:",
5042 			  current->comm, current->pid, ei->kind);
5043 		dump_line(&s, "  %s (%s)", ei->reason, ei->msg);
5044 		dump_newline(&s);
5045 		dump_line(&s, "Backtrace:");
5046 		dump_stack_trace(&s, "  ", ei->bt, ei->bt_len);
5047 	}
5048 
5049 	if (SCX_HAS_OP(sch, dump)) {
5050 		ops_dump_init(&s, "");
5051 		SCX_CALL_OP(sch, SCX_KF_UNLOCKED, dump, NULL, &dctx);
5052 		ops_dump_exit();
5053 	}
5054 
5055 	dump_newline(&s);
5056 	dump_line(&s, "CPU states");
5057 	dump_line(&s, "----------");
5058 
5059 	for_each_possible_cpu(cpu) {
5060 		struct rq *rq = cpu_rq(cpu);
5061 		struct rq_flags rf;
5062 		struct task_struct *p;
5063 		struct seq_buf ns;
5064 		size_t avail, used;
5065 		bool idle;
5066 
5067 		rq_lock_irqsave(rq, &rf);
5068 
5069 		idle = list_empty(&rq->scx.runnable_list) &&
5070 			rq->curr->sched_class == &idle_sched_class;
5071 
5072 		if (idle && !SCX_HAS_OP(sch, dump_cpu))
5073 			goto next;
5074 
5075 		/*
5076 		 * We don't yet know whether ops.dump_cpu() will produce output
5077 		 * and we may want to skip the default CPU dump if it doesn't.
5078 		 * Use a nested seq_buf to generate the standard dump so that we
5079 		 * can decide whether to commit later.
5080 		 */
5081 		avail = seq_buf_get_buf(&s, &buf);
5082 		seq_buf_init(&ns, buf, avail);
5083 
5084 		dump_newline(&ns);
5085 		dump_line(&ns, "CPU %-4d: nr_run=%u flags=0x%x cpu_rel=%d ops_qseq=%lu ksync=%lu",
5086 			  cpu, rq->scx.nr_running, rq->scx.flags,
5087 			  rq->scx.cpu_released, rq->scx.ops_qseq,
5088 			  rq->scx.kick_sync);
5089 		dump_line(&ns, "          curr=%s[%d] class=%ps",
5090 			  rq->curr->comm, rq->curr->pid,
5091 			  rq->curr->sched_class);
5092 		if (!cpumask_empty(rq->scx.cpus_to_kick))
5093 			dump_line(&ns, "  cpus_to_kick   : %*pb",
5094 				  cpumask_pr_args(rq->scx.cpus_to_kick));
5095 		if (!cpumask_empty(rq->scx.cpus_to_kick_if_idle))
5096 			dump_line(&ns, "  idle_to_kick   : %*pb",
5097 				  cpumask_pr_args(rq->scx.cpus_to_kick_if_idle));
5098 		if (!cpumask_empty(rq->scx.cpus_to_preempt))
5099 			dump_line(&ns, "  cpus_to_preempt: %*pb",
5100 				  cpumask_pr_args(rq->scx.cpus_to_preempt));
5101 		if (!cpumask_empty(rq->scx.cpus_to_wait))
5102 			dump_line(&ns, "  cpus_to_wait   : %*pb",
5103 				  cpumask_pr_args(rq->scx.cpus_to_wait));
5104 
5105 		used = seq_buf_used(&ns);
5106 		if (SCX_HAS_OP(sch, dump_cpu)) {
5107 			ops_dump_init(&ns, "  ");
5108 			SCX_CALL_OP(sch, SCX_KF_REST, dump_cpu, NULL,
5109 				    &dctx, cpu, idle);
5110 			ops_dump_exit();
5111 		}
5112 
5113 		/*
5114 		 * If idle && nothing generated by ops.dump_cpu(), there's
5115 		 * nothing interesting. Skip.
5116 		 */
5117 		if (idle && used == seq_buf_used(&ns))
5118 			goto next;
5119 
5120 		/*
5121 		 * $s may already have overflowed when $ns was created. If so,
5122 		 * calling commit on it will trigger BUG.
5123 		 */
5124 		if (avail) {
5125 			seq_buf_commit(&s, seq_buf_used(&ns));
5126 			if (seq_buf_has_overflowed(&ns))
5127 				seq_buf_set_overflow(&s);
5128 		}
5129 
5130 		if (rq->curr->sched_class == &ext_sched_class)
5131 			scx_dump_task(&s, &dctx, rq->curr, '*');
5132 
5133 		list_for_each_entry(p, &rq->scx.runnable_list, scx.runnable_node)
5134 			scx_dump_task(&s, &dctx, p, ' ');
5135 	next:
5136 		rq_unlock_irqrestore(rq, &rf);
5137 	}
5138 
5139 	dump_newline(&s);
5140 	dump_line(&s, "Event counters");
5141 	dump_line(&s, "--------------");
5142 
5143 	scx_read_events(sch, &events);
5144 	scx_dump_event(s, &events, SCX_EV_SELECT_CPU_FALLBACK);
5145 	scx_dump_event(s, &events, SCX_EV_DISPATCH_LOCAL_DSQ_OFFLINE);
5146 	scx_dump_event(s, &events, SCX_EV_DISPATCH_KEEP_LAST);
5147 	scx_dump_event(s, &events, SCX_EV_ENQ_SKIP_EXITING);
5148 	scx_dump_event(s, &events, SCX_EV_ENQ_SKIP_MIGRATION_DISABLED);
5149 	scx_dump_event(s, &events, SCX_EV_REFILL_SLICE_DFL);
5150 	scx_dump_event(s, &events, SCX_EV_BYPASS_DURATION);
5151 	scx_dump_event(s, &events, SCX_EV_BYPASS_DISPATCH);
5152 	scx_dump_event(s, &events, SCX_EV_BYPASS_ACTIVATE);
5153 
5154 	if (seq_buf_has_overflowed(&s) && dump_len >= sizeof(trunc_marker))
5155 		memcpy(ei->dump + dump_len - sizeof(trunc_marker),
5156 		       trunc_marker, sizeof(trunc_marker));
5157 
5158 	spin_unlock_irqrestore(&dump_lock, flags);
5159 }
5160 
5161 static void scx_error_irq_workfn(struct irq_work *irq_work)
5162 {
5163 	struct scx_sched *sch = container_of(irq_work, struct scx_sched, error_irq_work);
5164 	struct scx_exit_info *ei = sch->exit_info;
5165 
5166 	if (ei->kind >= SCX_EXIT_ERROR)
5167 		scx_dump_state(ei, sch->ops.exit_dump_len);
5168 
5169 	kthread_queue_work(sch->helper, &sch->disable_work);
5170 }
5171 
5172 static bool scx_vexit(struct scx_sched *sch,
5173 		      enum scx_exit_kind kind, s64 exit_code,
5174 		      const char *fmt, va_list args)
5175 {
5176 	struct scx_exit_info *ei = sch->exit_info;
5177 
5178 	guard(preempt)();
5179 
5180 	if (!scx_claim_exit(sch, kind))
5181 		return false;
5182 
5183 	ei->exit_code = exit_code;
5184 #ifdef CONFIG_STACKTRACE
5185 	if (kind >= SCX_EXIT_ERROR)
5186 		ei->bt_len = stack_trace_save(ei->bt, SCX_EXIT_BT_LEN, 1);
5187 #endif
5188 	vscnprintf(ei->msg, SCX_EXIT_MSG_LEN, fmt, args);
5189 
5190 	/*
5191 	 * Set ei->kind and ->reason for scx_dump_state(). They'll be set again
5192 	 * in scx_disable_workfn().
5193 	 */
5194 	ei->kind = kind;
5195 	ei->reason = scx_exit_reason(ei->kind);
5196 
5197 	irq_work_queue(&sch->error_irq_work);
5198 	return true;
5199 }
5200 
5201 static int alloc_kick_syncs(void)
5202 {
5203 	int cpu;
5204 
5205 	/*
5206 	 * Allocate per-CPU arrays sized by nr_cpu_ids. Use kvzalloc as size
5207 	 * can exceed percpu allocator limits on large machines.
5208 	 */
5209 	for_each_possible_cpu(cpu) {
5210 		struct scx_kick_syncs **ksyncs = per_cpu_ptr(&scx_kick_syncs, cpu);
5211 		struct scx_kick_syncs *new_ksyncs;
5212 
5213 		WARN_ON_ONCE(rcu_access_pointer(*ksyncs));
5214 
5215 		new_ksyncs = kvzalloc_node(struct_size(new_ksyncs, syncs, nr_cpu_ids),
5216 					   GFP_KERNEL, cpu_to_node(cpu));
5217 		if (!new_ksyncs) {
5218 			free_kick_syncs();
5219 			return -ENOMEM;
5220 		}
5221 
5222 		rcu_assign_pointer(*ksyncs, new_ksyncs);
5223 	}
5224 
5225 	return 0;
5226 }
5227 
5228 static struct scx_sched *scx_alloc_and_add_sched(struct sched_ext_ops *ops,
5229 						 struct cgroup *cgrp,
5230 						 struct scx_sched *parent)
5231 {
5232 	struct scx_sched *sch;
5233 	s32 level = parent ? parent->level + 1 : 0;
5234 	int node, ret;
5235 
5236 	sch = kzalloc_flex(*sch, ancestors, level);
5237 	if (!sch)
5238 		return ERR_PTR(-ENOMEM);
5239 
5240 	sch->exit_info = alloc_exit_info(ops->exit_dump_len);
5241 	if (!sch->exit_info) {
5242 		ret = -ENOMEM;
5243 		goto err_free_sch;
5244 	}
5245 
5246 	ret = rhashtable_init(&sch->dsq_hash, &dsq_hash_params);
5247 	if (ret < 0)
5248 		goto err_free_ei;
5249 
5250 	sch->global_dsqs = kzalloc_objs(sch->global_dsqs[0], nr_node_ids);
5251 	if (!sch->global_dsqs) {
5252 		ret = -ENOMEM;
5253 		goto err_free_hash;
5254 	}
5255 
5256 	for_each_node_state(node, N_POSSIBLE) {
5257 		struct scx_dispatch_q *dsq;
5258 
5259 		dsq = kzalloc_node(sizeof(*dsq), GFP_KERNEL, node);
5260 		if (!dsq) {
5261 			ret = -ENOMEM;
5262 			goto err_free_gdsqs;
5263 		}
5264 
5265 		init_dsq(dsq, SCX_DSQ_GLOBAL, sch);
5266 		sch->global_dsqs[node] = dsq;
5267 	}
5268 
5269 	sch->pcpu = alloc_percpu(struct scx_sched_pcpu);
5270 	if (!sch->pcpu) {
5271 		ret = -ENOMEM;
5272 		goto err_free_gdsqs;
5273 	}
5274 
5275 	sch->helper = kthread_run_worker(0, "sched_ext_helper");
5276 	if (IS_ERR(sch->helper)) {
5277 		ret = PTR_ERR(sch->helper);
5278 		goto err_free_pcpu;
5279 	}
5280 
5281 	sched_set_fifo(sch->helper->task);
5282 
5283 	if (parent)
5284 		memcpy(sch->ancestors, parent->ancestors,
5285 		       level * sizeof(parent->ancestors[0]));
5286 	sch->ancestors[level] = sch;
5287 	sch->level = level;
5288 
5289 	atomic_set(&sch->exit_kind, SCX_EXIT_NONE);
5290 	init_irq_work(&sch->error_irq_work, scx_error_irq_workfn);
5291 	kthread_init_work(&sch->disable_work, scx_disable_workfn);
5292 	sch->ops = *ops;
5293 	rcu_assign_pointer(ops->priv, sch);
5294 
5295 	sch->kobj.kset = scx_kset;
5296 
5297 #ifdef CONFIG_EXT_SUB_SCHED
5298 	char *buf = kzalloc(PATH_MAX, GFP_KERNEL);
5299 	if (!buf)
5300 		goto err_stop_helper;
5301 	cgroup_path(cgrp, buf, PATH_MAX);
5302 	sch->cgrp_path = kstrdup(buf, GFP_KERNEL);
5303 	kfree(buf);
5304 	if (!sch->cgrp_path)
5305 		goto err_stop_helper;
5306 
5307 	sch->cgrp = cgrp;
5308 	INIT_LIST_HEAD(&sch->children);
5309 	INIT_LIST_HEAD(&sch->sibling);
5310 
5311 	if (parent)
5312 		ret = kobject_init_and_add(&sch->kobj, &scx_ktype,
5313 					   &parent->sub_kset->kobj,
5314 					   "sub-%llu", cgroup_id(cgrp));
5315 	else
5316 		ret = kobject_init_and_add(&sch->kobj, &scx_ktype, NULL, "root");
5317 
5318 	if (ret < 0) {
5319 		kfree(sch->cgrp_path);
5320 		goto err_stop_helper;
5321 	}
5322 
5323 	if (ops->sub_attach) {
5324 		sch->sub_kset = kset_create_and_add("sub", NULL, &sch->kobj);
5325 		if (!sch->sub_kset) {
5326 			kobject_put(&sch->kobj);
5327 			return ERR_PTR(-ENOMEM);
5328 		}
5329 	}
5330 
5331 #else	/* CONFIG_EXT_SUB_SCHED */
5332 	ret = kobject_init_and_add(&sch->kobj, &scx_ktype, NULL, "root");
5333 	if (ret < 0)
5334 		goto err_stop_helper;
5335 #endif	/* CONFIG_EXT_SUB_SCHED */
5336 	return sch;
5337 
5338 err_stop_helper:
5339 	kthread_destroy_worker(sch->helper);
5340 err_free_pcpu:
5341 	free_percpu(sch->pcpu);
5342 err_free_gdsqs:
5343 	for_each_node_state(node, N_POSSIBLE)
5344 		kfree(sch->global_dsqs[node]);
5345 	kfree(sch->global_dsqs);
5346 err_free_hash:
5347 	rhashtable_free_and_destroy(&sch->dsq_hash, NULL, NULL);
5348 err_free_ei:
5349 	free_exit_info(sch->exit_info);
5350 err_free_sch:
5351 	kfree(sch);
5352 	return ERR_PTR(ret);
5353 }
5354 
5355 static int check_hotplug_seq(struct scx_sched *sch,
5356 			      const struct sched_ext_ops *ops)
5357 {
5358 	unsigned long long global_hotplug_seq;
5359 
5360 	/*
5361 	 * If a hotplug event has occurred between when a scheduler was
5362 	 * initialized, and when we were able to attach, exit and notify user
5363 	 * space about it.
5364 	 */
5365 	if (ops->hotplug_seq) {
5366 		global_hotplug_seq = atomic_long_read(&scx_hotplug_seq);
5367 		if (ops->hotplug_seq != global_hotplug_seq) {
5368 			scx_exit(sch, SCX_EXIT_UNREG_KERN,
5369 				 SCX_ECODE_ACT_RESTART | SCX_ECODE_RSN_HOTPLUG,
5370 				 "expected hotplug seq %llu did not match actual %llu",
5371 				 ops->hotplug_seq, global_hotplug_seq);
5372 			return -EBUSY;
5373 		}
5374 	}
5375 
5376 	return 0;
5377 }
5378 
5379 static int validate_ops(struct scx_sched *sch, const struct sched_ext_ops *ops)
5380 {
5381 	/*
5382 	 * It doesn't make sense to specify the SCX_OPS_ENQ_LAST flag if the
5383 	 * ops.enqueue() callback isn't implemented.
5384 	 */
5385 	if ((ops->flags & SCX_OPS_ENQ_LAST) && !ops->enqueue) {
5386 		scx_error(sch, "SCX_OPS_ENQ_LAST requires ops.enqueue() to be implemented");
5387 		return -EINVAL;
5388 	}
5389 
5390 	/*
5391 	 * SCX_OPS_BUILTIN_IDLE_PER_NODE requires built-in CPU idle
5392 	 * selection policy to be enabled.
5393 	 */
5394 	if ((ops->flags & SCX_OPS_BUILTIN_IDLE_PER_NODE) &&
5395 	    (ops->update_idle && !(ops->flags & SCX_OPS_KEEP_BUILTIN_IDLE))) {
5396 		scx_error(sch, "SCX_OPS_BUILTIN_IDLE_PER_NODE requires CPU idle selection enabled");
5397 		return -EINVAL;
5398 	}
5399 
5400 	if (ops->flags & SCX_OPS_HAS_CGROUP_WEIGHT)
5401 		pr_warn("SCX_OPS_HAS_CGROUP_WEIGHT is deprecated and a noop\n");
5402 
5403 	if (ops->cpu_acquire || ops->cpu_release)
5404 		pr_warn("ops->cpu_acquire/release() are deprecated, use sched_switch TP instead\n");
5405 
5406 	return 0;
5407 }
5408 
5409 /*
5410  * scx_enable() is offloaded to a dedicated system-wide RT kthread to avoid
5411  * starvation. During the READY -> ENABLED task switching loop, the calling
5412  * thread's sched_class gets switched from fair to ext. As fair has higher
5413  * priority than ext, the calling thread can be indefinitely starved under
5414  * fair-class saturation, leading to a system hang.
5415  */
5416 struct scx_enable_cmd {
5417 	struct kthread_work	work;
5418 	struct sched_ext_ops	*ops;
5419 	int			ret;
5420 };
5421 
5422 static void scx_root_enable_workfn(struct kthread_work *work)
5423 {
5424 	struct scx_enable_cmd *cmd = container_of(work, struct scx_enable_cmd, work);
5425 	struct sched_ext_ops *ops = cmd->ops;
5426 	struct scx_sched *sch;
5427 	struct scx_task_iter sti;
5428 	struct task_struct *p;
5429 	unsigned long timeout;
5430 	int i, cpu, ret;
5431 
5432 	mutex_lock(&scx_enable_mutex);
5433 
5434 	if (scx_enable_state() != SCX_DISABLED) {
5435 		ret = -EBUSY;
5436 		goto err_unlock;
5437 	}
5438 
5439 	ret = alloc_kick_syncs();
5440 	if (ret)
5441 		goto err_unlock;
5442 
5443 	sch = scx_alloc_and_add_sched(ops, root_cgroup(), NULL);
5444 	if (IS_ERR(sch)) {
5445 		ret = PTR_ERR(sch);
5446 		goto err_free_ksyncs;
5447 	}
5448 
5449 	/*
5450 	 * Transition to ENABLING and clear exit info to arm the disable path.
5451 	 * Failure triggers full disabling from here on.
5452 	 */
5453 	WARN_ON_ONCE(scx_set_enable_state(SCX_ENABLING) != SCX_DISABLED);
5454 	WARN_ON_ONCE(scx_root);
5455 	if (WARN_ON_ONCE(READ_ONCE(scx_aborting)))
5456 		WRITE_ONCE(scx_aborting, false);
5457 
5458 	atomic_long_set(&scx_nr_rejected, 0);
5459 
5460 	for_each_possible_cpu(cpu) {
5461 		struct rq *rq = cpu_rq(cpu);
5462 
5463 		rq->scx.local_dsq.sched = sch;
5464 		rq->scx.bypass_dsq.sched = sch;
5465 		rq->scx.cpuperf_target = SCX_CPUPERF_ONE;
5466 	}
5467 
5468 	/*
5469 	 * Keep CPUs stable during enable so that the BPF scheduler can track
5470 	 * online CPUs by watching ->on/offline_cpu() after ->init().
5471 	 */
5472 	cpus_read_lock();
5473 
5474 	/*
5475 	 * Make the scheduler instance visible. Must be inside cpus_read_lock().
5476 	 * See handle_hotplug().
5477 	 */
5478 	rcu_assign_pointer(scx_root, sch);
5479 
5480 	raw_spin_lock_irq(&scx_sched_lock);
5481 	list_add_tail_rcu(&sch->all, &scx_sched_all);
5482 	raw_spin_unlock_irq(&scx_sched_lock);
5483 
5484 	scx_idle_enable(ops);
5485 
5486 	if (sch->ops.init) {
5487 		ret = SCX_CALL_OP_RET(sch, SCX_KF_UNLOCKED, init, NULL);
5488 		if (ret) {
5489 			ret = ops_sanitize_err(sch, "init", ret);
5490 			cpus_read_unlock();
5491 			scx_error(sch, "ops.init() failed (%d)", ret);
5492 			goto err_disable;
5493 		}
5494 		sch->exit_info->flags |= SCX_EFLAG_INITIALIZED;
5495 	}
5496 
5497 	for (i = SCX_OPI_CPU_HOTPLUG_BEGIN; i < SCX_OPI_CPU_HOTPLUG_END; i++)
5498 		if (((void (**)(void))ops)[i])
5499 			set_bit(i, sch->has_op);
5500 
5501 	ret = check_hotplug_seq(sch, ops);
5502 	if (ret) {
5503 		cpus_read_unlock();
5504 		goto err_disable;
5505 	}
5506 	scx_idle_update_selcpu_topology(ops);
5507 
5508 	cpus_read_unlock();
5509 
5510 	ret = validate_ops(sch, ops);
5511 	if (ret)
5512 		goto err_disable;
5513 
5514 	WARN_ON_ONCE(scx_dsp_ctx);
5515 	scx_dsp_max_batch = ops->dispatch_max_batch ?: SCX_DSP_DFL_MAX_BATCH;
5516 	scx_dsp_ctx = __alloc_percpu(struct_size_t(struct scx_dsp_ctx, buf,
5517 						   scx_dsp_max_batch),
5518 				     __alignof__(struct scx_dsp_ctx));
5519 	if (!scx_dsp_ctx) {
5520 		ret = -ENOMEM;
5521 		goto err_disable;
5522 	}
5523 
5524 	if (ops->timeout_ms)
5525 		timeout = msecs_to_jiffies(ops->timeout_ms);
5526 	else
5527 		timeout = SCX_WATCHDOG_MAX_TIMEOUT;
5528 
5529 	WRITE_ONCE(scx_watchdog_timeout, timeout);
5530 	WRITE_ONCE(scx_watchdog_timestamp, jiffies);
5531 	queue_delayed_work(system_unbound_wq, &scx_watchdog_work,
5532 			   READ_ONCE(scx_watchdog_timeout) / 2);
5533 
5534 	/*
5535 	 * Once __scx_enabled is set, %current can be switched to SCX anytime.
5536 	 * This can lead to stalls as some BPF schedulers (e.g. userspace
5537 	 * scheduling) may not function correctly before all tasks are switched.
5538 	 * Init in bypass mode to guarantee forward progress.
5539 	 */
5540 	scx_bypass(true);
5541 	scx_bypassed_for_enable = true;
5542 
5543 	for (i = SCX_OPI_NORMAL_BEGIN; i < SCX_OPI_NORMAL_END; i++)
5544 		if (((void (**)(void))ops)[i])
5545 			set_bit(i, sch->has_op);
5546 
5547 	if (sch->ops.cpu_acquire || sch->ops.cpu_release)
5548 		sch->ops.flags |= SCX_OPS_HAS_CPU_PREEMPT;
5549 
5550 	/*
5551 	 * Lock out forks, cgroup on/offlining and moves before opening the
5552 	 * floodgate so that they don't wander into the operations prematurely.
5553 	 */
5554 	percpu_down_write(&scx_fork_rwsem);
5555 
5556 	WARN_ON_ONCE(scx_init_task_enabled);
5557 	scx_init_task_enabled = true;
5558 
5559 	/*
5560 	 * Enable ops for every task. Fork is excluded by scx_fork_rwsem
5561 	 * preventing new tasks from being added. No need to exclude tasks
5562 	 * leaving as sched_ext_free() can handle both prepped and enabled
5563 	 * tasks. Prep all tasks first and then enable them with preemption
5564 	 * disabled.
5565 	 *
5566 	 * All cgroups should be initialized before scx_init_task() so that the
5567 	 * BPF scheduler can reliably track each task's cgroup membership from
5568 	 * scx_init_task(). Lock out cgroup on/offlining and task migrations
5569 	 * while tasks are being initialized so that scx_cgroup_can_attach()
5570 	 * never sees uninitialized tasks.
5571 	 */
5572 	scx_cgroup_lock();
5573 	set_cgroup_sched(sch_cgroup(sch), sch);
5574 	ret = scx_cgroup_init(sch);
5575 	if (ret)
5576 		goto err_disable_unlock_all;
5577 
5578 	scx_task_iter_start(&sti, NULL);
5579 	while ((p = scx_task_iter_next_locked(&sti))) {
5580 		/*
5581 		 * @p may already be dead, have lost all its usages counts and
5582 		 * be waiting for RCU grace period before being freed. @p can't
5583 		 * be initialized for SCX in such cases and should be ignored.
5584 		 */
5585 		if (!tryget_task_struct(p))
5586 			continue;
5587 
5588 		scx_task_iter_unlock(&sti);
5589 
5590 		ret = scx_init_task(p, task_group(p), false);
5591 		if (ret) {
5592 			put_task_struct(p);
5593 			scx_task_iter_stop(&sti);
5594 			scx_error(sch, "ops.init_task() failed (%d) for %s[%d]",
5595 				  ret, p->comm, p->pid);
5596 			goto err_disable_unlock_all;
5597 		}
5598 
5599 		scx_set_task_sched(p, sch);
5600 		scx_set_task_state(p, SCX_TASK_READY);
5601 
5602 		put_task_struct(p);
5603 	}
5604 	scx_task_iter_stop(&sti);
5605 	scx_cgroup_unlock();
5606 	percpu_up_write(&scx_fork_rwsem);
5607 
5608 	/*
5609 	 * All tasks are READY. It's safe to turn on scx_enabled() and switch
5610 	 * all eligible tasks.
5611 	 */
5612 	WRITE_ONCE(scx_switching_all, !(ops->flags & SCX_OPS_SWITCH_PARTIAL));
5613 	static_branch_enable(&__scx_enabled);
5614 
5615 	/*
5616 	 * We're fully committed and can't fail. The task READY -> ENABLED
5617 	 * transitions here are synchronized against sched_ext_free() through
5618 	 * scx_tasks_lock.
5619 	 */
5620 	percpu_down_write(&scx_fork_rwsem);
5621 	scx_task_iter_start(&sti, NULL);
5622 	while ((p = scx_task_iter_next_locked(&sti))) {
5623 		unsigned int queue_flags = DEQUEUE_SAVE | DEQUEUE_MOVE;
5624 		const struct sched_class *old_class = p->sched_class;
5625 		const struct sched_class *new_class = scx_setscheduler_class(p);
5626 
5627 		if (scx_get_task_state(p) != SCX_TASK_READY)
5628 			continue;
5629 
5630 		if (old_class != new_class)
5631 			queue_flags |= DEQUEUE_CLASS;
5632 
5633 		scoped_guard (sched_change, p, queue_flags) {
5634 			p->scx.slice = READ_ONCE(scx_slice_dfl);
5635 			p->sched_class = new_class;
5636 		}
5637 	}
5638 	scx_task_iter_stop(&sti);
5639 	percpu_up_write(&scx_fork_rwsem);
5640 
5641 	scx_bypassed_for_enable = false;
5642 	scx_bypass(false);
5643 
5644 	if (!scx_tryset_enable_state(SCX_ENABLED, SCX_ENABLING)) {
5645 		WARN_ON_ONCE(atomic_read(&sch->exit_kind) == SCX_EXIT_NONE);
5646 		goto err_disable;
5647 	}
5648 
5649 	if (!(ops->flags & SCX_OPS_SWITCH_PARTIAL))
5650 		static_branch_enable(&__scx_switched_all);
5651 
5652 	pr_info("sched_ext: BPF scheduler \"%s\" enabled%s\n",
5653 		sch->ops.name, scx_switched_all() ? "" : " (partial)");
5654 	kobject_uevent(&sch->kobj, KOBJ_ADD);
5655 	mutex_unlock(&scx_enable_mutex);
5656 
5657 	atomic_long_inc(&scx_enable_seq);
5658 
5659 	cmd->ret = 0;
5660 	return;
5661 
5662 err_free_ksyncs:
5663 	free_kick_syncs();
5664 err_unlock:
5665 	mutex_unlock(&scx_enable_mutex);
5666 	cmd->ret = ret;
5667 	return;
5668 
5669 err_disable_unlock_all:
5670 	scx_cgroup_unlock();
5671 	percpu_up_write(&scx_fork_rwsem);
5672 	/* we'll soon enter disable path, keep bypass on */
5673 err_disable:
5674 	mutex_unlock(&scx_enable_mutex);
5675 	/*
5676 	 * Returning an error code here would not pass all the error information
5677 	 * to userspace. Record errno using scx_error() for cases scx_error()
5678 	 * wasn't already invoked and exit indicating success so that the error
5679 	 * is notified through ops.exit() with all the details.
5680 	 *
5681 	 * Flush scx_disable_work to ensure that error is reported before init
5682 	 * completion. sch's base reference will be put by bpf_scx_unreg().
5683 	 */
5684 	scx_error(sch, "scx_root_enable() failed (%d)", ret);
5685 	kthread_flush_work(&sch->disable_work);
5686 	cmd->ret = 0;
5687 }
5688 
5689 #ifdef CONFIG_EXT_SUB_SCHED
5690 /* verify that a scheduler can be attached to @cgrp and return the parent */
5691 static struct scx_sched *find_parent_sched(struct cgroup *cgrp)
5692 {
5693 	struct scx_sched *parent = cgrp->scx_sched;
5694 	struct scx_sched *pos;
5695 
5696 	lockdep_assert_held(&scx_sched_lock);
5697 
5698 	/* can't attach twice to the same cgroup */
5699 	if (parent->cgrp == cgrp)
5700 		return ERR_PTR(-EBUSY);
5701 
5702 	/* does $parent allow sub-scheds? */
5703 	if (!parent->ops.sub_attach)
5704 		return ERR_PTR(-EOPNOTSUPP);
5705 
5706 	/* can't insert between $parent and its exiting children */
5707 	list_for_each_entry(pos, &parent->children, sibling)
5708 		if (cgroup_is_descendant(pos->cgrp, cgrp))
5709 			return ERR_PTR(-EBUSY);
5710 
5711 	return parent;
5712 }
5713 
5714 static void scx_sub_enable_workfn(struct kthread_work *work)
5715 {
5716 	struct scx_enable_cmd *cmd = container_of(work, struct scx_enable_cmd, work);
5717 	struct sched_ext_ops *ops = cmd->ops;
5718 	struct cgroup *cgrp;
5719 	struct scx_sched *parent, *sch;
5720 	s32 ret;
5721 
5722 	mutex_lock(&scx_enable_mutex);
5723 
5724 	if (!scx_enabled()) {
5725 		ret = -ENODEV;
5726 		goto out_unlock;
5727 	}
5728 
5729 	cgrp = cgroup_get_from_id(ops->sub_cgroup_id);
5730 	if (IS_ERR(cgrp)) {
5731 		ret = PTR_ERR(cgrp);
5732 		goto out_unlock;
5733 	}
5734 
5735 	raw_spin_lock_irq(&scx_sched_lock);
5736 	parent = find_parent_sched(cgrp);
5737 	if (IS_ERR(parent)) {
5738 		raw_spin_unlock_irq(&scx_sched_lock);
5739 		ret = PTR_ERR(parent);
5740 		goto out_put_cgrp;
5741 	}
5742 	kobject_get(&parent->kobj);
5743 	raw_spin_unlock_irq(&scx_sched_lock);
5744 
5745 	sch = scx_alloc_and_add_sched(ops, cgrp, parent);
5746 	kobject_put(&parent->kobj);
5747 	if (IS_ERR(sch)) {
5748 		ret = PTR_ERR(sch);
5749 		goto out_put_cgrp;
5750 	}
5751 
5752 	raw_spin_lock_irq(&scx_sched_lock);
5753 	list_add_tail(&sch->sibling, &parent->children);
5754 	list_add_tail_rcu(&sch->all, &scx_sched_all);
5755 	raw_spin_unlock_irq(&scx_sched_lock);
5756 
5757 	if (sch->level >= SCX_SUB_MAX_DEPTH) {
5758 		scx_error(sch, "max nesting depth %d violated",
5759 			  SCX_SUB_MAX_DEPTH);
5760 		goto err_disable;
5761 	}
5762 
5763 	if (sch->ops.init) {
5764 		ret = SCX_CALL_OP_RET(sch, SCX_KF_UNLOCKED, init, NULL);
5765 		if (ret) {
5766 			ret = ops_sanitize_err(sch, "init", ret);
5767 			scx_error(sch, "ops.init() failed (%d)", ret);
5768 			goto err_disable;
5769 		}
5770 		sch->exit_info->flags |= SCX_EFLAG_INITIALIZED;
5771 	}
5772 
5773 	if (validate_ops(sch, ops))
5774 		goto err_disable;
5775 
5776 	struct scx_sub_attach_args sub_attach_args = {
5777 		.ops = &sch->ops,
5778 		.cgroup_path = sch->cgrp_path,
5779 	};
5780 
5781 	ret = SCX_CALL_OP_RET(parent, SCX_KF_UNLOCKED, sub_attach, NULL,
5782 			      &sub_attach_args);
5783 	if (ret) {
5784 		ret = ops_sanitize_err(sch, "sub_attach", ret);
5785 		scx_error(sch, "parent rejected (%d)", ret);
5786 		goto err_disable;
5787 	}
5788 	sch->sub_attached = true;
5789 
5790 	percpu_down_write(&scx_fork_rwsem);
5791 	scx_cgroup_lock();
5792 
5793 	/*
5794 	 * Set cgroup->scx_sched's and check CSS_ONLINE. Either we see
5795 	 * !CSS_ONLINE or scx_cgroup_lifetime_notify() sees and shoots us down.
5796 	 */
5797 	set_cgroup_sched(sch_cgroup(sch), sch);
5798 	if (!(cgrp->self.flags & CSS_ONLINE)) {
5799 		scx_error(sch, "cgroup is not online");
5800 		goto err_unlock_and_disable;
5801 	}
5802 
5803 	/* TODO - perform actual enabling here */
5804 
5805 	scx_cgroup_unlock();
5806 	percpu_up_write(&scx_fork_rwsem);
5807 
5808 	pr_info("sched_ext: BPF sub-scheduler \"%s\" enabled\n", sch->ops.name);
5809 	kobject_uevent(&sch->kobj, KOBJ_ADD);
5810 	ret = 0;
5811 	goto out_unlock;
5812 
5813 out_put_cgrp:
5814 	cgroup_put(cgrp);
5815 out_unlock:
5816 	mutex_unlock(&scx_enable_mutex);
5817 	cmd->ret = ret;
5818 	return;
5819 
5820 err_unlock_and_disable:
5821 	scx_cgroup_unlock();
5822 	percpu_up_write(&scx_fork_rwsem);
5823 err_disable:
5824 	mutex_unlock(&scx_enable_mutex);
5825 	kthread_flush_work(&sch->disable_work);
5826 	cmd->ret = 0;
5827 }
5828 
5829 static s32 scx_cgroup_lifetime_notify(struct notifier_block *nb,
5830 				      unsigned long action, void *data)
5831 {
5832 	struct cgroup *cgrp = data;
5833 	struct cgroup *parent = cgroup_parent(cgrp);
5834 
5835 	if (!cgroup_on_dfl(cgrp))
5836 		return NOTIFY_OK;
5837 
5838 	switch (action) {
5839 	case CGROUP_LIFETIME_ONLINE:
5840 		/* inherit ->scx_sched from $parent */
5841 		if (parent)
5842 			rcu_assign_pointer(cgrp->scx_sched, parent->scx_sched);
5843 		break;
5844 	case CGROUP_LIFETIME_OFFLINE:
5845 		/* if there is a sched attached, shoot it down */
5846 		if (cgrp->scx_sched && cgrp->scx_sched->cgrp == cgrp)
5847 			scx_exit(cgrp->scx_sched, SCX_EXIT_UNREG_KERN,
5848 				 SCX_ECODE_RSN_CGROUP_OFFLINE,
5849 				 "cgroup %llu going offline", cgroup_id(cgrp));
5850 		break;
5851 	}
5852 
5853 	return NOTIFY_OK;
5854 }
5855 
5856 static struct notifier_block scx_cgroup_lifetime_nb = {
5857 	.notifier_call = scx_cgroup_lifetime_notify,
5858 };
5859 
5860 static s32 __init scx_cgroup_lifetime_notifier_init(void)
5861 {
5862 	return blocking_notifier_chain_register(&cgroup_lifetime_notifier,
5863 						&scx_cgroup_lifetime_nb);
5864 }
5865 core_initcall(scx_cgroup_lifetime_notifier_init);
5866 #endif	/* CONFIG_EXT_SUB_SCHED */
5867 
5868 static s32 scx_enable(struct sched_ext_ops *ops, struct bpf_link *link)
5869 {
5870 	static struct kthread_worker *helper;
5871 	static DEFINE_MUTEX(helper_mutex);
5872 	struct scx_enable_cmd cmd;
5873 
5874 	if (!cpumask_equal(housekeeping_cpumask(HK_TYPE_DOMAIN),
5875 			   cpu_possible_mask)) {
5876 		pr_err("sched_ext: Not compatible with \"isolcpus=\" domain isolation\n");
5877 		return -EINVAL;
5878 	}
5879 
5880 	if (!READ_ONCE(helper)) {
5881 		mutex_lock(&helper_mutex);
5882 		if (!helper) {
5883 			helper = kthread_run_worker(0, "scx_enable_helper");
5884 			if (IS_ERR_OR_NULL(helper)) {
5885 				helper = NULL;
5886 				mutex_unlock(&helper_mutex);
5887 				return -ENOMEM;
5888 			}
5889 			sched_set_fifo(helper->task);
5890 		}
5891 		mutex_unlock(&helper_mutex);
5892 	}
5893 
5894 #ifdef CONFIG_EXT_SUB_SCHED
5895 	if (ops->sub_cgroup_id > 1)
5896 		kthread_init_work(&cmd.work, scx_sub_enable_workfn);
5897 	else
5898 #endif	/* CONFIG_EXT_SUB_SCHED */
5899 		kthread_init_work(&cmd.work, scx_root_enable_workfn);
5900 	cmd.ops = ops;
5901 
5902 	kthread_queue_work(READ_ONCE(helper), &cmd.work);
5903 	kthread_flush_work(&cmd.work);
5904 	return cmd.ret;
5905 }
5906 
5907 
5908 /********************************************************************************
5909  * bpf_struct_ops plumbing.
5910  */
5911 #include <linux/bpf_verifier.h>
5912 #include <linux/bpf.h>
5913 #include <linux/btf.h>
5914 
5915 static const struct btf_type *task_struct_type;
5916 
5917 static bool bpf_scx_is_valid_access(int off, int size,
5918 				    enum bpf_access_type type,
5919 				    const struct bpf_prog *prog,
5920 				    struct bpf_insn_access_aux *info)
5921 {
5922 	if (type != BPF_READ)
5923 		return false;
5924 	if (off < 0 || off >= sizeof(__u64) * MAX_BPF_FUNC_ARGS)
5925 		return false;
5926 	if (off % size != 0)
5927 		return false;
5928 
5929 	return btf_ctx_access(off, size, type, prog, info);
5930 }
5931 
5932 static int bpf_scx_btf_struct_access(struct bpf_verifier_log *log,
5933 				     const struct bpf_reg_state *reg, int off,
5934 				     int size)
5935 {
5936 	const struct btf_type *t;
5937 
5938 	t = btf_type_by_id(reg->btf, reg->btf_id);
5939 	if (t == task_struct_type) {
5940 		if (off >= offsetof(struct task_struct, scx.slice) &&
5941 		    off + size <= offsetofend(struct task_struct, scx.slice))
5942 			return SCALAR_VALUE;
5943 		if (off >= offsetof(struct task_struct, scx.dsq_vtime) &&
5944 		    off + size <= offsetofend(struct task_struct, scx.dsq_vtime))
5945 			return SCALAR_VALUE;
5946 		if (off >= offsetof(struct task_struct, scx.disallow) &&
5947 		    off + size <= offsetofend(struct task_struct, scx.disallow))
5948 			return SCALAR_VALUE;
5949 	}
5950 
5951 	return -EACCES;
5952 }
5953 
5954 static const struct bpf_verifier_ops bpf_scx_verifier_ops = {
5955 	.get_func_proto = bpf_base_func_proto,
5956 	.is_valid_access = bpf_scx_is_valid_access,
5957 	.btf_struct_access = bpf_scx_btf_struct_access,
5958 };
5959 
5960 static int bpf_scx_init_member(const struct btf_type *t,
5961 			       const struct btf_member *member,
5962 			       void *kdata, const void *udata)
5963 {
5964 	const struct sched_ext_ops *uops = udata;
5965 	struct sched_ext_ops *ops = kdata;
5966 	u32 moff = __btf_member_bit_offset(t, member) / 8;
5967 	int ret;
5968 
5969 	switch (moff) {
5970 	case offsetof(struct sched_ext_ops, dispatch_max_batch):
5971 		if (*(u32 *)(udata + moff) > INT_MAX)
5972 			return -E2BIG;
5973 		ops->dispatch_max_batch = *(u32 *)(udata + moff);
5974 		return 1;
5975 	case offsetof(struct sched_ext_ops, flags):
5976 		if (*(u64 *)(udata + moff) & ~SCX_OPS_ALL_FLAGS)
5977 			return -EINVAL;
5978 		ops->flags = *(u64 *)(udata + moff);
5979 		return 1;
5980 	case offsetof(struct sched_ext_ops, name):
5981 		ret = bpf_obj_name_cpy(ops->name, uops->name,
5982 				       sizeof(ops->name));
5983 		if (ret < 0)
5984 			return ret;
5985 		if (ret == 0)
5986 			return -EINVAL;
5987 		return 1;
5988 	case offsetof(struct sched_ext_ops, timeout_ms):
5989 		if (msecs_to_jiffies(*(u32 *)(udata + moff)) >
5990 		    SCX_WATCHDOG_MAX_TIMEOUT)
5991 			return -E2BIG;
5992 		ops->timeout_ms = *(u32 *)(udata + moff);
5993 		return 1;
5994 	case offsetof(struct sched_ext_ops, exit_dump_len):
5995 		ops->exit_dump_len =
5996 			*(u32 *)(udata + moff) ?: SCX_EXIT_DUMP_DFL_LEN;
5997 		return 1;
5998 	case offsetof(struct sched_ext_ops, hotplug_seq):
5999 		ops->hotplug_seq = *(u64 *)(udata + moff);
6000 		return 1;
6001 #ifdef CONFIG_EXT_SUB_SCHED
6002 	case offsetof(struct sched_ext_ops, sub_cgroup_id):
6003 		ops->sub_cgroup_id = *(u64 *)(udata + moff);
6004 		return 1;
6005 #endif	/* CONFIG_EXT_SUB_SCHED */
6006 	}
6007 
6008 	return 0;
6009 }
6010 
6011 static int bpf_scx_check_member(const struct btf_type *t,
6012 				const struct btf_member *member,
6013 				const struct bpf_prog *prog)
6014 {
6015 	u32 moff = __btf_member_bit_offset(t, member) / 8;
6016 
6017 	switch (moff) {
6018 	case offsetof(struct sched_ext_ops, init_task):
6019 #ifdef CONFIG_EXT_GROUP_SCHED
6020 	case offsetof(struct sched_ext_ops, cgroup_init):
6021 	case offsetof(struct sched_ext_ops, cgroup_exit):
6022 	case offsetof(struct sched_ext_ops, cgroup_prep_move):
6023 #endif
6024 	case offsetof(struct sched_ext_ops, cpu_online):
6025 	case offsetof(struct sched_ext_ops, cpu_offline):
6026 	case offsetof(struct sched_ext_ops, init):
6027 	case offsetof(struct sched_ext_ops, exit):
6028 	case offsetof(struct sched_ext_ops, sub_attach):
6029 	case offsetof(struct sched_ext_ops, sub_detach):
6030 		break;
6031 	default:
6032 		if (prog->sleepable)
6033 			return -EINVAL;
6034 	}
6035 
6036 	return 0;
6037 }
6038 
6039 static int bpf_scx_reg(void *kdata, struct bpf_link *link)
6040 {
6041 	return scx_enable(kdata, link);
6042 }
6043 
6044 static void bpf_scx_unreg(void *kdata, struct bpf_link *link)
6045 {
6046 	struct sched_ext_ops *ops = kdata;
6047 	struct scx_sched *sch = rcu_dereference_protected(ops->priv, true);
6048 
6049 	scx_disable(sch, SCX_EXIT_UNREG);
6050 	kthread_flush_work(&sch->disable_work);
6051 	RCU_INIT_POINTER(ops->priv, NULL);
6052 	kobject_put(&sch->kobj);
6053 }
6054 
6055 static int bpf_scx_init(struct btf *btf)
6056 {
6057 	task_struct_type = btf_type_by_id(btf, btf_tracing_ids[BTF_TRACING_TYPE_TASK]);
6058 
6059 	return 0;
6060 }
6061 
6062 static int bpf_scx_update(void *kdata, void *old_kdata, struct bpf_link *link)
6063 {
6064 	/*
6065 	 * sched_ext does not support updating the actively-loaded BPF
6066 	 * scheduler, as registering a BPF scheduler can always fail if the
6067 	 * scheduler returns an error code for e.g. ops.init(), ops.init_task(),
6068 	 * etc. Similarly, we can always race with unregistration happening
6069 	 * elsewhere, such as with sysrq.
6070 	 */
6071 	return -EOPNOTSUPP;
6072 }
6073 
6074 static int bpf_scx_validate(void *kdata)
6075 {
6076 	return 0;
6077 }
6078 
6079 static s32 sched_ext_ops__select_cpu(struct task_struct *p, s32 prev_cpu, u64 wake_flags) { return -EINVAL; }
6080 static void sched_ext_ops__enqueue(struct task_struct *p, u64 enq_flags) {}
6081 static void sched_ext_ops__dequeue(struct task_struct *p, u64 enq_flags) {}
6082 static void sched_ext_ops__dispatch(s32 prev_cpu, struct task_struct *prev__nullable) {}
6083 static void sched_ext_ops__tick(struct task_struct *p) {}
6084 static void sched_ext_ops__runnable(struct task_struct *p, u64 enq_flags) {}
6085 static void sched_ext_ops__running(struct task_struct *p) {}
6086 static void sched_ext_ops__stopping(struct task_struct *p, bool runnable) {}
6087 static void sched_ext_ops__quiescent(struct task_struct *p, u64 deq_flags) {}
6088 static bool sched_ext_ops__yield(struct task_struct *from, struct task_struct *to__nullable) { return false; }
6089 static bool sched_ext_ops__core_sched_before(struct task_struct *a, struct task_struct *b) { return false; }
6090 static void sched_ext_ops__set_weight(struct task_struct *p, u32 weight) {}
6091 static void sched_ext_ops__set_cpumask(struct task_struct *p, const struct cpumask *mask) {}
6092 static void sched_ext_ops__update_idle(s32 cpu, bool idle) {}
6093 static void sched_ext_ops__cpu_acquire(s32 cpu, struct scx_cpu_acquire_args *args) {}
6094 static void sched_ext_ops__cpu_release(s32 cpu, struct scx_cpu_release_args *args) {}
6095 static s32 sched_ext_ops__init_task(struct task_struct *p, struct scx_init_task_args *args) { return -EINVAL; }
6096 static void sched_ext_ops__exit_task(struct task_struct *p, struct scx_exit_task_args *args) {}
6097 static void sched_ext_ops__enable(struct task_struct *p) {}
6098 static void sched_ext_ops__disable(struct task_struct *p) {}
6099 #ifdef CONFIG_EXT_GROUP_SCHED
6100 static s32 sched_ext_ops__cgroup_init(struct cgroup *cgrp, struct scx_cgroup_init_args *args) { return -EINVAL; }
6101 static void sched_ext_ops__cgroup_exit(struct cgroup *cgrp) {}
6102 static s32 sched_ext_ops__cgroup_prep_move(struct task_struct *p, struct cgroup *from, struct cgroup *to) { return -EINVAL; }
6103 static void sched_ext_ops__cgroup_move(struct task_struct *p, struct cgroup *from, struct cgroup *to) {}
6104 static void sched_ext_ops__cgroup_cancel_move(struct task_struct *p, struct cgroup *from, struct cgroup *to) {}
6105 static void sched_ext_ops__cgroup_set_weight(struct cgroup *cgrp, u32 weight) {}
6106 static void sched_ext_ops__cgroup_set_bandwidth(struct cgroup *cgrp, u64 period_us, u64 quota_us, u64 burst_us) {}
6107 static void sched_ext_ops__cgroup_set_idle(struct cgroup *cgrp, bool idle) {}
6108 #endif	/* CONFIG_EXT_GROUP_SCHED */
6109 static s32 sched_ext_ops__sub_attach(struct scx_sub_attach_args *args) { return -EINVAL; }
6110 static void sched_ext_ops__sub_detach(struct scx_sub_detach_args *args) {}
6111 static void sched_ext_ops__cpu_online(s32 cpu) {}
6112 static void sched_ext_ops__cpu_offline(s32 cpu) {}
6113 static s32 sched_ext_ops__init(void) { return -EINVAL; }
6114 static void sched_ext_ops__exit(struct scx_exit_info *info) {}
6115 static void sched_ext_ops__dump(struct scx_dump_ctx *ctx) {}
6116 static void sched_ext_ops__dump_cpu(struct scx_dump_ctx *ctx, s32 cpu, bool idle) {}
6117 static void sched_ext_ops__dump_task(struct scx_dump_ctx *ctx, struct task_struct *p) {}
6118 
6119 static struct sched_ext_ops __bpf_ops_sched_ext_ops = {
6120 	.select_cpu		= sched_ext_ops__select_cpu,
6121 	.enqueue		= sched_ext_ops__enqueue,
6122 	.dequeue		= sched_ext_ops__dequeue,
6123 	.dispatch		= sched_ext_ops__dispatch,
6124 	.tick			= sched_ext_ops__tick,
6125 	.runnable		= sched_ext_ops__runnable,
6126 	.running		= sched_ext_ops__running,
6127 	.stopping		= sched_ext_ops__stopping,
6128 	.quiescent		= sched_ext_ops__quiescent,
6129 	.yield			= sched_ext_ops__yield,
6130 	.core_sched_before	= sched_ext_ops__core_sched_before,
6131 	.set_weight		= sched_ext_ops__set_weight,
6132 	.set_cpumask		= sched_ext_ops__set_cpumask,
6133 	.update_idle		= sched_ext_ops__update_idle,
6134 	.cpu_acquire		= sched_ext_ops__cpu_acquire,
6135 	.cpu_release		= sched_ext_ops__cpu_release,
6136 	.init_task		= sched_ext_ops__init_task,
6137 	.exit_task		= sched_ext_ops__exit_task,
6138 	.enable			= sched_ext_ops__enable,
6139 	.disable		= sched_ext_ops__disable,
6140 #ifdef CONFIG_EXT_GROUP_SCHED
6141 	.cgroup_init		= sched_ext_ops__cgroup_init,
6142 	.cgroup_exit		= sched_ext_ops__cgroup_exit,
6143 	.cgroup_prep_move	= sched_ext_ops__cgroup_prep_move,
6144 	.cgroup_move		= sched_ext_ops__cgroup_move,
6145 	.cgroup_cancel_move	= sched_ext_ops__cgroup_cancel_move,
6146 	.cgroup_set_weight	= sched_ext_ops__cgroup_set_weight,
6147 	.cgroup_set_bandwidth	= sched_ext_ops__cgroup_set_bandwidth,
6148 	.cgroup_set_idle	= sched_ext_ops__cgroup_set_idle,
6149 #endif
6150 	.sub_attach		= sched_ext_ops__sub_attach,
6151 	.sub_detach		= sched_ext_ops__sub_detach,
6152 	.cpu_online		= sched_ext_ops__cpu_online,
6153 	.cpu_offline		= sched_ext_ops__cpu_offline,
6154 	.init			= sched_ext_ops__init,
6155 	.exit			= sched_ext_ops__exit,
6156 	.dump			= sched_ext_ops__dump,
6157 	.dump_cpu		= sched_ext_ops__dump_cpu,
6158 	.dump_task		= sched_ext_ops__dump_task,
6159 };
6160 
6161 static struct bpf_struct_ops bpf_sched_ext_ops = {
6162 	.verifier_ops = &bpf_scx_verifier_ops,
6163 	.reg = bpf_scx_reg,
6164 	.unreg = bpf_scx_unreg,
6165 	.check_member = bpf_scx_check_member,
6166 	.init_member = bpf_scx_init_member,
6167 	.init = bpf_scx_init,
6168 	.update = bpf_scx_update,
6169 	.validate = bpf_scx_validate,
6170 	.name = "sched_ext_ops",
6171 	.owner = THIS_MODULE,
6172 	.cfi_stubs = &__bpf_ops_sched_ext_ops
6173 };
6174 
6175 
6176 /********************************************************************************
6177  * System integration and init.
6178  */
6179 
6180 static void sysrq_handle_sched_ext_reset(u8 key)
6181 {
6182 	struct scx_sched *sch;
6183 
6184 	rcu_read_lock();
6185 	sch = rcu_dereference(scx_root);
6186 	if (likely(sch))
6187 		scx_disable(sch, SCX_EXIT_SYSRQ);
6188 	else
6189 		pr_info("sched_ext: BPF schedulers not loaded\n");
6190 	rcu_read_unlock();
6191 }
6192 
6193 static const struct sysrq_key_op sysrq_sched_ext_reset_op = {
6194 	.handler	= sysrq_handle_sched_ext_reset,
6195 	.help_msg	= "reset-sched-ext(S)",
6196 	.action_msg	= "Disable sched_ext and revert all tasks to CFS",
6197 	.enable_mask	= SYSRQ_ENABLE_RTNICE,
6198 };
6199 
6200 static void sysrq_handle_sched_ext_dump(u8 key)
6201 {
6202 	struct scx_exit_info ei = { .kind = SCX_EXIT_NONE, .reason = "SysRq-D" };
6203 
6204 	if (scx_enabled())
6205 		scx_dump_state(&ei, 0);
6206 }
6207 
6208 static const struct sysrq_key_op sysrq_sched_ext_dump_op = {
6209 	.handler	= sysrq_handle_sched_ext_dump,
6210 	.help_msg	= "dump-sched-ext(D)",
6211 	.action_msg	= "Trigger sched_ext debug dump",
6212 	.enable_mask	= SYSRQ_ENABLE_RTNICE,
6213 };
6214 
6215 static bool can_skip_idle_kick(struct rq *rq)
6216 {
6217 	lockdep_assert_rq_held(rq);
6218 
6219 	/*
6220 	 * We can skip idle kicking if @rq is going to go through at least one
6221 	 * full SCX scheduling cycle before going idle. Just checking whether
6222 	 * curr is not idle is insufficient because we could be racing
6223 	 * balance_one() trying to pull the next task from a remote rq, which
6224 	 * may fail, and @rq may become idle afterwards.
6225 	 *
6226 	 * The race window is small and we don't and can't guarantee that @rq is
6227 	 * only kicked while idle anyway. Skip only when sure.
6228 	 */
6229 	return !is_idle_task(rq->curr) && !(rq->scx.flags & SCX_RQ_IN_BALANCE);
6230 }
6231 
6232 static bool kick_one_cpu(s32 cpu, struct rq *this_rq, unsigned long *ksyncs)
6233 {
6234 	struct rq *rq = cpu_rq(cpu);
6235 	struct scx_rq *this_scx = &this_rq->scx;
6236 	const struct sched_class *cur_class;
6237 	bool should_wait = false;
6238 	unsigned long flags;
6239 
6240 	raw_spin_rq_lock_irqsave(rq, flags);
6241 	cur_class = rq->curr->sched_class;
6242 
6243 	/*
6244 	 * During CPU hotplug, a CPU may depend on kicking itself to make
6245 	 * forward progress. Allow kicking self regardless of online state. If
6246 	 * @cpu is running a higher class task, we have no control over @cpu.
6247 	 * Skip kicking.
6248 	 */
6249 	if ((cpu_online(cpu) || cpu == cpu_of(this_rq)) &&
6250 	    !sched_class_above(cur_class, &ext_sched_class)) {
6251 		if (cpumask_test_cpu(cpu, this_scx->cpus_to_preempt)) {
6252 			if (cur_class == &ext_sched_class)
6253 				rq->curr->scx.slice = 0;
6254 			cpumask_clear_cpu(cpu, this_scx->cpus_to_preempt);
6255 		}
6256 
6257 		if (cpumask_test_cpu(cpu, this_scx->cpus_to_wait)) {
6258 			if (cur_class == &ext_sched_class) {
6259 				ksyncs[cpu] = rq->scx.kick_sync;
6260 				should_wait = true;
6261 			} else {
6262 				cpumask_clear_cpu(cpu, this_scx->cpus_to_wait);
6263 			}
6264 		}
6265 
6266 		resched_curr(rq);
6267 	} else {
6268 		cpumask_clear_cpu(cpu, this_scx->cpus_to_preempt);
6269 		cpumask_clear_cpu(cpu, this_scx->cpus_to_wait);
6270 	}
6271 
6272 	raw_spin_rq_unlock_irqrestore(rq, flags);
6273 
6274 	return should_wait;
6275 }
6276 
6277 static void kick_one_cpu_if_idle(s32 cpu, struct rq *this_rq)
6278 {
6279 	struct rq *rq = cpu_rq(cpu);
6280 	unsigned long flags;
6281 
6282 	raw_spin_rq_lock_irqsave(rq, flags);
6283 
6284 	if (!can_skip_idle_kick(rq) &&
6285 	    (cpu_online(cpu) || cpu == cpu_of(this_rq)))
6286 		resched_curr(rq);
6287 
6288 	raw_spin_rq_unlock_irqrestore(rq, flags);
6289 }
6290 
6291 static void kick_cpus_irq_workfn(struct irq_work *irq_work)
6292 {
6293 	struct rq *this_rq = this_rq();
6294 	struct scx_rq *this_scx = &this_rq->scx;
6295 	struct scx_kick_syncs __rcu *ksyncs_pcpu = __this_cpu_read(scx_kick_syncs);
6296 	bool should_wait = false;
6297 	unsigned long *ksyncs;
6298 	s32 cpu;
6299 
6300 	if (unlikely(!ksyncs_pcpu)) {
6301 		pr_warn_once("kick_cpus_irq_workfn() called with NULL scx_kick_syncs");
6302 		return;
6303 	}
6304 
6305 	ksyncs = rcu_dereference_bh(ksyncs_pcpu)->syncs;
6306 
6307 	for_each_cpu(cpu, this_scx->cpus_to_kick) {
6308 		should_wait |= kick_one_cpu(cpu, this_rq, ksyncs);
6309 		cpumask_clear_cpu(cpu, this_scx->cpus_to_kick);
6310 		cpumask_clear_cpu(cpu, this_scx->cpus_to_kick_if_idle);
6311 	}
6312 
6313 	for_each_cpu(cpu, this_scx->cpus_to_kick_if_idle) {
6314 		kick_one_cpu_if_idle(cpu, this_rq);
6315 		cpumask_clear_cpu(cpu, this_scx->cpus_to_kick_if_idle);
6316 	}
6317 
6318 	if (!should_wait)
6319 		return;
6320 
6321 	for_each_cpu(cpu, this_scx->cpus_to_wait) {
6322 		unsigned long *wait_kick_sync = &cpu_rq(cpu)->scx.kick_sync;
6323 
6324 		/*
6325 		 * Busy-wait until the task running at the time of kicking is no
6326 		 * longer running. This can be used to implement e.g. core
6327 		 * scheduling.
6328 		 *
6329 		 * smp_cond_load_acquire() pairs with store_releases in
6330 		 * pick_task_scx() and put_prev_task_scx(). The former breaks
6331 		 * the wait if SCX's scheduling path is entered even if the same
6332 		 * task is picked subsequently. The latter is necessary to break
6333 		 * the wait when $cpu is taken by a higher sched class.
6334 		 */
6335 		if (cpu != cpu_of(this_rq))
6336 			smp_cond_load_acquire(wait_kick_sync, VAL != ksyncs[cpu]);
6337 
6338 		cpumask_clear_cpu(cpu, this_scx->cpus_to_wait);
6339 	}
6340 }
6341 
6342 /**
6343  * print_scx_info - print out sched_ext scheduler state
6344  * @log_lvl: the log level to use when printing
6345  * @p: target task
6346  *
6347  * If a sched_ext scheduler is enabled, print the name and state of the
6348  * scheduler. If @p is on sched_ext, print further information about the task.
6349  *
6350  * This function can be safely called on any task as long as the task_struct
6351  * itself is accessible. While safe, this function isn't synchronized and may
6352  * print out mixups or garbages of limited length.
6353  */
6354 void print_scx_info(const char *log_lvl, struct task_struct *p)
6355 {
6356 	struct scx_sched *sch = scx_root;
6357 	enum scx_enable_state state = scx_enable_state();
6358 	const char *all = READ_ONCE(scx_switching_all) ? "+all" : "";
6359 	char runnable_at_buf[22] = "?";
6360 	struct sched_class *class;
6361 	unsigned long runnable_at;
6362 
6363 	if (state == SCX_DISABLED)
6364 		return;
6365 
6366 	/*
6367 	 * Carefully check if the task was running on sched_ext, and then
6368 	 * carefully copy the time it's been runnable, and its state.
6369 	 */
6370 	if (copy_from_kernel_nofault(&class, &p->sched_class, sizeof(class)) ||
6371 	    class != &ext_sched_class) {
6372 		printk("%sSched_ext: %s (%s%s)", log_lvl, sch->ops.name,
6373 		       scx_enable_state_str[state], all);
6374 		return;
6375 	}
6376 
6377 	if (!copy_from_kernel_nofault(&runnable_at, &p->scx.runnable_at,
6378 				      sizeof(runnable_at)))
6379 		scnprintf(runnable_at_buf, sizeof(runnable_at_buf), "%+ldms",
6380 			  jiffies_delta_msecs(runnable_at, jiffies));
6381 
6382 	/* print everything onto one line to conserve console space */
6383 	printk("%sSched_ext: %s (%s%s), task: runnable_at=%s",
6384 	       log_lvl, sch->ops.name, scx_enable_state_str[state], all,
6385 	       runnable_at_buf);
6386 }
6387 
6388 static int scx_pm_handler(struct notifier_block *nb, unsigned long event, void *ptr)
6389 {
6390 	/*
6391 	 * SCX schedulers often have userspace components which are sometimes
6392 	 * involved in critial scheduling paths. PM operations involve freezing
6393 	 * userspace which can lead to scheduling misbehaviors including stalls.
6394 	 * Let's bypass while PM operations are in progress.
6395 	 */
6396 	switch (event) {
6397 	case PM_HIBERNATION_PREPARE:
6398 	case PM_SUSPEND_PREPARE:
6399 	case PM_RESTORE_PREPARE:
6400 		scx_bypass(true);
6401 		break;
6402 	case PM_POST_HIBERNATION:
6403 	case PM_POST_SUSPEND:
6404 	case PM_POST_RESTORE:
6405 		scx_bypass(false);
6406 		break;
6407 	}
6408 
6409 	return NOTIFY_OK;
6410 }
6411 
6412 static struct notifier_block scx_pm_notifier = {
6413 	.notifier_call = scx_pm_handler,
6414 };
6415 
6416 void __init init_sched_ext_class(void)
6417 {
6418 	s32 cpu, v;
6419 
6420 	/*
6421 	 * The following is to prevent the compiler from optimizing out the enum
6422 	 * definitions so that BPF scheduler implementations can use them
6423 	 * through the generated vmlinux.h.
6424 	 */
6425 	WRITE_ONCE(v, SCX_ENQ_WAKEUP | SCX_DEQ_SLEEP | SCX_KICK_PREEMPT |
6426 		   SCX_TG_ONLINE);
6427 
6428 	scx_idle_init_masks();
6429 
6430 	for_each_possible_cpu(cpu) {
6431 		struct rq *rq = cpu_rq(cpu);
6432 		int  n = cpu_to_node(cpu);
6433 
6434 		/* local/bypass dsq's sch will be set during scx_root_enable() */
6435 		init_dsq(&rq->scx.local_dsq, SCX_DSQ_LOCAL, NULL);
6436 		init_dsq(&rq->scx.bypass_dsq, SCX_DSQ_BYPASS, NULL);
6437 
6438 		INIT_LIST_HEAD(&rq->scx.runnable_list);
6439 		INIT_LIST_HEAD(&rq->scx.ddsp_deferred_locals);
6440 
6441 		BUG_ON(!zalloc_cpumask_var_node(&rq->scx.cpus_to_kick, GFP_KERNEL, n));
6442 		BUG_ON(!zalloc_cpumask_var_node(&rq->scx.cpus_to_kick_if_idle, GFP_KERNEL, n));
6443 		BUG_ON(!zalloc_cpumask_var_node(&rq->scx.cpus_to_preempt, GFP_KERNEL, n));
6444 		BUG_ON(!zalloc_cpumask_var_node(&rq->scx.cpus_to_wait, GFP_KERNEL, n));
6445 		rq->scx.deferred_irq_work = IRQ_WORK_INIT_HARD(deferred_irq_workfn);
6446 		rq->scx.kick_cpus_irq_work = IRQ_WORK_INIT_HARD(kick_cpus_irq_workfn);
6447 
6448 		if (cpu_online(cpu))
6449 			cpu_rq(cpu)->scx.flags |= SCX_RQ_ONLINE;
6450 	}
6451 
6452 	register_sysrq_key('S', &sysrq_sched_ext_reset_op);
6453 	register_sysrq_key('D', &sysrq_sched_ext_dump_op);
6454 	INIT_DELAYED_WORK(&scx_watchdog_work, scx_watchdog_workfn);
6455 }
6456 
6457 
6458 /********************************************************************************
6459  * Helpers that can be called from the BPF scheduler.
6460  */
6461 static bool scx_dsq_insert_preamble(struct scx_sched *sch, struct task_struct *p,
6462 				    u64 enq_flags)
6463 {
6464 	if (!scx_kf_allowed(sch, SCX_KF_ENQUEUE | SCX_KF_DISPATCH))
6465 		return false;
6466 
6467 	lockdep_assert_irqs_disabled();
6468 
6469 	if (unlikely(!p)) {
6470 		scx_error(sch, "called with NULL task");
6471 		return false;
6472 	}
6473 
6474 	if (unlikely(enq_flags & __SCX_ENQ_INTERNAL_MASK)) {
6475 		scx_error(sch, "invalid enq_flags 0x%llx", enq_flags);
6476 		return false;
6477 	}
6478 
6479 	return true;
6480 }
6481 
6482 static void scx_dsq_insert_commit(struct scx_sched *sch, struct task_struct *p,
6483 				  u64 dsq_id, u64 enq_flags)
6484 {
6485 	struct scx_dsp_ctx *dspc = this_cpu_ptr(scx_dsp_ctx);
6486 	struct task_struct *ddsp_task;
6487 
6488 	ddsp_task = __this_cpu_read(direct_dispatch_task);
6489 	if (ddsp_task) {
6490 		mark_direct_dispatch(sch, ddsp_task, p, dsq_id, enq_flags);
6491 		return;
6492 	}
6493 
6494 	if (unlikely(dspc->cursor >= scx_dsp_max_batch)) {
6495 		scx_error(sch, "dispatch buffer overflow");
6496 		return;
6497 	}
6498 
6499 	dspc->buf[dspc->cursor++] = (struct scx_dsp_buf_ent){
6500 		.task = p,
6501 		.qseq = atomic_long_read(&p->scx.ops_state) & SCX_OPSS_QSEQ_MASK,
6502 		.dsq_id = dsq_id,
6503 		.enq_flags = enq_flags,
6504 	};
6505 }
6506 
6507 __bpf_kfunc_start_defs();
6508 
6509 /**
6510  * scx_bpf_dsq_insert - Insert a task into the FIFO queue of a DSQ
6511  * @p: task_struct to insert
6512  * @dsq_id: DSQ to insert into
6513  * @slice: duration @p can run for in nsecs, 0 to keep the current value
6514  * @enq_flags: SCX_ENQ_*
6515  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
6516  *
6517  * Insert @p into the FIFO queue of the DSQ identified by @dsq_id. It is safe to
6518  * call this function spuriously. Can be called from ops.enqueue(),
6519  * ops.select_cpu(), and ops.dispatch().
6520  *
6521  * When called from ops.select_cpu() or ops.enqueue(), it's for direct dispatch
6522  * and @p must match the task being enqueued.
6523  *
6524  * When called from ops.select_cpu(), @enq_flags and @dsp_id are stored, and @p
6525  * will be directly inserted into the corresponding dispatch queue after
6526  * ops.select_cpu() returns. If @p is inserted into SCX_DSQ_LOCAL, it will be
6527  * inserted into the local DSQ of the CPU returned by ops.select_cpu().
6528  * @enq_flags are OR'd with the enqueue flags on the enqueue path before the
6529  * task is inserted.
6530  *
6531  * When called from ops.dispatch(), there are no restrictions on @p or @dsq_id
6532  * and this function can be called upto ops.dispatch_max_batch times to insert
6533  * multiple tasks. scx_bpf_dispatch_nr_slots() returns the number of the
6534  * remaining slots. scx_bpf_dsq_move_to_local() flushes the batch and resets the
6535  * counter.
6536  *
6537  * This function doesn't have any locking restrictions and may be called under
6538  * BPF locks (in the future when BPF introduces more flexible locking).
6539  *
6540  * @p is allowed to run for @slice. The scheduling path is triggered on slice
6541  * exhaustion. If zero, the current residual slice is maintained. If
6542  * %SCX_SLICE_INF, @p never expires and the BPF scheduler must kick the CPU with
6543  * scx_bpf_kick_cpu() to trigger scheduling.
6544  *
6545  * Returns %true on successful insertion, %false on failure. On the root
6546  * scheduler, %false return triggers scheduler abort and the caller doesn't need
6547  * to check the return value.
6548  */
6549 __bpf_kfunc bool scx_bpf_dsq_insert___v2(struct task_struct *p, u64 dsq_id,
6550 					 u64 slice, u64 enq_flags,
6551 					 const struct bpf_prog_aux *aux)
6552 {
6553 	struct scx_sched *sch;
6554 
6555 	guard(rcu)();
6556 	sch = scx_prog_sched(aux);
6557 	if (unlikely(!sch))
6558 		return false;
6559 
6560 	if (!scx_dsq_insert_preamble(sch, p, enq_flags))
6561 		return false;
6562 
6563 	if (slice)
6564 		p->scx.slice = slice;
6565 	else
6566 		p->scx.slice = p->scx.slice ?: 1;
6567 
6568 	scx_dsq_insert_commit(sch, p, dsq_id, enq_flags);
6569 
6570 	return true;
6571 }
6572 
6573 /*
6574  * COMPAT: Will be removed in v6.23 along with the ___v2 suffix.
6575  */
6576 __bpf_kfunc void scx_bpf_dsq_insert(struct task_struct *p, u64 dsq_id,
6577 				    u64 slice, u64 enq_flags,
6578 				    const struct bpf_prog_aux *aux)
6579 {
6580 	scx_bpf_dsq_insert___v2(p, dsq_id, slice, enq_flags, aux);
6581 }
6582 
6583 static bool scx_dsq_insert_vtime(struct scx_sched *sch, struct task_struct *p,
6584 				 u64 dsq_id, u64 slice, u64 vtime, u64 enq_flags)
6585 {
6586 	if (!scx_dsq_insert_preamble(sch, p, enq_flags))
6587 		return false;
6588 
6589 	if (slice)
6590 		p->scx.slice = slice;
6591 	else
6592 		p->scx.slice = p->scx.slice ?: 1;
6593 
6594 	p->scx.dsq_vtime = vtime;
6595 
6596 	scx_dsq_insert_commit(sch, p, dsq_id, enq_flags | SCX_ENQ_DSQ_PRIQ);
6597 
6598 	return true;
6599 }
6600 
6601 struct scx_bpf_dsq_insert_vtime_args {
6602 	/* @p can't be packed together as KF_RCU is not transitive */
6603 	u64			dsq_id;
6604 	u64			slice;
6605 	u64			vtime;
6606 	u64			enq_flags;
6607 };
6608 
6609 /**
6610  * __scx_bpf_dsq_insert_vtime - Arg-wrapped vtime DSQ insertion
6611  * @p: task_struct to insert
6612  * @args: struct containing the rest of the arguments
6613  *       @args->dsq_id: DSQ to insert into
6614  *       @args->slice: duration @p can run for in nsecs, 0 to keep the current value
6615  *       @args->vtime: @p's ordering inside the vtime-sorted queue of the target DSQ
6616  *       @args->enq_flags: SCX_ENQ_*
6617  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
6618  *
6619  * Wrapper kfunc that takes arguments via struct to work around BPF's 5 argument
6620  * limit. BPF programs should use scx_bpf_dsq_insert_vtime() which is provided
6621  * as an inline wrapper in common.bpf.h.
6622  *
6623  * Insert @p into the vtime priority queue of the DSQ identified by
6624  * @args->dsq_id. Tasks queued into the priority queue are ordered by
6625  * @args->vtime. All other aspects are identical to scx_bpf_dsq_insert().
6626  *
6627  * @args->vtime ordering is according to time_before64() which considers
6628  * wrapping. A numerically larger vtime may indicate an earlier position in the
6629  * ordering and vice-versa.
6630  *
6631  * A DSQ can only be used as a FIFO or priority queue at any given time and this
6632  * function must not be called on a DSQ which already has one or more FIFO tasks
6633  * queued and vice-versa. Also, the built-in DSQs (SCX_DSQ_LOCAL and
6634  * SCX_DSQ_GLOBAL) cannot be used as priority queues.
6635  *
6636  * Returns %true on successful insertion, %false on failure. On the root
6637  * scheduler, %false return triggers scheduler abort and the caller doesn't need
6638  * to check the return value.
6639  */
6640 __bpf_kfunc bool
6641 __scx_bpf_dsq_insert_vtime(struct task_struct *p,
6642 			   struct scx_bpf_dsq_insert_vtime_args *args,
6643 			   const struct bpf_prog_aux *aux)
6644 {
6645 	struct scx_sched *sch;
6646 
6647 	guard(rcu)();
6648 
6649 	sch = scx_prog_sched(aux);
6650 	if (unlikely(!sch))
6651 		return false;
6652 
6653 	return scx_dsq_insert_vtime(sch, p, args->dsq_id, args->slice,
6654 				    args->vtime, args->enq_flags);
6655 }
6656 
6657 /*
6658  * COMPAT: Will be removed in v6.23.
6659  */
6660 __bpf_kfunc void scx_bpf_dsq_insert_vtime(struct task_struct *p, u64 dsq_id,
6661 					  u64 slice, u64 vtime, u64 enq_flags)
6662 {
6663 	struct scx_sched *sch;
6664 
6665 	guard(rcu)();
6666 
6667 	sch = rcu_dereference(scx_root);
6668 	if (unlikely(!sch))
6669 		return;
6670 
6671 	scx_dsq_insert_vtime(sch, p, dsq_id, slice, vtime, enq_flags);
6672 }
6673 
6674 __bpf_kfunc_end_defs();
6675 
6676 BTF_KFUNCS_START(scx_kfunc_ids_enqueue_dispatch)
6677 BTF_ID_FLAGS(func, scx_bpf_dsq_insert, KF_IMPLICIT_ARGS | KF_RCU)
6678 BTF_ID_FLAGS(func, scx_bpf_dsq_insert___v2, KF_IMPLICIT_ARGS | KF_RCU)
6679 BTF_ID_FLAGS(func, __scx_bpf_dsq_insert_vtime, KF_IMPLICIT_ARGS | KF_RCU)
6680 BTF_ID_FLAGS(func, scx_bpf_dsq_insert_vtime, KF_RCU)
6681 BTF_KFUNCS_END(scx_kfunc_ids_enqueue_dispatch)
6682 
6683 static const struct btf_kfunc_id_set scx_kfunc_set_enqueue_dispatch = {
6684 	.owner			= THIS_MODULE,
6685 	.set			= &scx_kfunc_ids_enqueue_dispatch,
6686 };
6687 
6688 static bool scx_dsq_move(struct bpf_iter_scx_dsq_kern *kit,
6689 			 struct task_struct *p, u64 dsq_id, u64 enq_flags)
6690 {
6691 	struct scx_sched *sch = scx_root;
6692 	struct scx_dispatch_q *src_dsq = kit->dsq, *dst_dsq;
6693 	struct rq *this_rq, *src_rq, *locked_rq;
6694 	bool dispatched = false;
6695 	bool in_balance;
6696 	unsigned long flags;
6697 
6698 	if (!scx_kf_allowed_if_unlocked() &&
6699 	    !scx_kf_allowed(sch, SCX_KF_DISPATCH))
6700 		return false;
6701 
6702 	/*
6703 	 * If the BPF scheduler keeps calling this function repeatedly, it can
6704 	 * cause similar live-lock conditions as consume_dispatch_q().
6705 	 */
6706 	if (unlikely(READ_ONCE(scx_aborting)))
6707 		return false;
6708 
6709 	/*
6710 	 * Can be called from either ops.dispatch() locking this_rq() or any
6711 	 * context where no rq lock is held. If latter, lock @p's task_rq which
6712 	 * we'll likely need anyway.
6713 	 */
6714 	src_rq = task_rq(p);
6715 
6716 	local_irq_save(flags);
6717 	this_rq = this_rq();
6718 	in_balance = this_rq->scx.flags & SCX_RQ_IN_BALANCE;
6719 
6720 	if (in_balance) {
6721 		if (this_rq != src_rq) {
6722 			raw_spin_rq_unlock(this_rq);
6723 			raw_spin_rq_lock(src_rq);
6724 		}
6725 	} else {
6726 		raw_spin_rq_lock(src_rq);
6727 	}
6728 
6729 	locked_rq = src_rq;
6730 	raw_spin_lock(&src_dsq->lock);
6731 
6732 	/*
6733 	 * Did someone else get to it? @p could have already left $src_dsq, got
6734 	 * re-enqueud, or be in the process of being consumed by someone else.
6735 	 */
6736 	if (unlikely(p->scx.dsq != src_dsq ||
6737 		     u32_before(kit->cursor.priv, p->scx.dsq_seq) ||
6738 		     p->scx.holding_cpu >= 0) ||
6739 	    WARN_ON_ONCE(src_rq != task_rq(p))) {
6740 		raw_spin_unlock(&src_dsq->lock);
6741 		goto out;
6742 	}
6743 
6744 	/* @p is still on $src_dsq and stable, determine the destination */
6745 	dst_dsq = find_dsq_for_dispatch(sch, this_rq, dsq_id, p);
6746 
6747 	/*
6748 	 * Apply vtime and slice updates before moving so that the new time is
6749 	 * visible before inserting into $dst_dsq. @p is still on $src_dsq but
6750 	 * this is safe as we're locking it.
6751 	 */
6752 	if (kit->cursor.flags & __SCX_DSQ_ITER_HAS_VTIME)
6753 		p->scx.dsq_vtime = kit->vtime;
6754 	if (kit->cursor.flags & __SCX_DSQ_ITER_HAS_SLICE)
6755 		p->scx.slice = kit->slice;
6756 
6757 	/* execute move */
6758 	locked_rq = move_task_between_dsqs(sch, p, enq_flags, src_dsq, dst_dsq);
6759 	dispatched = true;
6760 out:
6761 	if (in_balance) {
6762 		if (this_rq != locked_rq) {
6763 			raw_spin_rq_unlock(locked_rq);
6764 			raw_spin_rq_lock(this_rq);
6765 		}
6766 	} else {
6767 		raw_spin_rq_unlock_irqrestore(locked_rq, flags);
6768 	}
6769 
6770 	kit->cursor.flags &= ~(__SCX_DSQ_ITER_HAS_SLICE |
6771 			       __SCX_DSQ_ITER_HAS_VTIME);
6772 	return dispatched;
6773 }
6774 
6775 __bpf_kfunc_start_defs();
6776 
6777 /**
6778  * scx_bpf_dispatch_nr_slots - Return the number of remaining dispatch slots
6779  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
6780  *
6781  * Can only be called from ops.dispatch().
6782  */
6783 __bpf_kfunc u32 scx_bpf_dispatch_nr_slots(const struct bpf_prog_aux *aux)
6784 {
6785 	struct scx_sched *sch;
6786 
6787 	guard(rcu)();
6788 
6789 	sch = scx_prog_sched(aux);
6790 	if (unlikely(!sch))
6791 		return 0;
6792 
6793 	if (!scx_kf_allowed(sch, SCX_KF_DISPATCH))
6794 		return 0;
6795 
6796 	return scx_dsp_max_batch - __this_cpu_read(scx_dsp_ctx->cursor);
6797 }
6798 
6799 /**
6800  * scx_bpf_dispatch_cancel - Cancel the latest dispatch
6801  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
6802  *
6803  * Cancel the latest dispatch. Can be called multiple times to cancel further
6804  * dispatches. Can only be called from ops.dispatch().
6805  */
6806 __bpf_kfunc void scx_bpf_dispatch_cancel(const struct bpf_prog_aux *aux)
6807 {
6808 	struct scx_dsp_ctx *dspc = this_cpu_ptr(scx_dsp_ctx);
6809 	struct scx_sched *sch;
6810 
6811 	guard(rcu)();
6812 
6813 	sch = scx_prog_sched(aux);
6814 	if (unlikely(!sch))
6815 		return;
6816 
6817 	if (!scx_kf_allowed(sch, SCX_KF_DISPATCH))
6818 		return;
6819 
6820 	if (dspc->cursor > 0)
6821 		dspc->cursor--;
6822 	else
6823 		scx_error(sch, "dispatch buffer underflow");
6824 }
6825 
6826 /**
6827  * scx_bpf_dsq_move_to_local - move a task from a DSQ to the current CPU's local DSQ
6828  * @dsq_id: DSQ to move task from
6829  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
6830  *
6831  * Move a task from the non-local DSQ identified by @dsq_id to the current CPU's
6832  * local DSQ for execution. Can only be called from ops.dispatch().
6833  *
6834  * This function flushes the in-flight dispatches from scx_bpf_dsq_insert()
6835  * before trying to move from the specified DSQ. It may also grab rq locks and
6836  * thus can't be called under any BPF locks.
6837  *
6838  * Returns %true if a task has been moved, %false if there isn't any task to
6839  * move.
6840  */
6841 __bpf_kfunc bool scx_bpf_dsq_move_to_local(u64 dsq_id, const struct bpf_prog_aux *aux)
6842 {
6843 	struct scx_dsp_ctx *dspc = this_cpu_ptr(scx_dsp_ctx);
6844 	struct scx_dispatch_q *dsq;
6845 	struct scx_sched *sch;
6846 
6847 	guard(rcu)();
6848 
6849 	sch = scx_prog_sched(aux);
6850 	if (unlikely(!sch))
6851 		return false;
6852 
6853 	if (!scx_kf_allowed(sch, SCX_KF_DISPATCH))
6854 		return false;
6855 
6856 	flush_dispatch_buf(sch, dspc->rq);
6857 
6858 	dsq = find_user_dsq(sch, dsq_id);
6859 	if (unlikely(!dsq)) {
6860 		scx_error(sch, "invalid DSQ ID 0x%016llx", dsq_id);
6861 		return false;
6862 	}
6863 
6864 	if (consume_dispatch_q(sch, dspc->rq, dsq)) {
6865 		/*
6866 		 * A successfully consumed task can be dequeued before it starts
6867 		 * running while the CPU is trying to migrate other dispatched
6868 		 * tasks. Bump nr_tasks to tell balance_one() to retry on empty
6869 		 * local DSQ.
6870 		 */
6871 		dspc->nr_tasks++;
6872 		return true;
6873 	} else {
6874 		return false;
6875 	}
6876 }
6877 
6878 /**
6879  * scx_bpf_dsq_move_set_slice - Override slice when moving between DSQs
6880  * @it__iter: DSQ iterator in progress
6881  * @slice: duration the moved task can run for in nsecs
6882  *
6883  * Override the slice of the next task that will be moved from @it__iter using
6884  * scx_bpf_dsq_move[_vtime](). If this function is not called, the previous
6885  * slice duration is kept.
6886  */
6887 __bpf_kfunc void scx_bpf_dsq_move_set_slice(struct bpf_iter_scx_dsq *it__iter,
6888 					    u64 slice)
6889 {
6890 	struct bpf_iter_scx_dsq_kern *kit = (void *)it__iter;
6891 
6892 	kit->slice = slice;
6893 	kit->cursor.flags |= __SCX_DSQ_ITER_HAS_SLICE;
6894 }
6895 
6896 /**
6897  * scx_bpf_dsq_move_set_vtime - Override vtime when moving between DSQs
6898  * @it__iter: DSQ iterator in progress
6899  * @vtime: task's ordering inside the vtime-sorted queue of the target DSQ
6900  *
6901  * Override the vtime of the next task that will be moved from @it__iter using
6902  * scx_bpf_dsq_move_vtime(). If this function is not called, the previous slice
6903  * vtime is kept. If scx_bpf_dsq_move() is used to dispatch the next task, the
6904  * override is ignored and cleared.
6905  */
6906 __bpf_kfunc void scx_bpf_dsq_move_set_vtime(struct bpf_iter_scx_dsq *it__iter,
6907 					    u64 vtime)
6908 {
6909 	struct bpf_iter_scx_dsq_kern *kit = (void *)it__iter;
6910 
6911 	kit->vtime = vtime;
6912 	kit->cursor.flags |= __SCX_DSQ_ITER_HAS_VTIME;
6913 }
6914 
6915 /**
6916  * scx_bpf_dsq_move - Move a task from DSQ iteration to a DSQ
6917  * @it__iter: DSQ iterator in progress
6918  * @p: task to transfer
6919  * @dsq_id: DSQ to move @p to
6920  * @enq_flags: SCX_ENQ_*
6921  *
6922  * Transfer @p which is on the DSQ currently iterated by @it__iter to the DSQ
6923  * specified by @dsq_id. All DSQs - local DSQs, global DSQ and user DSQs - can
6924  * be the destination.
6925  *
6926  * For the transfer to be successful, @p must still be on the DSQ and have been
6927  * queued before the DSQ iteration started. This function doesn't care whether
6928  * @p was obtained from the DSQ iteration. @p just has to be on the DSQ and have
6929  * been queued before the iteration started.
6930  *
6931  * @p's slice is kept by default. Use scx_bpf_dsq_move_set_slice() to update.
6932  *
6933  * Can be called from ops.dispatch() or any BPF context which doesn't hold a rq
6934  * lock (e.g. BPF timers or SYSCALL programs).
6935  *
6936  * Returns %true if @p has been consumed, %false if @p had already been
6937  * consumed, dequeued, or, for sub-scheds, @dsq_id points to a disallowed local
6938  * DSQ.
6939  */
6940 __bpf_kfunc bool scx_bpf_dsq_move(struct bpf_iter_scx_dsq *it__iter,
6941 				  struct task_struct *p, u64 dsq_id,
6942 				  u64 enq_flags)
6943 {
6944 	return scx_dsq_move((struct bpf_iter_scx_dsq_kern *)it__iter,
6945 			    p, dsq_id, enq_flags);
6946 }
6947 
6948 /**
6949  * scx_bpf_dsq_move_vtime - Move a task from DSQ iteration to a PRIQ DSQ
6950  * @it__iter: DSQ iterator in progress
6951  * @p: task to transfer
6952  * @dsq_id: DSQ to move @p to
6953  * @enq_flags: SCX_ENQ_*
6954  *
6955  * Transfer @p which is on the DSQ currently iterated by @it__iter to the
6956  * priority queue of the DSQ specified by @dsq_id. The destination must be a
6957  * user DSQ as only user DSQs support priority queue.
6958  *
6959  * @p's slice and vtime are kept by default. Use scx_bpf_dsq_move_set_slice()
6960  * and scx_bpf_dsq_move_set_vtime() to update.
6961  *
6962  * All other aspects are identical to scx_bpf_dsq_move(). See
6963  * scx_bpf_dsq_insert_vtime() for more information on @vtime.
6964  */
6965 __bpf_kfunc bool scx_bpf_dsq_move_vtime(struct bpf_iter_scx_dsq *it__iter,
6966 					struct task_struct *p, u64 dsq_id,
6967 					u64 enq_flags)
6968 {
6969 	return scx_dsq_move((struct bpf_iter_scx_dsq_kern *)it__iter,
6970 			    p, dsq_id, enq_flags | SCX_ENQ_DSQ_PRIQ);
6971 }
6972 
6973 __bpf_kfunc_end_defs();
6974 
6975 BTF_KFUNCS_START(scx_kfunc_ids_dispatch)
6976 BTF_ID_FLAGS(func, scx_bpf_dispatch_nr_slots, KF_IMPLICIT_ARGS)
6977 BTF_ID_FLAGS(func, scx_bpf_dispatch_cancel, KF_IMPLICIT_ARGS)
6978 BTF_ID_FLAGS(func, scx_bpf_dsq_move_to_local, KF_IMPLICIT_ARGS)
6979 BTF_ID_FLAGS(func, scx_bpf_dsq_move_set_slice, KF_RCU)
6980 BTF_ID_FLAGS(func, scx_bpf_dsq_move_set_vtime, KF_RCU)
6981 BTF_ID_FLAGS(func, scx_bpf_dsq_move, KF_RCU)
6982 BTF_ID_FLAGS(func, scx_bpf_dsq_move_vtime, KF_RCU)
6983 BTF_KFUNCS_END(scx_kfunc_ids_dispatch)
6984 
6985 static const struct btf_kfunc_id_set scx_kfunc_set_dispatch = {
6986 	.owner			= THIS_MODULE,
6987 	.set			= &scx_kfunc_ids_dispatch,
6988 };
6989 
6990 static u32 reenq_local(struct rq *rq)
6991 {
6992 	LIST_HEAD(tasks);
6993 	u32 nr_enqueued = 0;
6994 	struct task_struct *p, *n;
6995 
6996 	lockdep_assert_rq_held(rq);
6997 
6998 	/*
6999 	 * The BPF scheduler may choose to dispatch tasks back to
7000 	 * @rq->scx.local_dsq. Move all candidate tasks off to a private list
7001 	 * first to avoid processing the same tasks repeatedly.
7002 	 */
7003 	list_for_each_entry_safe(p, n, &rq->scx.local_dsq.list,
7004 				 scx.dsq_list.node) {
7005 		/*
7006 		 * If @p is being migrated, @p's current CPU may not agree with
7007 		 * its allowed CPUs and the migration_cpu_stop is about to
7008 		 * deactivate and re-activate @p anyway. Skip re-enqueueing.
7009 		 *
7010 		 * While racing sched property changes may also dequeue and
7011 		 * re-enqueue a migrating task while its current CPU and allowed
7012 		 * CPUs disagree, they use %ENQUEUE_RESTORE which is bypassed to
7013 		 * the current local DSQ for running tasks and thus are not
7014 		 * visible to the BPF scheduler.
7015 		 */
7016 		if (p->migration_pending)
7017 			continue;
7018 
7019 		dispatch_dequeue(rq, p);
7020 		list_add_tail(&p->scx.dsq_list.node, &tasks);
7021 	}
7022 
7023 	list_for_each_entry_safe(p, n, &tasks, scx.dsq_list.node) {
7024 		list_del_init(&p->scx.dsq_list.node);
7025 		do_enqueue_task(rq, p, SCX_ENQ_REENQ, -1);
7026 		nr_enqueued++;
7027 	}
7028 
7029 	return nr_enqueued;
7030 }
7031 
7032 __bpf_kfunc_start_defs();
7033 
7034 /**
7035  * scx_bpf_reenqueue_local - Re-enqueue tasks on a local DSQ
7036  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
7037  *
7038  * Iterate over all of the tasks currently enqueued on the local DSQ of the
7039  * caller's CPU, and re-enqueue them in the BPF scheduler. Returns the number of
7040  * processed tasks. Can only be called from ops.cpu_release().
7041  *
7042  * COMPAT: Will be removed in v6.23 along with the ___v2 suffix on the void
7043  * returning variant that can be called from anywhere.
7044  */
7045 __bpf_kfunc u32 scx_bpf_reenqueue_local(const struct bpf_prog_aux *aux)
7046 {
7047 	struct scx_sched *sch;
7048 	struct rq *rq;
7049 
7050 	guard(rcu)();
7051 	sch = scx_prog_sched(aux);
7052 	if (unlikely(!sch))
7053 		return 0;
7054 
7055 	if (!scx_kf_allowed(sch, SCX_KF_CPU_RELEASE))
7056 		return 0;
7057 
7058 	rq = cpu_rq(smp_processor_id());
7059 	lockdep_assert_rq_held(rq);
7060 
7061 	return reenq_local(rq);
7062 }
7063 
7064 __bpf_kfunc_end_defs();
7065 
7066 BTF_KFUNCS_START(scx_kfunc_ids_cpu_release)
7067 BTF_ID_FLAGS(func, scx_bpf_reenqueue_local, KF_IMPLICIT_ARGS)
7068 BTF_KFUNCS_END(scx_kfunc_ids_cpu_release)
7069 
7070 static const struct btf_kfunc_id_set scx_kfunc_set_cpu_release = {
7071 	.owner			= THIS_MODULE,
7072 	.set			= &scx_kfunc_ids_cpu_release,
7073 };
7074 
7075 __bpf_kfunc_start_defs();
7076 
7077 /**
7078  * scx_bpf_create_dsq - Create a custom DSQ
7079  * @dsq_id: DSQ to create
7080  * @node: NUMA node to allocate from
7081  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
7082  *
7083  * Create a custom DSQ identified by @dsq_id. Can be called from any sleepable
7084  * scx callback, and any BPF_PROG_TYPE_SYSCALL prog.
7085  */
7086 __bpf_kfunc s32 scx_bpf_create_dsq(u64 dsq_id, s32 node, const struct bpf_prog_aux *aux)
7087 {
7088 	struct scx_dispatch_q *dsq;
7089 	struct scx_sched *sch;
7090 	s32 ret;
7091 
7092 	if (unlikely(node >= (int)nr_node_ids ||
7093 		     (node < 0 && node != NUMA_NO_NODE)))
7094 		return -EINVAL;
7095 
7096 	if (unlikely(dsq_id & SCX_DSQ_FLAG_BUILTIN))
7097 		return -EINVAL;
7098 
7099 	dsq = kmalloc_node(sizeof(*dsq), GFP_KERNEL, node);
7100 	if (!dsq)
7101 		return -ENOMEM;
7102 
7103 	rcu_read_lock();
7104 
7105 	sch = scx_prog_sched(aux);
7106 	if (sch) {
7107 		init_dsq(dsq, dsq_id, sch);
7108 		ret = rhashtable_lookup_insert_fast(&sch->dsq_hash, &dsq->hash_node,
7109 						    dsq_hash_params);
7110 	} else {
7111 		ret = -ENODEV;
7112 	}
7113 
7114 	rcu_read_unlock();
7115 	if (ret)
7116 		kfree(dsq);
7117 	return ret;
7118 }
7119 
7120 __bpf_kfunc_end_defs();
7121 
7122 BTF_KFUNCS_START(scx_kfunc_ids_unlocked)
7123 BTF_ID_FLAGS(func, scx_bpf_create_dsq, KF_IMPLICIT_ARGS | KF_SLEEPABLE)
7124 BTF_ID_FLAGS(func, scx_bpf_dsq_move_set_slice, KF_RCU)
7125 BTF_ID_FLAGS(func, scx_bpf_dsq_move_set_vtime, KF_RCU)
7126 BTF_ID_FLAGS(func, scx_bpf_dsq_move, KF_RCU)
7127 BTF_ID_FLAGS(func, scx_bpf_dsq_move_vtime, KF_RCU)
7128 BTF_KFUNCS_END(scx_kfunc_ids_unlocked)
7129 
7130 static const struct btf_kfunc_id_set scx_kfunc_set_unlocked = {
7131 	.owner			= THIS_MODULE,
7132 	.set			= &scx_kfunc_ids_unlocked,
7133 };
7134 
7135 __bpf_kfunc_start_defs();
7136 
7137 /**
7138  * scx_bpf_task_set_slice - Set task's time slice
7139  * @p: task of interest
7140  * @slice: time slice to set in nsecs
7141  *
7142  * Set @p's time slice to @slice. Returns %true on success, %false if the
7143  * calling scheduler doesn't have authority over @p.
7144  */
7145 __bpf_kfunc bool scx_bpf_task_set_slice(struct task_struct *p, u64 slice)
7146 {
7147 	p->scx.slice = slice;
7148 	return true;
7149 }
7150 
7151 /**
7152  * scx_bpf_task_set_dsq_vtime - Set task's virtual time for DSQ ordering
7153  * @p: task of interest
7154  * @vtime: virtual time to set
7155  *
7156  * Set @p's virtual time to @vtime. Returns %true on success, %false if the
7157  * calling scheduler doesn't have authority over @p.
7158  */
7159 __bpf_kfunc bool scx_bpf_task_set_dsq_vtime(struct task_struct *p, u64 vtime)
7160 {
7161 	p->scx.dsq_vtime = vtime;
7162 	return true;
7163 }
7164 
7165 static void scx_kick_cpu(struct scx_sched *sch, s32 cpu, u64 flags)
7166 {
7167 	struct rq *this_rq;
7168 	unsigned long irq_flags;
7169 
7170 	if (!ops_cpu_valid(sch, cpu, NULL))
7171 		return;
7172 
7173 	local_irq_save(irq_flags);
7174 
7175 	this_rq = this_rq();
7176 
7177 	/*
7178 	 * While bypassing for PM ops, IRQ handling may not be online which can
7179 	 * lead to irq_work_queue() malfunction such as infinite busy wait for
7180 	 * IRQ status update. Suppress kicking.
7181 	 */
7182 	if (scx_rq_bypassing(this_rq))
7183 		goto out;
7184 
7185 	/*
7186 	 * Actual kicking is bounced to kick_cpus_irq_workfn() to avoid nesting
7187 	 * rq locks. We can probably be smarter and avoid bouncing if called
7188 	 * from ops which don't hold a rq lock.
7189 	 */
7190 	if (flags & SCX_KICK_IDLE) {
7191 		struct rq *target_rq = cpu_rq(cpu);
7192 
7193 		if (unlikely(flags & (SCX_KICK_PREEMPT | SCX_KICK_WAIT)))
7194 			scx_error(sch, "PREEMPT/WAIT cannot be used with SCX_KICK_IDLE");
7195 
7196 		if (raw_spin_rq_trylock(target_rq)) {
7197 			if (can_skip_idle_kick(target_rq)) {
7198 				raw_spin_rq_unlock(target_rq);
7199 				goto out;
7200 			}
7201 			raw_spin_rq_unlock(target_rq);
7202 		}
7203 		cpumask_set_cpu(cpu, this_rq->scx.cpus_to_kick_if_idle);
7204 	} else {
7205 		cpumask_set_cpu(cpu, this_rq->scx.cpus_to_kick);
7206 
7207 		if (flags & SCX_KICK_PREEMPT)
7208 			cpumask_set_cpu(cpu, this_rq->scx.cpus_to_preempt);
7209 		if (flags & SCX_KICK_WAIT)
7210 			cpumask_set_cpu(cpu, this_rq->scx.cpus_to_wait);
7211 	}
7212 
7213 	irq_work_queue(&this_rq->scx.kick_cpus_irq_work);
7214 out:
7215 	local_irq_restore(irq_flags);
7216 }
7217 
7218 /**
7219  * scx_bpf_kick_cpu - Trigger reschedule on a CPU
7220  * @cpu: cpu to kick
7221  * @flags: %SCX_KICK_* flags
7222  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
7223  *
7224  * Kick @cpu into rescheduling. This can be used to wake up an idle CPU or
7225  * trigger rescheduling on a busy CPU. This can be called from any online
7226  * scx_ops operation and the actual kicking is performed asynchronously through
7227  * an irq work.
7228  */
7229 __bpf_kfunc void scx_bpf_kick_cpu(s32 cpu, u64 flags, const struct bpf_prog_aux *aux)
7230 {
7231 	struct scx_sched *sch;
7232 
7233 	guard(rcu)();
7234 	sch = scx_prog_sched(aux);
7235 	if (likely(sch))
7236 		scx_kick_cpu(sch, cpu, flags);
7237 }
7238 
7239 /**
7240  * scx_bpf_dsq_nr_queued - Return the number of queued tasks
7241  * @dsq_id: id of the DSQ
7242  *
7243  * Return the number of tasks in the DSQ matching @dsq_id. If not found,
7244  * -%ENOENT is returned.
7245  */
7246 __bpf_kfunc s32 scx_bpf_dsq_nr_queued(u64 dsq_id)
7247 {
7248 	struct scx_sched *sch;
7249 	struct scx_dispatch_q *dsq;
7250 	s32 ret;
7251 
7252 	preempt_disable();
7253 
7254 	sch = rcu_dereference_sched(scx_root);
7255 	if (unlikely(!sch)) {
7256 		ret = -ENODEV;
7257 		goto out;
7258 	}
7259 
7260 	if (dsq_id == SCX_DSQ_LOCAL) {
7261 		ret = READ_ONCE(this_rq()->scx.local_dsq.nr);
7262 		goto out;
7263 	} else if ((dsq_id & SCX_DSQ_LOCAL_ON) == SCX_DSQ_LOCAL_ON) {
7264 		s32 cpu = dsq_id & SCX_DSQ_LOCAL_CPU_MASK;
7265 
7266 		if (ops_cpu_valid(sch, cpu, NULL)) {
7267 			ret = READ_ONCE(cpu_rq(cpu)->scx.local_dsq.nr);
7268 			goto out;
7269 		}
7270 	} else {
7271 		dsq = find_user_dsq(sch, dsq_id);
7272 		if (dsq) {
7273 			ret = READ_ONCE(dsq->nr);
7274 			goto out;
7275 		}
7276 	}
7277 	ret = -ENOENT;
7278 out:
7279 	preempt_enable();
7280 	return ret;
7281 }
7282 
7283 /**
7284  * scx_bpf_destroy_dsq - Destroy a custom DSQ
7285  * @dsq_id: DSQ to destroy
7286  *
7287  * Destroy the custom DSQ identified by @dsq_id. Only DSQs created with
7288  * scx_bpf_create_dsq() can be destroyed. The caller must ensure that the DSQ is
7289  * empty and no further tasks are dispatched to it. Ignored if called on a DSQ
7290  * which doesn't exist. Can be called from any online scx_ops operations.
7291  */
7292 __bpf_kfunc void scx_bpf_destroy_dsq(u64 dsq_id)
7293 {
7294 	struct scx_sched *sch;
7295 
7296 	rcu_read_lock();
7297 	sch = rcu_dereference(scx_root);
7298 	if (sch)
7299 		destroy_dsq(sch, dsq_id);
7300 	rcu_read_unlock();
7301 }
7302 
7303 /**
7304  * bpf_iter_scx_dsq_new - Create a DSQ iterator
7305  * @it: iterator to initialize
7306  * @dsq_id: DSQ to iterate
7307  * @flags: %SCX_DSQ_ITER_*
7308  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
7309  *
7310  * Initialize BPF iterator @it which can be used with bpf_for_each() to walk
7311  * tasks in the DSQ specified by @dsq_id. Iteration using @it only includes
7312  * tasks which are already queued when this function is invoked.
7313  */
7314 __bpf_kfunc int bpf_iter_scx_dsq_new(struct bpf_iter_scx_dsq *it, u64 dsq_id,
7315 				     u64 flags, const struct bpf_prog_aux *aux)
7316 {
7317 	struct bpf_iter_scx_dsq_kern *kit = (void *)it;
7318 	struct scx_sched *sch;
7319 
7320 	BUILD_BUG_ON(sizeof(struct bpf_iter_scx_dsq_kern) >
7321 		     sizeof(struct bpf_iter_scx_dsq));
7322 	BUILD_BUG_ON(__alignof__(struct bpf_iter_scx_dsq_kern) !=
7323 		     __alignof__(struct bpf_iter_scx_dsq));
7324 	BUILD_BUG_ON(__SCX_DSQ_ITER_ALL_FLAGS &
7325 		     ((1U << __SCX_DSQ_LNODE_PRIV_SHIFT) - 1));
7326 
7327 	/*
7328 	 * next() and destroy() will be called regardless of the return value.
7329 	 * Always clear $kit->dsq.
7330 	 */
7331 	kit->dsq = NULL;
7332 
7333 	sch = scx_prog_sched(aux);
7334 	if (unlikely(!sch))
7335 		return -ENODEV;
7336 
7337 	if (flags & ~__SCX_DSQ_ITER_USER_FLAGS)
7338 		return -EINVAL;
7339 
7340 	kit->dsq = find_user_dsq(sch, dsq_id);
7341 	if (!kit->dsq)
7342 		return -ENOENT;
7343 
7344 	kit->cursor = INIT_DSQ_LIST_CURSOR(kit->cursor, flags,
7345 					   READ_ONCE(kit->dsq->seq));
7346 
7347 	return 0;
7348 }
7349 
7350 /**
7351  * bpf_iter_scx_dsq_next - Progress a DSQ iterator
7352  * @it: iterator to progress
7353  *
7354  * Return the next task. See bpf_iter_scx_dsq_new().
7355  */
7356 __bpf_kfunc struct task_struct *bpf_iter_scx_dsq_next(struct bpf_iter_scx_dsq *it)
7357 {
7358 	struct bpf_iter_scx_dsq_kern *kit = (void *)it;
7359 	bool rev = kit->cursor.flags & SCX_DSQ_ITER_REV;
7360 	struct task_struct *p;
7361 	unsigned long flags;
7362 
7363 	if (!kit->dsq)
7364 		return NULL;
7365 
7366 	raw_spin_lock_irqsave(&kit->dsq->lock, flags);
7367 
7368 	if (list_empty(&kit->cursor.node))
7369 		p = NULL;
7370 	else
7371 		p = container_of(&kit->cursor, struct task_struct, scx.dsq_list);
7372 
7373 	/*
7374 	 * Only tasks which were queued before the iteration started are
7375 	 * visible. This bounds BPF iterations and guarantees that vtime never
7376 	 * jumps in the other direction while iterating.
7377 	 */
7378 	do {
7379 		p = nldsq_next_task(kit->dsq, p, rev);
7380 	} while (p && unlikely(u32_before(kit->cursor.priv, p->scx.dsq_seq)));
7381 
7382 	if (p) {
7383 		if (rev)
7384 			list_move_tail(&kit->cursor.node, &p->scx.dsq_list.node);
7385 		else
7386 			list_move(&kit->cursor.node, &p->scx.dsq_list.node);
7387 	} else {
7388 		list_del_init(&kit->cursor.node);
7389 	}
7390 
7391 	raw_spin_unlock_irqrestore(&kit->dsq->lock, flags);
7392 
7393 	return p;
7394 }
7395 
7396 /**
7397  * bpf_iter_scx_dsq_destroy - Destroy a DSQ iterator
7398  * @it: iterator to destroy
7399  *
7400  * Undo scx_iter_scx_dsq_new().
7401  */
7402 __bpf_kfunc void bpf_iter_scx_dsq_destroy(struct bpf_iter_scx_dsq *it)
7403 {
7404 	struct bpf_iter_scx_dsq_kern *kit = (void *)it;
7405 
7406 	if (!kit->dsq)
7407 		return;
7408 
7409 	if (!list_empty(&kit->cursor.node)) {
7410 		unsigned long flags;
7411 
7412 		raw_spin_lock_irqsave(&kit->dsq->lock, flags);
7413 		list_del_init(&kit->cursor.node);
7414 		raw_spin_unlock_irqrestore(&kit->dsq->lock, flags);
7415 	}
7416 	kit->dsq = NULL;
7417 }
7418 
7419 /**
7420  * scx_bpf_dsq_peek - Lockless peek at the first element.
7421  * @dsq_id: DSQ to examine.
7422  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
7423  *
7424  * Read the first element in the DSQ. This is semantically equivalent to using
7425  * the DSQ iterator, but is lockfree. Of course, like any lockless operation,
7426  * this provides only a point-in-time snapshot, and the contents may change
7427  * by the time any subsequent locking operation reads the queue.
7428  *
7429  * Returns the pointer, or NULL indicates an empty queue OR internal error.
7430  */
7431 __bpf_kfunc struct task_struct *scx_bpf_dsq_peek(u64 dsq_id,
7432 						 const struct bpf_prog_aux *aux)
7433 {
7434 	struct scx_sched *sch;
7435 	struct scx_dispatch_q *dsq;
7436 
7437 	sch = scx_prog_sched(aux);
7438 	if (unlikely(!sch))
7439 		return NULL;
7440 
7441 	if (unlikely(dsq_id & SCX_DSQ_FLAG_BUILTIN)) {
7442 		scx_error(sch, "peek disallowed on builtin DSQ 0x%llx", dsq_id);
7443 		return NULL;
7444 	}
7445 
7446 	dsq = find_user_dsq(sch, dsq_id);
7447 	if (unlikely(!dsq)) {
7448 		scx_error(sch, "peek on non-existent DSQ 0x%llx", dsq_id);
7449 		return NULL;
7450 	}
7451 
7452 	return rcu_dereference(dsq->first_task);
7453 }
7454 
7455 __bpf_kfunc_end_defs();
7456 
7457 static s32 __bstr_format(struct scx_sched *sch, u64 *data_buf, char *line_buf,
7458 			 size_t line_size, char *fmt, unsigned long long *data,
7459 			 u32 data__sz)
7460 {
7461 	struct bpf_bprintf_data bprintf_data = { .get_bin_args = true };
7462 	s32 ret;
7463 
7464 	if (data__sz % 8 || data__sz > MAX_BPRINTF_VARARGS * 8 ||
7465 	    (data__sz && !data)) {
7466 		scx_error(sch, "invalid data=%p and data__sz=%u", (void *)data, data__sz);
7467 		return -EINVAL;
7468 	}
7469 
7470 	ret = copy_from_kernel_nofault(data_buf, data, data__sz);
7471 	if (ret < 0) {
7472 		scx_error(sch, "failed to read data fields (%d)", ret);
7473 		return ret;
7474 	}
7475 
7476 	ret = bpf_bprintf_prepare(fmt, UINT_MAX, data_buf, data__sz / 8,
7477 				  &bprintf_data);
7478 	if (ret < 0) {
7479 		scx_error(sch, "format preparation failed (%d)", ret);
7480 		return ret;
7481 	}
7482 
7483 	ret = bstr_printf(line_buf, line_size, fmt,
7484 			  bprintf_data.bin_args);
7485 	bpf_bprintf_cleanup(&bprintf_data);
7486 	if (ret < 0) {
7487 		scx_error(sch, "(\"%s\", %p, %u) failed to format", fmt, data, data__sz);
7488 		return ret;
7489 	}
7490 
7491 	return ret;
7492 }
7493 
7494 static s32 bstr_format(struct scx_sched *sch, struct scx_bstr_buf *buf,
7495 		       char *fmt, unsigned long long *data, u32 data__sz)
7496 {
7497 	return __bstr_format(sch, buf->data, buf->line, sizeof(buf->line),
7498 			     fmt, data, data__sz);
7499 }
7500 
7501 __bpf_kfunc_start_defs();
7502 
7503 /**
7504  * scx_bpf_exit_bstr - Gracefully exit the BPF scheduler.
7505  * @exit_code: Exit value to pass to user space via struct scx_exit_info.
7506  * @fmt: error message format string
7507  * @data: format string parameters packaged using ___bpf_fill() macro
7508  * @data__sz: @data len, must end in '__sz' for the verifier
7509  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
7510  *
7511  * Indicate that the BPF scheduler wants to exit gracefully, and initiate ops
7512  * disabling.
7513  */
7514 __bpf_kfunc void scx_bpf_exit_bstr(s64 exit_code, char *fmt,
7515 				   unsigned long long *data, u32 data__sz,
7516 				   const struct bpf_prog_aux *aux)
7517 {
7518 	struct scx_sched *sch;
7519 	unsigned long flags;
7520 
7521 	raw_spin_lock_irqsave(&scx_exit_bstr_buf_lock, flags);
7522 	sch = scx_prog_sched(aux);
7523 	if (likely(sch) &&
7524 	    bstr_format(sch, &scx_exit_bstr_buf, fmt, data, data__sz) >= 0)
7525 		scx_exit(sch, SCX_EXIT_UNREG_BPF, exit_code, "%s", scx_exit_bstr_buf.line);
7526 	raw_spin_unlock_irqrestore(&scx_exit_bstr_buf_lock, flags);
7527 }
7528 
7529 /**
7530  * scx_bpf_error_bstr - Indicate fatal error
7531  * @fmt: error message format string
7532  * @data: format string parameters packaged using ___bpf_fill() macro
7533  * @data__sz: @data len, must end in '__sz' for the verifier
7534  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
7535  *
7536  * Indicate that the BPF scheduler encountered a fatal error and initiate ops
7537  * disabling.
7538  */
7539 __bpf_kfunc void scx_bpf_error_bstr(char *fmt, unsigned long long *data,
7540 				    u32 data__sz, const struct bpf_prog_aux *aux)
7541 {
7542 	struct scx_sched *sch;
7543 	unsigned long flags;
7544 
7545 	raw_spin_lock_irqsave(&scx_exit_bstr_buf_lock, flags);
7546 	sch = scx_prog_sched(aux);
7547 	if (likely(sch) &&
7548 	    bstr_format(sch, &scx_exit_bstr_buf, fmt, data, data__sz) >= 0)
7549 		scx_exit(sch, SCX_EXIT_ERROR_BPF, 0, "%s", scx_exit_bstr_buf.line);
7550 	raw_spin_unlock_irqrestore(&scx_exit_bstr_buf_lock, flags);
7551 }
7552 
7553 /**
7554  * scx_bpf_dump_bstr - Generate extra debug dump specific to the BPF scheduler
7555  * @fmt: format string
7556  * @data: format string parameters packaged using ___bpf_fill() macro
7557  * @data__sz: @data len, must end in '__sz' for the verifier
7558  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
7559  *
7560  * To be called through scx_bpf_dump() helper from ops.dump(), dump_cpu() and
7561  * dump_task() to generate extra debug dump specific to the BPF scheduler.
7562  *
7563  * The extra dump may be multiple lines. A single line may be split over
7564  * multiple calls. The last line is automatically terminated.
7565  */
7566 __bpf_kfunc void scx_bpf_dump_bstr(char *fmt, unsigned long long *data,
7567 				   u32 data__sz, const struct bpf_prog_aux *aux)
7568 {
7569 	struct scx_sched *sch;
7570 	struct scx_dump_data *dd = &scx_dump_data;
7571 	struct scx_bstr_buf *buf = &dd->buf;
7572 	s32 ret;
7573 
7574 	guard(rcu)();
7575 
7576 	sch = scx_prog_sched(aux);
7577 	if (unlikely(!sch))
7578 		return;
7579 
7580 	if (raw_smp_processor_id() != dd->cpu) {
7581 		scx_error(sch, "scx_bpf_dump() must only be called from ops.dump() and friends");
7582 		return;
7583 	}
7584 
7585 	/* append the formatted string to the line buf */
7586 	ret = __bstr_format(sch, buf->data, buf->line + dd->cursor,
7587 			    sizeof(buf->line) - dd->cursor, fmt, data, data__sz);
7588 	if (ret < 0) {
7589 		dump_line(dd->s, "%s[!] (\"%s\", %p, %u) failed to format (%d)",
7590 			  dd->prefix, fmt, data, data__sz, ret);
7591 		return;
7592 	}
7593 
7594 	dd->cursor += ret;
7595 	dd->cursor = min_t(s32, dd->cursor, sizeof(buf->line));
7596 
7597 	if (!dd->cursor)
7598 		return;
7599 
7600 	/*
7601 	 * If the line buf overflowed or ends in a newline, flush it into the
7602 	 * dump. This is to allow the caller to generate a single line over
7603 	 * multiple calls. As ops_dump_flush() can also handle multiple lines in
7604 	 * the line buf, the only case which can lead to an unexpected
7605 	 * truncation is when the caller keeps generating newlines in the middle
7606 	 * instead of the end consecutively. Don't do that.
7607 	 */
7608 	if (dd->cursor >= sizeof(buf->line) || buf->line[dd->cursor - 1] == '\n')
7609 		ops_dump_flush();
7610 }
7611 
7612 /**
7613  * scx_bpf_reenqueue_local - Re-enqueue tasks on a local DSQ
7614  *
7615  * Iterate over all of the tasks currently enqueued on the local DSQ of the
7616  * caller's CPU, and re-enqueue them in the BPF scheduler. Can be called from
7617  * anywhere.
7618  */
7619 __bpf_kfunc void scx_bpf_reenqueue_local___v2(void)
7620 {
7621 	struct rq *rq;
7622 
7623 	guard(preempt)();
7624 
7625 	rq = this_rq();
7626 	local_set(&rq->scx.reenq_local_deferred, 1);
7627 	schedule_deferred(rq);
7628 }
7629 
7630 /**
7631  * scx_bpf_cpuperf_cap - Query the maximum relative capacity of a CPU
7632  * @cpu: CPU of interest
7633  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
7634  *
7635  * Return the maximum relative capacity of @cpu in relation to the most
7636  * performant CPU in the system. The return value is in the range [1,
7637  * %SCX_CPUPERF_ONE]. See scx_bpf_cpuperf_cur().
7638  */
7639 __bpf_kfunc u32 scx_bpf_cpuperf_cap(s32 cpu, const struct bpf_prog_aux *aux)
7640 {
7641 	struct scx_sched *sch;
7642 
7643 	guard(rcu)();
7644 
7645 	sch = scx_prog_sched(aux);
7646 	if (likely(sch) && ops_cpu_valid(sch, cpu, NULL))
7647 		return arch_scale_cpu_capacity(cpu);
7648 	else
7649 		return SCX_CPUPERF_ONE;
7650 }
7651 
7652 /**
7653  * scx_bpf_cpuperf_cur - Query the current relative performance of a CPU
7654  * @cpu: CPU of interest
7655  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
7656  *
7657  * Return the current relative performance of @cpu in relation to its maximum.
7658  * The return value is in the range [1, %SCX_CPUPERF_ONE].
7659  *
7660  * The current performance level of a CPU in relation to the maximum performance
7661  * available in the system can be calculated as follows:
7662  *
7663  *   scx_bpf_cpuperf_cap() * scx_bpf_cpuperf_cur() / %SCX_CPUPERF_ONE
7664  *
7665  * The result is in the range [1, %SCX_CPUPERF_ONE].
7666  */
7667 __bpf_kfunc u32 scx_bpf_cpuperf_cur(s32 cpu, const struct bpf_prog_aux *aux)
7668 {
7669 	struct scx_sched *sch;
7670 
7671 	guard(rcu)();
7672 
7673 	sch = scx_prog_sched(aux);
7674 	if (likely(sch) && ops_cpu_valid(sch, cpu, NULL))
7675 		return arch_scale_freq_capacity(cpu);
7676 	else
7677 		return SCX_CPUPERF_ONE;
7678 }
7679 
7680 /**
7681  * scx_bpf_cpuperf_set - Set the relative performance target of a CPU
7682  * @cpu: CPU of interest
7683  * @perf: target performance level [0, %SCX_CPUPERF_ONE]
7684  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
7685  *
7686  * Set the target performance level of @cpu to @perf. @perf is in linear
7687  * relative scale between 0 and %SCX_CPUPERF_ONE. This determines how the
7688  * schedutil cpufreq governor chooses the target frequency.
7689  *
7690  * The actual performance level chosen, CPU grouping, and the overhead and
7691  * latency of the operations are dependent on the hardware and cpufreq driver in
7692  * use. Consult hardware and cpufreq documentation for more information. The
7693  * current performance level can be monitored using scx_bpf_cpuperf_cur().
7694  */
7695 __bpf_kfunc void scx_bpf_cpuperf_set(s32 cpu, u32 perf, const struct bpf_prog_aux *aux)
7696 {
7697 	struct scx_sched *sch;
7698 
7699 	guard(rcu)();
7700 
7701 	sch = scx_prog_sched(aux);
7702 	if (unlikely(!sch))
7703 		return;
7704 
7705 	if (unlikely(perf > SCX_CPUPERF_ONE)) {
7706 		scx_error(sch, "Invalid cpuperf target %u for CPU %d", perf, cpu);
7707 		return;
7708 	}
7709 
7710 	if (ops_cpu_valid(sch, cpu, NULL)) {
7711 		struct rq *rq = cpu_rq(cpu), *locked_rq = scx_locked_rq();
7712 		struct rq_flags rf;
7713 
7714 		/*
7715 		 * When called with an rq lock held, restrict the operation
7716 		 * to the corresponding CPU to prevent ABBA deadlocks.
7717 		 */
7718 		if (locked_rq && rq != locked_rq) {
7719 			scx_error(sch, "Invalid target CPU %d", cpu);
7720 			return;
7721 		}
7722 
7723 		/*
7724 		 * If no rq lock is held, allow to operate on any CPU by
7725 		 * acquiring the corresponding rq lock.
7726 		 */
7727 		if (!locked_rq) {
7728 			rq_lock_irqsave(rq, &rf);
7729 			update_rq_clock(rq);
7730 		}
7731 
7732 		rq->scx.cpuperf_target = perf;
7733 		cpufreq_update_util(rq, 0);
7734 
7735 		if (!locked_rq)
7736 			rq_unlock_irqrestore(rq, &rf);
7737 	}
7738 }
7739 
7740 /**
7741  * scx_bpf_nr_node_ids - Return the number of possible node IDs
7742  *
7743  * All valid node IDs in the system are smaller than the returned value.
7744  */
7745 __bpf_kfunc u32 scx_bpf_nr_node_ids(void)
7746 {
7747 	return nr_node_ids;
7748 }
7749 
7750 /**
7751  * scx_bpf_nr_cpu_ids - Return the number of possible CPU IDs
7752  *
7753  * All valid CPU IDs in the system are smaller than the returned value.
7754  */
7755 __bpf_kfunc u32 scx_bpf_nr_cpu_ids(void)
7756 {
7757 	return nr_cpu_ids;
7758 }
7759 
7760 /**
7761  * scx_bpf_get_possible_cpumask - Get a referenced kptr to cpu_possible_mask
7762  */
7763 __bpf_kfunc const struct cpumask *scx_bpf_get_possible_cpumask(void)
7764 {
7765 	return cpu_possible_mask;
7766 }
7767 
7768 /**
7769  * scx_bpf_get_online_cpumask - Get a referenced kptr to cpu_online_mask
7770  */
7771 __bpf_kfunc const struct cpumask *scx_bpf_get_online_cpumask(void)
7772 {
7773 	return cpu_online_mask;
7774 }
7775 
7776 /**
7777  * scx_bpf_put_cpumask - Release a possible/online cpumask
7778  * @cpumask: cpumask to release
7779  */
7780 __bpf_kfunc void scx_bpf_put_cpumask(const struct cpumask *cpumask)
7781 {
7782 	/*
7783 	 * Empty function body because we aren't actually acquiring or releasing
7784 	 * a reference to a global cpumask, which is read-only in the caller and
7785 	 * is never released. The acquire / release semantics here are just used
7786 	 * to make the cpumask is a trusted pointer in the caller.
7787 	 */
7788 }
7789 
7790 /**
7791  * scx_bpf_task_running - Is task currently running?
7792  * @p: task of interest
7793  */
7794 __bpf_kfunc bool scx_bpf_task_running(const struct task_struct *p)
7795 {
7796 	return task_rq(p)->curr == p;
7797 }
7798 
7799 /**
7800  * scx_bpf_task_cpu - CPU a task is currently associated with
7801  * @p: task of interest
7802  */
7803 __bpf_kfunc s32 scx_bpf_task_cpu(const struct task_struct *p)
7804 {
7805 	return task_cpu(p);
7806 }
7807 
7808 /**
7809  * scx_bpf_cpu_rq - Fetch the rq of a CPU
7810  * @cpu: CPU of the rq
7811  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
7812  */
7813 __bpf_kfunc struct rq *scx_bpf_cpu_rq(s32 cpu, const struct bpf_prog_aux *aux)
7814 {
7815 	struct scx_sched *sch;
7816 
7817 	guard(rcu)();
7818 
7819 	sch = scx_prog_sched(aux);
7820 	if (unlikely(!sch))
7821 		return NULL;
7822 
7823 	if (!ops_cpu_valid(sch, cpu, NULL))
7824 		return NULL;
7825 
7826 	if (!sch->warned_deprecated_rq) {
7827 		printk_deferred(KERN_WARNING "sched_ext: %s() is deprecated; "
7828 				"use scx_bpf_locked_rq() when holding rq lock "
7829 				"or scx_bpf_cpu_curr() to read remote curr safely.\n", __func__);
7830 		sch->warned_deprecated_rq = true;
7831 	}
7832 
7833 	return cpu_rq(cpu);
7834 }
7835 
7836 /**
7837  * scx_bpf_locked_rq - Return the rq currently locked by SCX
7838  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
7839  *
7840  * Returns the rq if a rq lock is currently held by SCX.
7841  * Otherwise emits an error and returns NULL.
7842  */
7843 __bpf_kfunc struct rq *scx_bpf_locked_rq(const struct bpf_prog_aux *aux)
7844 {
7845 	struct scx_sched *sch;
7846 	struct rq *rq;
7847 
7848 	guard(preempt)();
7849 
7850 	sch = scx_prog_sched(aux);
7851 	if (unlikely(!sch))
7852 		return NULL;
7853 
7854 	rq = scx_locked_rq();
7855 	if (!rq) {
7856 		scx_error(sch, "accessing rq without holding rq lock");
7857 		return NULL;
7858 	}
7859 
7860 	return rq;
7861 }
7862 
7863 /**
7864  * scx_bpf_cpu_curr - Return remote CPU's curr task
7865  * @cpu: CPU of interest
7866  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
7867  *
7868  * Callers must hold RCU read lock (KF_RCU).
7869  */
7870 __bpf_kfunc struct task_struct *scx_bpf_cpu_curr(s32 cpu, const struct bpf_prog_aux *aux)
7871 {
7872 	struct scx_sched *sch;
7873 
7874 	guard(rcu)();
7875 
7876 	sch = scx_prog_sched(aux);
7877 	if (unlikely(!sch))
7878 		return NULL;
7879 
7880 	if (!ops_cpu_valid(sch, cpu, NULL))
7881 		return NULL;
7882 
7883 	return rcu_dereference(cpu_rq(cpu)->curr);
7884 }
7885 
7886 /**
7887  * scx_bpf_task_cgroup - Return the sched cgroup of a task
7888  * @p: task of interest
7889  * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs
7890  *
7891  * @p->sched_task_group->css.cgroup represents the cgroup @p is associated with
7892  * from the scheduler's POV. SCX operations should use this function to
7893  * determine @p's current cgroup as, unlike following @p->cgroups,
7894  * @p->sched_task_group is protected by @p's rq lock and thus atomic w.r.t. all
7895  * rq-locked operations. Can be called on the parameter tasks of rq-locked
7896  * operations. The restriction guarantees that @p's rq is locked by the caller.
7897  */
7898 #ifdef CONFIG_CGROUP_SCHED
7899 __bpf_kfunc struct cgroup *scx_bpf_task_cgroup(struct task_struct *p,
7900 					       const struct bpf_prog_aux *aux)
7901 {
7902 	struct task_group *tg = p->sched_task_group;
7903 	struct cgroup *cgrp = &cgrp_dfl_root.cgrp;
7904 	struct scx_sched *sch;
7905 
7906 	guard(rcu)();
7907 
7908 	sch = scx_prog_sched(aux);
7909 	if (unlikely(!sch))
7910 		goto out;
7911 
7912 	if (!scx_kf_allowed_on_arg_tasks(sch, __SCX_KF_RQ_LOCKED, p))
7913 		goto out;
7914 
7915 	cgrp = tg_cgrp(tg);
7916 
7917 out:
7918 	cgroup_get(cgrp);
7919 	return cgrp;
7920 }
7921 #endif
7922 
7923 /**
7924  * scx_bpf_now - Returns a high-performance monotonically non-decreasing
7925  * clock for the current CPU. The clock returned is in nanoseconds.
7926  *
7927  * It provides the following properties:
7928  *
7929  * 1) High performance: Many BPF schedulers call bpf_ktime_get_ns() frequently
7930  *  to account for execution time and track tasks' runtime properties.
7931  *  Unfortunately, in some hardware platforms, bpf_ktime_get_ns() -- which
7932  *  eventually reads a hardware timestamp counter -- is neither performant nor
7933  *  scalable. scx_bpf_now() aims to provide a high-performance clock by
7934  *  using the rq clock in the scheduler core whenever possible.
7935  *
7936  * 2) High enough resolution for the BPF scheduler use cases: In most BPF
7937  *  scheduler use cases, the required clock resolution is lower than the most
7938  *  accurate hardware clock (e.g., rdtsc in x86). scx_bpf_now() basically
7939  *  uses the rq clock in the scheduler core whenever it is valid. It considers
7940  *  that the rq clock is valid from the time the rq clock is updated
7941  *  (update_rq_clock) until the rq is unlocked (rq_unpin_lock).
7942  *
7943  * 3) Monotonically non-decreasing clock for the same CPU: scx_bpf_now()
7944  *  guarantees the clock never goes backward when comparing them in the same
7945  *  CPU. On the other hand, when comparing clocks in different CPUs, there
7946  *  is no such guarantee -- the clock can go backward. It provides a
7947  *  monotonically *non-decreasing* clock so that it would provide the same
7948  *  clock values in two different scx_bpf_now() calls in the same CPU
7949  *  during the same period of when the rq clock is valid.
7950  */
7951 __bpf_kfunc u64 scx_bpf_now(void)
7952 {
7953 	struct rq *rq;
7954 	u64 clock;
7955 
7956 	preempt_disable();
7957 
7958 	rq = this_rq();
7959 	if (smp_load_acquire(&rq->scx.flags) & SCX_RQ_CLK_VALID) {
7960 		/*
7961 		 * If the rq clock is valid, use the cached rq clock.
7962 		 *
7963 		 * Note that scx_bpf_now() is re-entrant between a process
7964 		 * context and an interrupt context (e.g., timer interrupt).
7965 		 * However, we don't need to consider the race between them
7966 		 * because such race is not observable from a caller.
7967 		 */
7968 		clock = READ_ONCE(rq->scx.clock);
7969 	} else {
7970 		/*
7971 		 * Otherwise, return a fresh rq clock.
7972 		 *
7973 		 * The rq clock is updated outside of the rq lock.
7974 		 * In this case, keep the updated rq clock invalid so the next
7975 		 * kfunc call outside the rq lock gets a fresh rq clock.
7976 		 */
7977 		clock = sched_clock_cpu(cpu_of(rq));
7978 	}
7979 
7980 	preempt_enable();
7981 
7982 	return clock;
7983 }
7984 
7985 static void scx_read_events(struct scx_sched *sch, struct scx_event_stats *events)
7986 {
7987 	struct scx_event_stats *e_cpu;
7988 	int cpu;
7989 
7990 	/* Aggregate per-CPU event counters into @events. */
7991 	memset(events, 0, sizeof(*events));
7992 	for_each_possible_cpu(cpu) {
7993 		e_cpu = &per_cpu_ptr(sch->pcpu, cpu)->event_stats;
7994 		scx_agg_event(events, e_cpu, SCX_EV_SELECT_CPU_FALLBACK);
7995 		scx_agg_event(events, e_cpu, SCX_EV_DISPATCH_LOCAL_DSQ_OFFLINE);
7996 		scx_agg_event(events, e_cpu, SCX_EV_DISPATCH_KEEP_LAST);
7997 		scx_agg_event(events, e_cpu, SCX_EV_ENQ_SKIP_EXITING);
7998 		scx_agg_event(events, e_cpu, SCX_EV_ENQ_SKIP_MIGRATION_DISABLED);
7999 		scx_agg_event(events, e_cpu, SCX_EV_REFILL_SLICE_DFL);
8000 		scx_agg_event(events, e_cpu, SCX_EV_BYPASS_DURATION);
8001 		scx_agg_event(events, e_cpu, SCX_EV_BYPASS_DISPATCH);
8002 		scx_agg_event(events, e_cpu, SCX_EV_BYPASS_ACTIVATE);
8003 	}
8004 }
8005 
8006 /*
8007  * scx_bpf_events - Get a system-wide event counter to
8008  * @events: output buffer from a BPF program
8009  * @events__sz: @events len, must end in '__sz'' for the verifier
8010  */
8011 __bpf_kfunc void scx_bpf_events(struct scx_event_stats *events,
8012 				size_t events__sz)
8013 {
8014 	struct scx_sched *sch;
8015 	struct scx_event_stats e_sys;
8016 
8017 	rcu_read_lock();
8018 	sch = rcu_dereference(scx_root);
8019 	if (sch)
8020 		scx_read_events(sch, &e_sys);
8021 	else
8022 		memset(&e_sys, 0, sizeof(e_sys));
8023 	rcu_read_unlock();
8024 
8025 	/*
8026 	 * We cannot entirely trust a BPF-provided size since a BPF program
8027 	 * might be compiled against a different vmlinux.h, of which
8028 	 * scx_event_stats would be larger (a newer vmlinux.h) or smaller
8029 	 * (an older vmlinux.h). Hence, we use the smaller size to avoid
8030 	 * memory corruption.
8031 	 */
8032 	events__sz = min(events__sz, sizeof(*events));
8033 	memcpy(events, &e_sys, events__sz);
8034 }
8035 
8036 __bpf_kfunc_end_defs();
8037 
8038 BTF_KFUNCS_START(scx_kfunc_ids_any)
8039 BTF_ID_FLAGS(func, scx_bpf_task_set_slice, KF_RCU);
8040 BTF_ID_FLAGS(func, scx_bpf_task_set_dsq_vtime, KF_RCU);
8041 BTF_ID_FLAGS(func, scx_bpf_kick_cpu, KF_IMPLICIT_ARGS)
8042 BTF_ID_FLAGS(func, scx_bpf_dsq_nr_queued)
8043 BTF_ID_FLAGS(func, scx_bpf_destroy_dsq)
8044 BTF_ID_FLAGS(func, scx_bpf_dsq_peek, KF_IMPLICIT_ARGS | KF_RCU_PROTECTED | KF_RET_NULL)
8045 BTF_ID_FLAGS(func, bpf_iter_scx_dsq_new, KF_IMPLICIT_ARGS | KF_ITER_NEW | KF_RCU_PROTECTED)
8046 BTF_ID_FLAGS(func, bpf_iter_scx_dsq_next, KF_ITER_NEXT | KF_RET_NULL)
8047 BTF_ID_FLAGS(func, bpf_iter_scx_dsq_destroy, KF_ITER_DESTROY)
8048 BTF_ID_FLAGS(func, scx_bpf_exit_bstr, KF_IMPLICIT_ARGS)
8049 BTF_ID_FLAGS(func, scx_bpf_error_bstr, KF_IMPLICIT_ARGS)
8050 BTF_ID_FLAGS(func, scx_bpf_dump_bstr, KF_IMPLICIT_ARGS)
8051 BTF_ID_FLAGS(func, scx_bpf_reenqueue_local___v2)
8052 BTF_ID_FLAGS(func, scx_bpf_cpuperf_cap, KF_IMPLICIT_ARGS)
8053 BTF_ID_FLAGS(func, scx_bpf_cpuperf_cur, KF_IMPLICIT_ARGS)
8054 BTF_ID_FLAGS(func, scx_bpf_cpuperf_set, KF_IMPLICIT_ARGS)
8055 BTF_ID_FLAGS(func, scx_bpf_nr_node_ids)
8056 BTF_ID_FLAGS(func, scx_bpf_nr_cpu_ids)
8057 BTF_ID_FLAGS(func, scx_bpf_get_possible_cpumask, KF_ACQUIRE)
8058 BTF_ID_FLAGS(func, scx_bpf_get_online_cpumask, KF_ACQUIRE)
8059 BTF_ID_FLAGS(func, scx_bpf_put_cpumask, KF_RELEASE)
8060 BTF_ID_FLAGS(func, scx_bpf_task_running, KF_RCU)
8061 BTF_ID_FLAGS(func, scx_bpf_task_cpu, KF_RCU)
8062 BTF_ID_FLAGS(func, scx_bpf_cpu_rq, KF_IMPLICIT_ARGS)
8063 BTF_ID_FLAGS(func, scx_bpf_locked_rq, KF_IMPLICIT_ARGS | KF_RET_NULL)
8064 BTF_ID_FLAGS(func, scx_bpf_cpu_curr, KF_IMPLICIT_ARGS | KF_RET_NULL | KF_RCU_PROTECTED)
8065 #ifdef CONFIG_CGROUP_SCHED
8066 BTF_ID_FLAGS(func, scx_bpf_task_cgroup, KF_IMPLICIT_ARGS | KF_RCU | KF_ACQUIRE)
8067 #endif
8068 BTF_ID_FLAGS(func, scx_bpf_now)
8069 BTF_ID_FLAGS(func, scx_bpf_events)
8070 BTF_KFUNCS_END(scx_kfunc_ids_any)
8071 
8072 static const struct btf_kfunc_id_set scx_kfunc_set_any = {
8073 	.owner			= THIS_MODULE,
8074 	.set			= &scx_kfunc_ids_any,
8075 };
8076 
8077 static int __init scx_init(void)
8078 {
8079 	int ret;
8080 
8081 	/*
8082 	 * kfunc registration can't be done from init_sched_ext_class() as
8083 	 * register_btf_kfunc_id_set() needs most of the system to be up.
8084 	 *
8085 	 * Some kfuncs are context-sensitive and can only be called from
8086 	 * specific SCX ops. They are grouped into BTF sets accordingly.
8087 	 * Unfortunately, BPF currently doesn't have a way of enforcing such
8088 	 * restrictions. Eventually, the verifier should be able to enforce
8089 	 * them. For now, register them the same and make each kfunc explicitly
8090 	 * check using scx_kf_allowed().
8091 	 */
8092 	if ((ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_STRUCT_OPS,
8093 					     &scx_kfunc_set_enqueue_dispatch)) ||
8094 	    (ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_STRUCT_OPS,
8095 					     &scx_kfunc_set_dispatch)) ||
8096 	    (ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_STRUCT_OPS,
8097 					     &scx_kfunc_set_cpu_release)) ||
8098 	    (ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_STRUCT_OPS,
8099 					     &scx_kfunc_set_unlocked)) ||
8100 	    (ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_SYSCALL,
8101 					     &scx_kfunc_set_unlocked)) ||
8102 	    (ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_STRUCT_OPS,
8103 					     &scx_kfunc_set_any)) ||
8104 	    (ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_TRACING,
8105 					     &scx_kfunc_set_any)) ||
8106 	    (ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_SYSCALL,
8107 					     &scx_kfunc_set_any))) {
8108 		pr_err("sched_ext: Failed to register kfunc sets (%d)\n", ret);
8109 		return ret;
8110 	}
8111 
8112 	ret = scx_idle_init();
8113 	if (ret) {
8114 		pr_err("sched_ext: Failed to initialize idle tracking (%d)\n", ret);
8115 		return ret;
8116 	}
8117 
8118 	ret = register_bpf_struct_ops(&bpf_sched_ext_ops, sched_ext_ops);
8119 	if (ret) {
8120 		pr_err("sched_ext: Failed to register struct_ops (%d)\n", ret);
8121 		return ret;
8122 	}
8123 
8124 	ret = register_pm_notifier(&scx_pm_notifier);
8125 	if (ret) {
8126 		pr_err("sched_ext: Failed to register PM notifier (%d)\n", ret);
8127 		return ret;
8128 	}
8129 
8130 	scx_kset = kset_create_and_add("sched_ext", &scx_uevent_ops, kernel_kobj);
8131 	if (!scx_kset) {
8132 		pr_err("sched_ext: Failed to create /sys/kernel/sched_ext\n");
8133 		return -ENOMEM;
8134 	}
8135 
8136 	ret = sysfs_create_group(&scx_kset->kobj, &scx_global_attr_group);
8137 	if (ret < 0) {
8138 		pr_err("sched_ext: Failed to add global attributes\n");
8139 		return ret;
8140 	}
8141 
8142 	if (!alloc_cpumask_var(&scx_bypass_lb_donee_cpumask, GFP_KERNEL) ||
8143 	    !alloc_cpumask_var(&scx_bypass_lb_resched_cpumask, GFP_KERNEL)) {
8144 		pr_err("sched_ext: Failed to allocate cpumasks\n");
8145 		return -ENOMEM;
8146 	}
8147 
8148 	return 0;
8149 }
8150 __initcall(scx_init);
8151