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