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