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