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