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