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