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