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