1 /* SPDX-License-Identifier: GPL-2.0 */
2 /*
3  * BPF extensible scheduler class: Documentation/scheduler/sched-ext.rst
4  *
5  * Copyright (c) 2022 Meta Platforms, Inc. and affiliates.
6  * Copyright (c) 2022 Tejun Heo <tj@kernel.org>
7  * Copyright (c) 2022 David Vernet <dvernet@meta.com>
8  */
9 #include <linux/btf_ids.h>
10 #include "ext_idle.h"
11 
12 /*
13  * NOTE: sched_ext is in the process of growing multiple scheduler support and
14  * scx_root usage is in a transitional state. Naked dereferences are safe if the
15  * caller is one of the tasks attached to SCX and explicit RCU dereference is
16  * necessary otherwise. Naked scx_root dereferences trigger sparse warnings but
17  * are used as temporary markers to indicate that the dereferences need to be
18  * updated to point to the associated scheduler instances rather than scx_root.
19  */
20 static struct scx_sched __rcu *scx_root;
21 
22 /*
23  * During exit, a task may schedule after losing its PIDs. When disabling the
24  * BPF scheduler, we need to be able to iterate tasks in every state to
25  * guarantee system safety. Maintain a dedicated task list which contains every
26  * task between its fork and eventual free.
27  */
28 static DEFINE_SPINLOCK(scx_tasks_lock);
29 static LIST_HEAD(scx_tasks);
30 
31 /* ops enable/disable */
32 static DEFINE_MUTEX(scx_enable_mutex);
33 DEFINE_STATIC_KEY_FALSE(__scx_enabled);
34 DEFINE_STATIC_PERCPU_RWSEM(scx_fork_rwsem);
35 static atomic_t scx_enable_state_var = ATOMIC_INIT(SCX_DISABLED);
36 static unsigned long scx_in_softlockup;
37 static atomic_t scx_breather_depth = ATOMIC_INIT(0);
38 static int scx_bypass_depth;
39 static bool scx_init_task_enabled;
40 static bool scx_switching_all;
41 DEFINE_STATIC_KEY_FALSE(__scx_switched_all);
42 
43 static atomic_long_t scx_nr_rejected = ATOMIC_LONG_INIT(0);
44 static atomic_long_t scx_hotplug_seq = ATOMIC_LONG_INIT(0);
45 
46 /*
47  * A monotically increasing sequence number that is incremented every time a
48  * scheduler is enabled. This can be used by to check if any custom sched_ext
49  * scheduler has ever been used in the system.
50  */
51 static atomic_long_t scx_enable_seq = ATOMIC_LONG_INIT(0);
52 
53 /*
54  * The maximum amount of time in jiffies that a task may be runnable without
55  * being scheduled on a CPU. If this timeout is exceeded, it will trigger
56  * scx_error().
57  */
58 static unsigned long scx_watchdog_timeout;
59 
60 /*
61  * The last time the delayed work was run. This delayed work relies on
62  * ksoftirqd being able to run to service timer interrupts, so it's possible
63  * that this work itself could get wedged. To account for this, we check that
64  * it's not stalled in the timer tick, and trigger an error if it is.
65  */
66 static unsigned long scx_watchdog_timestamp = INITIAL_JIFFIES;
67 
68 static struct delayed_work scx_watchdog_work;
69 
70 /*
71  * For %SCX_KICK_WAIT: Each CPU has a pointer to an array of 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 
scx_exit(struct scx_sched * sch,enum scx_exit_kind kind,s64 exit_code,const char * fmt,...)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 
jiffies_delta_msecs(unsigned long at,unsigned long now)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 */
higher_bits(u32 flags)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 */
highest_bit(u32 flags)184 static u32 highest_bit(u32 flags)
185 {
186 	int bit = fls(flags);
187 	return ((u64)1 << bit) >> 1;
188 }
189 
u32_before(u32 a,u32 b)190 static bool u32_before(u32 a, u32 b)
191 {
192 	return (s32)(a - b) < 0;
193 }
194 
find_global_dsq(struct scx_sched * sch,struct task_struct * p)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 
find_user_dsq(struct scx_sched * sch,u64 dsq_id)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  */
scx_kf_allow(u32 mask)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 
scx_kf_disallow(u32 mask)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 
update_locked_rq(struct rq * rq)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 */
scx_kf_allowed(struct scx_sched * sch,u32 mask)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() */
scx_kf_allowed_on_arg_tasks(struct scx_sched * sch,u32 mask,struct task_struct * p)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  */
nldsq_next_task(struct scx_dispatch_q * dsq,struct task_struct * cur,bool rev)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  */
scx_task_iter_start(struct scx_task_iter * iter)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 	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 
__scx_task_iter_rq_unlock(struct scx_task_iter * iter)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  */
scx_task_iter_unlock(struct scx_task_iter * iter)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 		spin_unlock_irq(&scx_tasks_lock);
511 	}
512 }
513 
__scx_task_iter_maybe_relock(struct scx_task_iter * iter)514 static void __scx_task_iter_maybe_relock(struct scx_task_iter *iter)
515 {
516 	if (!iter->list_locked) {
517 		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  */
scx_task_iter_stop(struct scx_task_iter * iter)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  */
scx_task_iter_next(struct scx_task_iter * iter)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  */
scx_task_iter_next_locked(struct scx_task_iter * iter)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 
scx_enable_state(void)673 static enum scx_enable_state scx_enable_state(void)
674 {
675 	return atomic_read(&scx_enable_state_var);
676 }
677 
scx_set_enable_state(enum scx_enable_state to)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 
scx_tryset_enable_state(enum scx_enable_state to,enum scx_enable_state from)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  */
wait_ops_state(struct task_struct * p,unsigned long opss)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 
__cpu_valid(s32 cpu)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  */
ops_cpu_valid(struct scx_sched * sch,s32 cpu,const char * where)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  */
ops_sanitize_err(struct scx_sched * sch,const char * ops_name,s32 err)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 
run_deferred(struct rq * rq)755 static void run_deferred(struct rq *rq)
756 {
757 	process_ddsp_deferred_locals(rq);
758 }
759 
deferred_bal_cb_workfn(struct rq * rq)760 static void deferred_bal_cb_workfn(struct rq *rq)
761 {
762 	run_deferred(rq);
763 }
764 
deferred_irq_workfn(struct irq_work * irq_work)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  */
schedule_deferred(struct rq * rq)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  */
touch_core_sched(struct rq * rq,struct task_struct * p)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  */
touch_core_sched_dispatch(struct rq * rq,struct task_struct * p)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 
update_curr_scx(struct rq * rq)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 
scx_dsq_priq_less(struct rb_node * node_a,const struct rb_node * node_b)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 
dsq_mod_nr(struct scx_dispatch_q * dsq,s32 delta)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 
refill_task_slice_dfl(struct scx_sched * sch,struct task_struct * p)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 
dispatch_enqueue(struct scx_sched * sch,struct scx_dispatch_q * dsq,struct task_struct * p,u64 enq_flags)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 
task_unlink_from_dsq(struct task_struct * p,struct scx_dispatch_q * dsq)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 
dispatch_dequeue(struct rq * rq,struct task_struct * p)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 
find_dsq_for_dispatch(struct scx_sched * sch,struct rq * rq,u64 dsq_id,struct task_struct * p)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 
mark_direct_dispatch(struct scx_sched * sch,struct task_struct * ddsp_task,struct task_struct * p,u64 dsq_id,u64 enq_flags)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 
direct_dispatch(struct scx_sched * sch,struct task_struct * p,u64 enq_flags)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 
scx_rq_online(struct rq * rq)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 
do_enqueue_task(struct rq * rq,struct task_struct * p,u64 enq_flags,int sticky_cpu)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 
task_runnable(const struct task_struct * p)1306 static bool task_runnable(const struct task_struct *p)
1307 {
1308 	return !list_empty(&p->scx.runnable_node);
1309 }
1310 
set_task_runnable(struct rq * rq,struct task_struct * p)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 
clr_task_runnable(struct task_struct * p,bool reset_runnable_at)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 
enqueue_task_scx(struct rq * rq,struct task_struct * p,int enq_flags)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 
ops_dequeue(struct rq * rq,struct task_struct * p,u64 deq_flags)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 
dequeue_task_scx(struct rq * rq,struct task_struct * p,int deq_flags)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 
yield_task_scx(struct rq * rq)1474 static void yield_task_scx(struct rq *rq)
1475 {
1476 	struct scx_sched *sch = scx_root;
1477 	struct task_struct *p = rq->curr;
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 
yield_to_task_scx(struct rq * rq,struct task_struct * to)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->curr;
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 
move_local_task_to_local_dsq(struct task_struct * p,u64 enq_flags,struct scx_dispatch_q * src_dsq,struct rq * dst_rq)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  */
move_remote_task_to_local_dsq(struct task_struct * p,u64 enq_flags,struct rq * src_rq,struct rq * dst_rq)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  */
task_can_run_on_remote_rq(struct scx_sched * sch,struct task_struct * p,struct rq * rq,bool enforce)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  */
unlink_dsq_and_lock_src_rq(struct task_struct * p,struct scx_dispatch_q * dsq,struct rq * src_rq)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 
consume_remote_task(struct rq * this_rq,struct task_struct * p,struct scx_dispatch_q * dsq,struct rq * src_rq)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  */
move_task_between_dsqs(struct scx_sched * sch,struct task_struct * p,u64 enq_flags,struct scx_dispatch_q * src_dsq,struct scx_dispatch_q * dst_dsq)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  */
scx_breather(struct rq * rq)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 
consume_dispatch_q(struct scx_sched * sch,struct rq * rq,struct scx_dispatch_q * dsq)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 
consume_global_dsq(struct scx_sched * sch,struct rq * rq)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  */
dispatch_to_local_dsq(struct scx_sched * sch,struct rq * rq,struct scx_dispatch_q * dst_dsq,struct task_struct * p,u64 enq_flags)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  */
finish_dispatch(struct scx_sched * sch,struct rq * rq,struct task_struct * p,unsigned long qseq_at_dispatch,u64 dsq_id,u64 enq_flags)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 
flush_dispatch_buf(struct scx_sched * sch,struct rq * rq)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 
maybe_queue_balance_callback(struct rq * rq)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 
balance_one(struct rq * rq,struct task_struct * prev)2040 static int balance_one(struct rq *rq, struct task_struct *prev)
2041 {
2042 	struct scx_sched *sch = scx_root;
2043 	struct scx_dsp_ctx *dspc = this_cpu_ptr(scx_dsp_ctx);
2044 	bool prev_on_scx = prev->sched_class == &ext_sched_class;
2045 	bool prev_on_rq = prev->scx.flags & SCX_TASK_QUEUED;
2046 	int nr_loops = SCX_DSP_MAX_LOOPS;
2047 
2048 	lockdep_assert_rq_held(rq);
2049 	rq->scx.flags |= SCX_RQ_IN_BALANCE;
2050 	rq->scx.flags &= ~(SCX_RQ_BAL_PENDING | SCX_RQ_BAL_KEEP);
2051 
2052 	if ((sch->ops.flags & SCX_OPS_HAS_CPU_PREEMPT) &&
2053 	    unlikely(rq->scx.cpu_released)) {
2054 		/*
2055 		 * If the previous sched_class for the current CPU was not SCX,
2056 		 * notify the BPF scheduler that it again has control of the
2057 		 * core. This callback complements ->cpu_release(), which is
2058 		 * emitted in switch_class().
2059 		 */
2060 		if (SCX_HAS_OP(sch, cpu_acquire))
2061 			SCX_CALL_OP(sch, SCX_KF_REST, cpu_acquire, rq,
2062 				    cpu_of(rq), NULL);
2063 		rq->scx.cpu_released = false;
2064 	}
2065 
2066 	if (prev_on_scx) {
2067 		update_curr_scx(rq);
2068 
2069 		/*
2070 		 * If @prev is runnable & has slice left, it has priority and
2071 		 * fetching more just increases latency for the fetched tasks.
2072 		 * Tell pick_task_scx() to keep running @prev. If the BPF
2073 		 * scheduler wants to handle this explicitly, it should
2074 		 * implement ->cpu_release().
2075 		 *
2076 		 * See scx_disable_workfn() for the explanation on the bypassing
2077 		 * test.
2078 		 */
2079 		if (prev_on_rq && prev->scx.slice && !scx_rq_bypassing(rq)) {
2080 			rq->scx.flags |= SCX_RQ_BAL_KEEP;
2081 			goto has_tasks;
2082 		}
2083 	}
2084 
2085 	/* if there already are tasks to run, nothing to do */
2086 	if (rq->scx.local_dsq.nr)
2087 		goto has_tasks;
2088 
2089 	if (consume_global_dsq(sch, rq))
2090 		goto has_tasks;
2091 
2092 	if (unlikely(!SCX_HAS_OP(sch, dispatch)) ||
2093 	    scx_rq_bypassing(rq) || !scx_rq_online(rq))
2094 		goto no_tasks;
2095 
2096 	dspc->rq = rq;
2097 
2098 	/*
2099 	 * The dispatch loop. Because flush_dispatch_buf() may drop the rq lock,
2100 	 * the local DSQ might still end up empty after a successful
2101 	 * ops.dispatch(). If the local DSQ is empty even after ops.dispatch()
2102 	 * produced some tasks, retry. The BPF scheduler may depend on this
2103 	 * looping behavior to simplify its implementation.
2104 	 */
2105 	do {
2106 		dspc->nr_tasks = 0;
2107 
2108 		SCX_CALL_OP(sch, SCX_KF_DISPATCH, dispatch, rq,
2109 			    cpu_of(rq), prev_on_scx ? prev : NULL);
2110 
2111 		flush_dispatch_buf(sch, rq);
2112 
2113 		if (prev_on_rq && prev->scx.slice) {
2114 			rq->scx.flags |= SCX_RQ_BAL_KEEP;
2115 			goto has_tasks;
2116 		}
2117 		if (rq->scx.local_dsq.nr)
2118 			goto has_tasks;
2119 		if (consume_global_dsq(sch, rq))
2120 			goto has_tasks;
2121 
2122 		/*
2123 		 * ops.dispatch() can trap us in this loop by repeatedly
2124 		 * dispatching ineligible tasks. Break out once in a while to
2125 		 * allow the watchdog to run. As IRQ can't be enabled in
2126 		 * balance(), we want to complete this scheduling cycle and then
2127 		 * start a new one. IOW, we want to call resched_curr() on the
2128 		 * next, most likely idle, task, not the current one. Use
2129 		 * scx_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 
balance_scx(struct rq * rq,struct task_struct * prev,struct rq_flags * rf)2156 static int balance_scx(struct rq *rq, struct task_struct *prev,
2157 		       struct rq_flags *rf)
2158 {
2159 	int ret;
2160 
2161 	rq_unpin_lock(rq, rf);
2162 
2163 	ret = balance_one(rq, prev);
2164 
2165 #ifdef CONFIG_SCHED_SMT
2166 	/*
2167 	 * When core-sched is enabled, this ops.balance() call will be followed
2168 	 * by pick_task_scx() on this CPU and the SMT siblings. Balance the
2169 	 * siblings too.
2170 	 */
2171 	if (sched_core_enabled(rq)) {
2172 		const struct cpumask *smt_mask = cpu_smt_mask(cpu_of(rq));
2173 		int scpu;
2174 
2175 		for_each_cpu_andnot(scpu, smt_mask, cpumask_of(cpu_of(rq))) {
2176 			struct rq *srq = cpu_rq(scpu);
2177 			struct task_struct *sprev = srq->curr;
2178 
2179 			WARN_ON_ONCE(__rq_lockp(rq) != __rq_lockp(srq));
2180 			update_rq_clock(srq);
2181 			balance_one(srq, sprev);
2182 		}
2183 	}
2184 #endif
2185 	rq_repin_lock(rq, rf);
2186 
2187 	maybe_queue_balance_callback(rq);
2188 
2189 	return ret;
2190 }
2191 
process_ddsp_deferred_locals(struct rq * rq)2192 static void process_ddsp_deferred_locals(struct rq *rq)
2193 {
2194 	struct task_struct *p;
2195 
2196 	lockdep_assert_rq_held(rq);
2197 
2198 	/*
2199 	 * Now that @rq can be unlocked, execute the deferred enqueueing of
2200 	 * tasks directly dispatched to the local DSQs of other CPUs. See
2201 	 * direct_dispatch(). Keep popping from the head instead of using
2202 	 * list_for_each_entry_safe() as dispatch_local_dsq() may unlock @rq
2203 	 * temporarily.
2204 	 */
2205 	while ((p = list_first_entry_or_null(&rq->scx.ddsp_deferred_locals,
2206 				struct task_struct, scx.dsq_list.node))) {
2207 		struct scx_sched *sch = scx_root;
2208 		struct scx_dispatch_q *dsq;
2209 
2210 		list_del_init(&p->scx.dsq_list.node);
2211 
2212 		dsq = find_dsq_for_dispatch(sch, rq, p->scx.ddsp_dsq_id, p);
2213 		if (!WARN_ON_ONCE(dsq->id != SCX_DSQ_LOCAL))
2214 			dispatch_to_local_dsq(sch, rq, dsq, p,
2215 					      p->scx.ddsp_enq_flags);
2216 	}
2217 }
2218 
set_next_task_scx(struct rq * rq,struct task_struct * p,bool first)2219 static void set_next_task_scx(struct rq *rq, struct task_struct *p, bool first)
2220 {
2221 	struct scx_sched *sch = scx_root;
2222 
2223 	if (p->scx.flags & SCX_TASK_QUEUED) {
2224 		/*
2225 		 * Core-sched might decide to execute @p before it is
2226 		 * dispatched. Call ops_dequeue() to notify the BPF scheduler.
2227 		 */
2228 		ops_dequeue(rq, p, SCX_DEQ_CORE_SCHED_EXEC);
2229 		dispatch_dequeue(rq, p);
2230 	}
2231 
2232 	p->se.exec_start = rq_clock_task(rq);
2233 
2234 	/* see dequeue_task_scx() on why we skip when !QUEUED */
2235 	if (SCX_HAS_OP(sch, running) && (p->scx.flags & SCX_TASK_QUEUED))
2236 		SCX_CALL_OP_TASK(sch, SCX_KF_REST, running, rq, p);
2237 
2238 	clr_task_runnable(p, true);
2239 
2240 	/*
2241 	 * @p is getting newly scheduled or got kicked after someone updated its
2242 	 * slice. Refresh whether tick can be stopped. See scx_can_stop_tick().
2243 	 */
2244 	if ((p->scx.slice == SCX_SLICE_INF) !=
2245 	    (bool)(rq->scx.flags & SCX_RQ_CAN_STOP_TICK)) {
2246 		if (p->scx.slice == SCX_SLICE_INF)
2247 			rq->scx.flags |= SCX_RQ_CAN_STOP_TICK;
2248 		else
2249 			rq->scx.flags &= ~SCX_RQ_CAN_STOP_TICK;
2250 
2251 		sched_update_tick_dependency(rq);
2252 
2253 		/*
2254 		 * For now, let's refresh the load_avgs just when transitioning
2255 		 * in and out of nohz. In the future, we might want to add a
2256 		 * mechanism which calls the following periodically on
2257 		 * tick-stopped CPUs.
2258 		 */
2259 		update_other_load_avgs(rq);
2260 	}
2261 }
2262 
2263 static enum scx_cpu_preempt_reason
preempt_reason_from_class(const struct sched_class * class)2264 preempt_reason_from_class(const struct sched_class *class)
2265 {
2266 	if (class == &stop_sched_class)
2267 		return SCX_CPU_PREEMPT_STOP;
2268 	if (class == &dl_sched_class)
2269 		return SCX_CPU_PREEMPT_DL;
2270 	if (class == &rt_sched_class)
2271 		return SCX_CPU_PREEMPT_RT;
2272 	return SCX_CPU_PREEMPT_UNKNOWN;
2273 }
2274 
switch_class(struct rq * rq,struct task_struct * next)2275 static void switch_class(struct rq *rq, struct task_struct *next)
2276 {
2277 	struct scx_sched *sch = scx_root;
2278 	const struct sched_class *next_class = next->sched_class;
2279 
2280 	/*
2281 	 * Pairs with the smp_load_acquire() issued by a CPU in
2282 	 * kick_cpus_irq_workfn() who is waiting for this CPU to perform a
2283 	 * resched.
2284 	 */
2285 	smp_store_release(&rq->scx.pnt_seq, rq->scx.pnt_seq + 1);
2286 	if (!(sch->ops.flags & SCX_OPS_HAS_CPU_PREEMPT))
2287 		return;
2288 
2289 	/*
2290 	 * The callback is conceptually meant to convey that the CPU is no
2291 	 * longer under the control of SCX. Therefore, don't invoke the callback
2292 	 * if the next class is below SCX (in which case the BPF scheduler has
2293 	 * actively decided not to schedule any tasks on the CPU).
2294 	 */
2295 	if (sched_class_above(&ext_sched_class, next_class))
2296 		return;
2297 
2298 	/*
2299 	 * At this point we know that SCX was preempted by a higher priority
2300 	 * sched_class, so invoke the ->cpu_release() callback if we have not
2301 	 * done so already. We only send the callback once between SCX being
2302 	 * preempted, and it regaining control of the CPU.
2303 	 *
2304 	 * ->cpu_release() complements ->cpu_acquire(), which is emitted the
2305 	 *  next time that balance_scx() is invoked.
2306 	 */
2307 	if (!rq->scx.cpu_released) {
2308 		if (SCX_HAS_OP(sch, cpu_release)) {
2309 			struct scx_cpu_release_args args = {
2310 				.reason = preempt_reason_from_class(next_class),
2311 				.task = next,
2312 			};
2313 
2314 			SCX_CALL_OP(sch, SCX_KF_CPU_RELEASE, cpu_release, rq,
2315 				    cpu_of(rq), &args);
2316 		}
2317 		rq->scx.cpu_released = true;
2318 	}
2319 }
2320 
put_prev_task_scx(struct rq * rq,struct task_struct * p,struct task_struct * next)2321 static void put_prev_task_scx(struct rq *rq, struct task_struct *p,
2322 			      struct task_struct *next)
2323 {
2324 	struct scx_sched *sch = scx_root;
2325 	update_curr_scx(rq);
2326 
2327 	/* see dequeue_task_scx() on why we skip when !QUEUED */
2328 	if (SCX_HAS_OP(sch, stopping) && (p->scx.flags & SCX_TASK_QUEUED))
2329 		SCX_CALL_OP_TASK(sch, SCX_KF_REST, stopping, rq, p, true);
2330 
2331 	if (p->scx.flags & SCX_TASK_QUEUED) {
2332 		set_task_runnable(rq, p);
2333 
2334 		/*
2335 		 * If @p has slice left and is being put, @p is getting
2336 		 * preempted by a higher priority scheduler class or core-sched
2337 		 * forcing a different task. Leave it at the head of the local
2338 		 * DSQ.
2339 		 */
2340 		if (p->scx.slice && !scx_rq_bypassing(rq)) {
2341 			dispatch_enqueue(sch, &rq->scx.local_dsq, p,
2342 					 SCX_ENQ_HEAD);
2343 			goto switch_class;
2344 		}
2345 
2346 		/*
2347 		 * If @p is runnable but we're about to enter a lower
2348 		 * sched_class, %SCX_OPS_ENQ_LAST must be set. Tell
2349 		 * ops.enqueue() that @p is the only one available for this cpu,
2350 		 * which should trigger an explicit follow-up scheduling event.
2351 		 */
2352 		if (sched_class_above(&ext_sched_class, next->sched_class)) {
2353 			WARN_ON_ONCE(!(sch->ops.flags & SCX_OPS_ENQ_LAST));
2354 			do_enqueue_task(rq, p, SCX_ENQ_LAST, -1);
2355 		} else {
2356 			do_enqueue_task(rq, p, 0, -1);
2357 		}
2358 	}
2359 
2360 switch_class:
2361 	if (next && next->sched_class != &ext_sched_class)
2362 		switch_class(rq, next);
2363 }
2364 
first_local_task(struct rq * rq)2365 static struct task_struct *first_local_task(struct rq *rq)
2366 {
2367 	return list_first_entry_or_null(&rq->scx.local_dsq.list,
2368 					struct task_struct, scx.dsq_list.node);
2369 }
2370 
pick_task_scx(struct rq * rq)2371 static struct task_struct *pick_task_scx(struct rq *rq)
2372 {
2373 	struct task_struct *prev = rq->curr;
2374 	struct task_struct *p;
2375 	bool keep_prev = rq->scx.flags & SCX_RQ_BAL_KEEP;
2376 	bool kick_idle = false;
2377 
2378 	/*
2379 	 * WORKAROUND:
2380 	 *
2381 	 * %SCX_RQ_BAL_KEEP should be set iff $prev is on SCX as it must just
2382 	 * have gone through balance_scx(). Unfortunately, there currently is a
2383 	 * bug where fair could say yes on balance() but no on pick_task(),
2384 	 * which then ends up calling pick_task_scx() without preceding
2385 	 * balance_scx().
2386 	 *
2387 	 * Keep running @prev if possible and avoid stalling from entering idle
2388 	 * without balancing.
2389 	 *
2390 	 * Once fair is fixed, remove the workaround and trigger WARN_ON_ONCE()
2391 	 * if pick_task_scx() is called without preceding balance_scx().
2392 	 */
2393 	if (unlikely(rq->scx.flags & SCX_RQ_BAL_PENDING)) {
2394 		if (prev->scx.flags & SCX_TASK_QUEUED) {
2395 			keep_prev = true;
2396 		} else {
2397 			keep_prev = false;
2398 			kick_idle = true;
2399 		}
2400 	} else if (unlikely(keep_prev &&
2401 			    prev->sched_class != &ext_sched_class)) {
2402 		/*
2403 		 * Can happen while enabling as SCX_RQ_BAL_PENDING assertion is
2404 		 * conditional on scx_enabled() and may have been skipped.
2405 		 */
2406 		WARN_ON_ONCE(scx_enable_state() == SCX_ENABLED);
2407 		keep_prev = false;
2408 	}
2409 
2410 	/*
2411 	 * If balance_scx() is telling us to keep running @prev, replenish slice
2412 	 * if necessary and keep running @prev. Otherwise, pop the first one
2413 	 * from the local DSQ.
2414 	 */
2415 	if (keep_prev) {
2416 		p = prev;
2417 		if (!p->scx.slice)
2418 			refill_task_slice_dfl(rcu_dereference_sched(scx_root), p);
2419 	} else {
2420 		p = first_local_task(rq);
2421 		if (!p) {
2422 			if (kick_idle)
2423 				scx_kick_cpu(rcu_dereference_sched(scx_root),
2424 					     cpu_of(rq), SCX_KICK_IDLE);
2425 			return NULL;
2426 		}
2427 
2428 		if (unlikely(!p->scx.slice)) {
2429 			struct scx_sched *sch = rcu_dereference_sched(scx_root);
2430 
2431 			if (!scx_rq_bypassing(rq) && !sch->warned_zero_slice) {
2432 				printk_deferred(KERN_WARNING "sched_ext: %s[%d] has zero slice in %s()\n",
2433 						p->comm, p->pid, __func__);
2434 				sch->warned_zero_slice = true;
2435 			}
2436 			refill_task_slice_dfl(sch, p);
2437 		}
2438 	}
2439 
2440 	return p;
2441 }
2442 
2443 #ifdef CONFIG_SCHED_CORE
2444 /**
2445  * scx_prio_less - Task ordering for core-sched
2446  * @a: task A
2447  * @b: task B
2448  * @in_fi: in forced idle state
2449  *
2450  * Core-sched is implemented as an additional scheduling layer on top of the
2451  * usual sched_class'es and needs to find out the expected task ordering. For
2452  * SCX, core-sched calls this function to interrogate the task ordering.
2453  *
2454  * Unless overridden by ops.core_sched_before(), @p->scx.core_sched_at is used
2455  * to implement the default task ordering. The older the timestamp, the higher
2456  * priority the task - the global FIFO ordering matching the default scheduling
2457  * behavior.
2458  *
2459  * When ops.core_sched_before() is enabled, @p->scx.core_sched_at is used to
2460  * implement FIFO ordering within each local DSQ. See pick_task_scx().
2461  */
scx_prio_less(const struct task_struct * a,const struct task_struct * b,bool in_fi)2462 bool scx_prio_less(const struct task_struct *a, const struct task_struct *b,
2463 		   bool in_fi)
2464 {
2465 	struct scx_sched *sch = scx_root;
2466 
2467 	/*
2468 	 * The const qualifiers are dropped from task_struct pointers when
2469 	 * calling ops.core_sched_before(). Accesses are controlled by the
2470 	 * verifier.
2471 	 */
2472 	if (SCX_HAS_OP(sch, core_sched_before) &&
2473 	    !scx_rq_bypassing(task_rq(a)))
2474 		return SCX_CALL_OP_2TASKS_RET(sch, SCX_KF_REST, core_sched_before,
2475 					      NULL,
2476 					      (struct task_struct *)a,
2477 					      (struct task_struct *)b);
2478 	else
2479 		return time_after64(a->scx.core_sched_at, b->scx.core_sched_at);
2480 }
2481 #endif	/* CONFIG_SCHED_CORE */
2482 
select_task_rq_scx(struct task_struct * p,int prev_cpu,int wake_flags)2483 static int select_task_rq_scx(struct task_struct *p, int prev_cpu, int wake_flags)
2484 {
2485 	struct scx_sched *sch = scx_root;
2486 	bool rq_bypass;
2487 
2488 	/*
2489 	 * sched_exec() calls with %WF_EXEC when @p is about to exec(2) as it
2490 	 * can be a good migration opportunity with low cache and memory
2491 	 * footprint. Returning a CPU different than @prev_cpu triggers
2492 	 * immediate rq migration. However, for SCX, as the current rq
2493 	 * association doesn't dictate where the task is going to run, this
2494 	 * doesn't fit well. If necessary, we can later add a dedicated method
2495 	 * which can decide to preempt self to force it through the regular
2496 	 * scheduling path.
2497 	 */
2498 	if (unlikely(wake_flags & WF_EXEC))
2499 		return prev_cpu;
2500 
2501 	rq_bypass = scx_rq_bypassing(task_rq(p));
2502 	if (likely(SCX_HAS_OP(sch, select_cpu)) && !rq_bypass) {
2503 		s32 cpu;
2504 		struct task_struct **ddsp_taskp;
2505 
2506 		ddsp_taskp = this_cpu_ptr(&direct_dispatch_task);
2507 		WARN_ON_ONCE(*ddsp_taskp);
2508 		*ddsp_taskp = p;
2509 
2510 		cpu = SCX_CALL_OP_TASK_RET(sch,
2511 					   SCX_KF_ENQUEUE | SCX_KF_SELECT_CPU,
2512 					   select_cpu, NULL, p, prev_cpu,
2513 					   wake_flags);
2514 		p->scx.selected_cpu = cpu;
2515 		*ddsp_taskp = NULL;
2516 		if (ops_cpu_valid(sch, cpu, "from ops.select_cpu()"))
2517 			return cpu;
2518 		else
2519 			return prev_cpu;
2520 	} else {
2521 		s32 cpu;
2522 
2523 		cpu = scx_select_cpu_dfl(p, prev_cpu, wake_flags, NULL, 0);
2524 		if (cpu >= 0) {
2525 			refill_task_slice_dfl(sch, p);
2526 			p->scx.ddsp_dsq_id = SCX_DSQ_LOCAL;
2527 		} else {
2528 			cpu = prev_cpu;
2529 		}
2530 		p->scx.selected_cpu = cpu;
2531 
2532 		if (rq_bypass)
2533 			__scx_add_event(sch, SCX_EV_BYPASS_DISPATCH, 1);
2534 		return cpu;
2535 	}
2536 }
2537 
task_woken_scx(struct rq * rq,struct task_struct * p)2538 static void task_woken_scx(struct rq *rq, struct task_struct *p)
2539 {
2540 	run_deferred(rq);
2541 }
2542 
set_cpus_allowed_scx(struct task_struct * p,struct affinity_context * ac)2543 static void set_cpus_allowed_scx(struct task_struct *p,
2544 				 struct affinity_context *ac)
2545 {
2546 	struct scx_sched *sch = scx_root;
2547 
2548 	set_cpus_allowed_common(p, ac);
2549 
2550 	/*
2551 	 * The effective cpumask is stored in @p->cpus_ptr which may temporarily
2552 	 * differ from the configured one in @p->cpus_mask. Always tell the bpf
2553 	 * scheduler the effective one.
2554 	 *
2555 	 * Fine-grained memory write control is enforced by BPF making the const
2556 	 * designation pointless. Cast it away when calling the operation.
2557 	 */
2558 	if (SCX_HAS_OP(sch, set_cpumask))
2559 		SCX_CALL_OP_TASK(sch, SCX_KF_REST, set_cpumask, NULL,
2560 				 p, (struct cpumask *)p->cpus_ptr);
2561 }
2562 
handle_hotplug(struct rq * rq,bool online)2563 static void handle_hotplug(struct rq *rq, bool online)
2564 {
2565 	struct scx_sched *sch = scx_root;
2566 	int cpu = cpu_of(rq);
2567 
2568 	atomic_long_inc(&scx_hotplug_seq);
2569 
2570 	/*
2571 	 * scx_root updates are protected by cpus_read_lock() and will stay
2572 	 * stable here. Note that we can't depend on scx_enabled() test as the
2573 	 * hotplug ops need to be enabled before __scx_enabled is set.
2574 	 */
2575 	if (unlikely(!sch))
2576 		return;
2577 
2578 	if (scx_enabled())
2579 		scx_idle_update_selcpu_topology(&sch->ops);
2580 
2581 	if (online && SCX_HAS_OP(sch, cpu_online))
2582 		SCX_CALL_OP(sch, SCX_KF_UNLOCKED, cpu_online, NULL, cpu);
2583 	else if (!online && SCX_HAS_OP(sch, cpu_offline))
2584 		SCX_CALL_OP(sch, SCX_KF_UNLOCKED, cpu_offline, NULL, cpu);
2585 	else
2586 		scx_exit(sch, SCX_EXIT_UNREG_KERN,
2587 			 SCX_ECODE_ACT_RESTART | SCX_ECODE_RSN_HOTPLUG,
2588 			 "cpu %d going %s, exiting scheduler", cpu,
2589 			 online ? "online" : "offline");
2590 }
2591 
scx_rq_activate(struct rq * rq)2592 void scx_rq_activate(struct rq *rq)
2593 {
2594 	handle_hotplug(rq, true);
2595 }
2596 
scx_rq_deactivate(struct rq * rq)2597 void scx_rq_deactivate(struct rq *rq)
2598 {
2599 	handle_hotplug(rq, false);
2600 }
2601 
rq_online_scx(struct rq * rq)2602 static void rq_online_scx(struct rq *rq)
2603 {
2604 	rq->scx.flags |= SCX_RQ_ONLINE;
2605 }
2606 
rq_offline_scx(struct rq * rq)2607 static void rq_offline_scx(struct rq *rq)
2608 {
2609 	rq->scx.flags &= ~SCX_RQ_ONLINE;
2610 }
2611 
2612 
check_rq_for_timeouts(struct rq * rq)2613 static bool check_rq_for_timeouts(struct rq *rq)
2614 {
2615 	struct scx_sched *sch;
2616 	struct task_struct *p;
2617 	struct rq_flags rf;
2618 	bool timed_out = false;
2619 
2620 	rq_lock_irqsave(rq, &rf);
2621 	sch = rcu_dereference_bh(scx_root);
2622 	if (unlikely(!sch))
2623 		goto out_unlock;
2624 
2625 	list_for_each_entry(p, &rq->scx.runnable_list, scx.runnable_node) {
2626 		unsigned long last_runnable = p->scx.runnable_at;
2627 
2628 		if (unlikely(time_after(jiffies,
2629 					last_runnable + scx_watchdog_timeout))) {
2630 			u32 dur_ms = jiffies_to_msecs(jiffies - last_runnable);
2631 
2632 			scx_exit(sch, SCX_EXIT_ERROR_STALL, 0,
2633 				 "%s[%d] failed to run for %u.%03us",
2634 				 p->comm, p->pid, dur_ms / 1000, dur_ms % 1000);
2635 			timed_out = true;
2636 			break;
2637 		}
2638 	}
2639 out_unlock:
2640 	rq_unlock_irqrestore(rq, &rf);
2641 	return timed_out;
2642 }
2643 
scx_watchdog_workfn(struct work_struct * work)2644 static void scx_watchdog_workfn(struct work_struct *work)
2645 {
2646 	int cpu;
2647 
2648 	WRITE_ONCE(scx_watchdog_timestamp, jiffies);
2649 
2650 	for_each_online_cpu(cpu) {
2651 		if (unlikely(check_rq_for_timeouts(cpu_rq(cpu))))
2652 			break;
2653 
2654 		cond_resched();
2655 	}
2656 	queue_delayed_work(system_unbound_wq, to_delayed_work(work),
2657 			   scx_watchdog_timeout / 2);
2658 }
2659 
scx_tick(struct rq * rq)2660 void scx_tick(struct rq *rq)
2661 {
2662 	struct scx_sched *sch;
2663 	unsigned long last_check;
2664 
2665 	if (!scx_enabled())
2666 		return;
2667 
2668 	sch = rcu_dereference_bh(scx_root);
2669 	if (unlikely(!sch))
2670 		return;
2671 
2672 	last_check = READ_ONCE(scx_watchdog_timestamp);
2673 	if (unlikely(time_after(jiffies,
2674 				last_check + READ_ONCE(scx_watchdog_timeout)))) {
2675 		u32 dur_ms = jiffies_to_msecs(jiffies - last_check);
2676 
2677 		scx_exit(sch, SCX_EXIT_ERROR_STALL, 0,
2678 			 "watchdog failed to check in for %u.%03us",
2679 			 dur_ms / 1000, dur_ms % 1000);
2680 	}
2681 
2682 	update_other_load_avgs(rq);
2683 }
2684 
task_tick_scx(struct rq * rq,struct task_struct * curr,int queued)2685 static void task_tick_scx(struct rq *rq, struct task_struct *curr, int queued)
2686 {
2687 	struct scx_sched *sch = scx_root;
2688 
2689 	update_curr_scx(rq);
2690 
2691 	/*
2692 	 * While disabling, always resched and refresh core-sched timestamp as
2693 	 * we can't trust the slice management or ops.core_sched_before().
2694 	 */
2695 	if (scx_rq_bypassing(rq)) {
2696 		curr->scx.slice = 0;
2697 		touch_core_sched(rq, curr);
2698 	} else if (SCX_HAS_OP(sch, tick)) {
2699 		SCX_CALL_OP_TASK(sch, SCX_KF_REST, tick, rq, curr);
2700 	}
2701 
2702 	if (!curr->scx.slice)
2703 		resched_curr(rq);
2704 }
2705 
2706 #ifdef CONFIG_EXT_GROUP_SCHED
tg_cgrp(struct task_group * tg)2707 static struct cgroup *tg_cgrp(struct task_group *tg)
2708 {
2709 	/*
2710 	 * If CGROUP_SCHED is disabled, @tg is NULL. If @tg is an autogroup,
2711 	 * @tg->css.cgroup is NULL. In both cases, @tg can be treated as the
2712 	 * root cgroup.
2713 	 */
2714 	if (tg && tg->css.cgroup)
2715 		return tg->css.cgroup;
2716 	else
2717 		return &cgrp_dfl_root.cgrp;
2718 }
2719 
2720 #define SCX_INIT_TASK_ARGS_CGROUP(tg)		.cgroup = tg_cgrp(tg),
2721 
2722 #else	/* CONFIG_EXT_GROUP_SCHED */
2723 
2724 #define SCX_INIT_TASK_ARGS_CGROUP(tg)
2725 
2726 #endif	/* CONFIG_EXT_GROUP_SCHED */
2727 
scx_get_task_state(const struct task_struct * p)2728 static enum scx_task_state scx_get_task_state(const struct task_struct *p)
2729 {
2730 	return (p->scx.flags & SCX_TASK_STATE_MASK) >> SCX_TASK_STATE_SHIFT;
2731 }
2732 
scx_set_task_state(struct task_struct * p,enum scx_task_state state)2733 static void scx_set_task_state(struct task_struct *p, enum scx_task_state state)
2734 {
2735 	enum scx_task_state prev_state = scx_get_task_state(p);
2736 	bool warn = false;
2737 
2738 	BUILD_BUG_ON(SCX_TASK_NR_STATES > (1 << SCX_TASK_STATE_BITS));
2739 
2740 	switch (state) {
2741 	case SCX_TASK_NONE:
2742 		break;
2743 	case SCX_TASK_INIT:
2744 		warn = prev_state != SCX_TASK_NONE;
2745 		break;
2746 	case SCX_TASK_READY:
2747 		warn = prev_state == SCX_TASK_NONE;
2748 		break;
2749 	case SCX_TASK_ENABLED:
2750 		warn = prev_state != SCX_TASK_READY;
2751 		break;
2752 	default:
2753 		warn = true;
2754 		return;
2755 	}
2756 
2757 	WARN_ONCE(warn, "sched_ext: Invalid task state transition %d -> %d for %s[%d]",
2758 		  prev_state, state, p->comm, p->pid);
2759 
2760 	p->scx.flags &= ~SCX_TASK_STATE_MASK;
2761 	p->scx.flags |= state << SCX_TASK_STATE_SHIFT;
2762 }
2763 
scx_init_task(struct task_struct * p,struct task_group * tg,bool fork)2764 static int scx_init_task(struct task_struct *p, struct task_group *tg, bool fork)
2765 {
2766 	struct scx_sched *sch = scx_root;
2767 	int ret;
2768 
2769 	p->scx.disallow = false;
2770 
2771 	if (SCX_HAS_OP(sch, init_task)) {
2772 		struct scx_init_task_args args = {
2773 			SCX_INIT_TASK_ARGS_CGROUP(tg)
2774 			.fork = fork,
2775 		};
2776 
2777 		ret = SCX_CALL_OP_RET(sch, SCX_KF_UNLOCKED, init_task, NULL,
2778 				      p, &args);
2779 		if (unlikely(ret)) {
2780 			ret = ops_sanitize_err(sch, "init_task", ret);
2781 			return ret;
2782 		}
2783 	}
2784 
2785 	scx_set_task_state(p, SCX_TASK_INIT);
2786 
2787 	if (p->scx.disallow) {
2788 		if (!fork) {
2789 			struct rq *rq;
2790 			struct rq_flags rf;
2791 
2792 			rq = task_rq_lock(p, &rf);
2793 
2794 			/*
2795 			 * We're in the load path and @p->policy will be applied
2796 			 * right after. Reverting @p->policy here and rejecting
2797 			 * %SCHED_EXT transitions from scx_check_setscheduler()
2798 			 * guarantees that if ops.init_task() sets @p->disallow,
2799 			 * @p can never be in SCX.
2800 			 */
2801 			if (p->policy == SCHED_EXT) {
2802 				p->policy = SCHED_NORMAL;
2803 				atomic_long_inc(&scx_nr_rejected);
2804 			}
2805 
2806 			task_rq_unlock(rq, p, &rf);
2807 		} else if (p->policy == SCHED_EXT) {
2808 			scx_error(sch, "ops.init_task() set task->scx.disallow for %s[%d] during fork",
2809 				  p->comm, p->pid);
2810 		}
2811 	}
2812 
2813 	p->scx.flags |= SCX_TASK_RESET_RUNNABLE_AT;
2814 	return 0;
2815 }
2816 
scx_enable_task(struct task_struct * p)2817 static void scx_enable_task(struct task_struct *p)
2818 {
2819 	struct scx_sched *sch = scx_root;
2820 	struct rq *rq = task_rq(p);
2821 	u32 weight;
2822 
2823 	lockdep_assert_rq_held(rq);
2824 
2825 	/*
2826 	 * Set the weight before calling ops.enable() so that the scheduler
2827 	 * doesn't see a stale value if they inspect the task struct.
2828 	 */
2829 	if (task_has_idle_policy(p))
2830 		weight = WEIGHT_IDLEPRIO;
2831 	else
2832 		weight = sched_prio_to_weight[p->static_prio - MAX_RT_PRIO];
2833 
2834 	p->scx.weight = sched_weight_to_cgroup(weight);
2835 
2836 	if (SCX_HAS_OP(sch, enable))
2837 		SCX_CALL_OP_TASK(sch, SCX_KF_REST, enable, rq, p);
2838 	scx_set_task_state(p, SCX_TASK_ENABLED);
2839 
2840 	if (SCX_HAS_OP(sch, set_weight))
2841 		SCX_CALL_OP_TASK(sch, SCX_KF_REST, set_weight, rq,
2842 				 p, p->scx.weight);
2843 }
2844 
scx_disable_task(struct task_struct * p)2845 static void scx_disable_task(struct task_struct *p)
2846 {
2847 	struct scx_sched *sch = scx_root;
2848 	struct rq *rq = task_rq(p);
2849 
2850 	lockdep_assert_rq_held(rq);
2851 	WARN_ON_ONCE(scx_get_task_state(p) != SCX_TASK_ENABLED);
2852 
2853 	if (SCX_HAS_OP(sch, disable))
2854 		SCX_CALL_OP_TASK(sch, SCX_KF_REST, disable, rq, p);
2855 	scx_set_task_state(p, SCX_TASK_READY);
2856 }
2857 
scx_exit_task(struct task_struct * p)2858 static void scx_exit_task(struct task_struct *p)
2859 {
2860 	struct scx_sched *sch = scx_root;
2861 	struct scx_exit_task_args args = {
2862 		.cancelled = false,
2863 	};
2864 
2865 	lockdep_assert_rq_held(task_rq(p));
2866 
2867 	switch (scx_get_task_state(p)) {
2868 	case SCX_TASK_NONE:
2869 		return;
2870 	case SCX_TASK_INIT:
2871 		args.cancelled = true;
2872 		break;
2873 	case SCX_TASK_READY:
2874 		break;
2875 	case SCX_TASK_ENABLED:
2876 		scx_disable_task(p);
2877 		break;
2878 	default:
2879 		WARN_ON_ONCE(true);
2880 		return;
2881 	}
2882 
2883 	if (SCX_HAS_OP(sch, exit_task))
2884 		SCX_CALL_OP_TASK(sch, SCX_KF_REST, exit_task, task_rq(p),
2885 				 p, &args);
2886 	scx_set_task_state(p, SCX_TASK_NONE);
2887 }
2888 
init_scx_entity(struct sched_ext_entity * scx)2889 void init_scx_entity(struct sched_ext_entity *scx)
2890 {
2891 	memset(scx, 0, sizeof(*scx));
2892 	INIT_LIST_HEAD(&scx->dsq_list.node);
2893 	RB_CLEAR_NODE(&scx->dsq_priq);
2894 	scx->sticky_cpu = -1;
2895 	scx->holding_cpu = -1;
2896 	INIT_LIST_HEAD(&scx->runnable_node);
2897 	scx->runnable_at = jiffies;
2898 	scx->ddsp_dsq_id = SCX_DSQ_INVALID;
2899 	scx->slice = SCX_SLICE_DFL;
2900 }
2901 
scx_pre_fork(struct task_struct * p)2902 void scx_pre_fork(struct task_struct *p)
2903 {
2904 	/*
2905 	 * BPF scheduler enable/disable paths want to be able to iterate and
2906 	 * update all tasks which can become complex when racing forks. As
2907 	 * enable/disable are very cold paths, let's use a percpu_rwsem to
2908 	 * exclude forks.
2909 	 */
2910 	percpu_down_read(&scx_fork_rwsem);
2911 }
2912 
scx_fork(struct task_struct * p)2913 int scx_fork(struct task_struct *p)
2914 {
2915 	percpu_rwsem_assert_held(&scx_fork_rwsem);
2916 
2917 	if (scx_init_task_enabled)
2918 		return scx_init_task(p, task_group(p), true);
2919 	else
2920 		return 0;
2921 }
2922 
scx_post_fork(struct task_struct * p)2923 void scx_post_fork(struct task_struct *p)
2924 {
2925 	if (scx_init_task_enabled) {
2926 		scx_set_task_state(p, SCX_TASK_READY);
2927 
2928 		/*
2929 		 * Enable the task immediately if it's running on sched_ext.
2930 		 * Otherwise, it'll be enabled in switching_to_scx() if and
2931 		 * when it's ever configured to run with a SCHED_EXT policy.
2932 		 */
2933 		if (p->sched_class == &ext_sched_class) {
2934 			struct rq_flags rf;
2935 			struct rq *rq;
2936 
2937 			rq = task_rq_lock(p, &rf);
2938 			scx_enable_task(p);
2939 			task_rq_unlock(rq, p, &rf);
2940 		}
2941 	}
2942 
2943 	spin_lock_irq(&scx_tasks_lock);
2944 	list_add_tail(&p->scx.tasks_node, &scx_tasks);
2945 	spin_unlock_irq(&scx_tasks_lock);
2946 
2947 	percpu_up_read(&scx_fork_rwsem);
2948 }
2949 
scx_cancel_fork(struct task_struct * p)2950 void scx_cancel_fork(struct task_struct *p)
2951 {
2952 	if (scx_enabled()) {
2953 		struct rq *rq;
2954 		struct rq_flags rf;
2955 
2956 		rq = task_rq_lock(p, &rf);
2957 		WARN_ON_ONCE(scx_get_task_state(p) >= SCX_TASK_READY);
2958 		scx_exit_task(p);
2959 		task_rq_unlock(rq, p, &rf);
2960 	}
2961 
2962 	percpu_up_read(&scx_fork_rwsem);
2963 }
2964 
sched_ext_free(struct task_struct * p)2965 void sched_ext_free(struct task_struct *p)
2966 {
2967 	unsigned long flags;
2968 
2969 	spin_lock_irqsave(&scx_tasks_lock, flags);
2970 	list_del_init(&p->scx.tasks_node);
2971 	spin_unlock_irqrestore(&scx_tasks_lock, flags);
2972 
2973 	/*
2974 	 * @p is off scx_tasks and wholly ours. scx_enable()'s READY -> ENABLED
2975 	 * transitions can't race us. Disable ops for @p.
2976 	 */
2977 	if (scx_get_task_state(p) != SCX_TASK_NONE) {
2978 		struct rq_flags rf;
2979 		struct rq *rq;
2980 
2981 		rq = task_rq_lock(p, &rf);
2982 		scx_exit_task(p);
2983 		task_rq_unlock(rq, p, &rf);
2984 	}
2985 }
2986 
reweight_task_scx(struct rq * rq,struct task_struct * p,const struct load_weight * lw)2987 static void reweight_task_scx(struct rq *rq, struct task_struct *p,
2988 			      const struct load_weight *lw)
2989 {
2990 	struct scx_sched *sch = scx_root;
2991 
2992 	lockdep_assert_rq_held(task_rq(p));
2993 
2994 	p->scx.weight = sched_weight_to_cgroup(scale_load_down(lw->weight));
2995 	if (SCX_HAS_OP(sch, set_weight))
2996 		SCX_CALL_OP_TASK(sch, SCX_KF_REST, set_weight, rq,
2997 				 p, p->scx.weight);
2998 }
2999 
prio_changed_scx(struct rq * rq,struct task_struct * p,int oldprio)3000 static void prio_changed_scx(struct rq *rq, struct task_struct *p, int oldprio)
3001 {
3002 }
3003 
switching_to_scx(struct rq * rq,struct task_struct * p)3004 static void switching_to_scx(struct rq *rq, struct task_struct *p)
3005 {
3006 	struct scx_sched *sch = scx_root;
3007 
3008 	scx_enable_task(p);
3009 
3010 	/*
3011 	 * set_cpus_allowed_scx() is not called while @p is associated with a
3012 	 * different scheduler class. Keep the BPF scheduler up-to-date.
3013 	 */
3014 	if (SCX_HAS_OP(sch, set_cpumask))
3015 		SCX_CALL_OP_TASK(sch, SCX_KF_REST, set_cpumask, rq,
3016 				 p, (struct cpumask *)p->cpus_ptr);
3017 }
3018 
switched_from_scx(struct rq * rq,struct task_struct * p)3019 static void switched_from_scx(struct rq *rq, struct task_struct *p)
3020 {
3021 	scx_disable_task(p);
3022 }
3023 
wakeup_preempt_scx(struct rq * rq,struct task_struct * p,int wake_flags)3024 static void wakeup_preempt_scx(struct rq *rq, struct task_struct *p,int wake_flags) {}
switched_to_scx(struct rq * rq,struct task_struct * p)3025 static void switched_to_scx(struct rq *rq, struct task_struct *p) {}
3026 
scx_check_setscheduler(struct task_struct * p,int policy)3027 int scx_check_setscheduler(struct task_struct *p, int policy)
3028 {
3029 	lockdep_assert_rq_held(task_rq(p));
3030 
3031 	/* if disallow, reject transitioning into SCX */
3032 	if (scx_enabled() && READ_ONCE(p->scx.disallow) &&
3033 	    p->policy != policy && policy == SCHED_EXT)
3034 		return -EACCES;
3035 
3036 	return 0;
3037 }
3038 
3039 #ifdef CONFIG_NO_HZ_FULL
scx_can_stop_tick(struct rq * rq)3040 bool scx_can_stop_tick(struct rq *rq)
3041 {
3042 	struct task_struct *p = rq->curr;
3043 
3044 	if (scx_rq_bypassing(rq))
3045 		return false;
3046 
3047 	if (p->sched_class != &ext_sched_class)
3048 		return true;
3049 
3050 	/*
3051 	 * @rq can dispatch from different DSQs, so we can't tell whether it
3052 	 * needs the tick or not by looking at nr_running. Allow stopping ticks
3053 	 * iff the BPF scheduler indicated so. See set_next_task_scx().
3054 	 */
3055 	return rq->scx.flags & SCX_RQ_CAN_STOP_TICK;
3056 }
3057 #endif
3058 
3059 #ifdef CONFIG_EXT_GROUP_SCHED
3060 
3061 DEFINE_STATIC_PERCPU_RWSEM(scx_cgroup_ops_rwsem);
3062 static bool scx_cgroup_enabled;
3063 
scx_tg_init(struct task_group * tg)3064 void scx_tg_init(struct task_group *tg)
3065 {
3066 	tg->scx.weight = CGROUP_WEIGHT_DFL;
3067 	tg->scx.bw_period_us = default_bw_period_us();
3068 	tg->scx.bw_quota_us = RUNTIME_INF;
3069 }
3070 
scx_tg_online(struct task_group * tg)3071 int scx_tg_online(struct task_group *tg)
3072 {
3073 	struct scx_sched *sch = scx_root;
3074 	int ret = 0;
3075 
3076 	WARN_ON_ONCE(tg->scx.flags & (SCX_TG_ONLINE | SCX_TG_INITED));
3077 
3078 	if (scx_cgroup_enabled) {
3079 		if (SCX_HAS_OP(sch, cgroup_init)) {
3080 			struct scx_cgroup_init_args args =
3081 				{ .weight = tg->scx.weight,
3082 				  .bw_period_us = tg->scx.bw_period_us,
3083 				  .bw_quota_us = tg->scx.bw_quota_us,
3084 				  .bw_burst_us = tg->scx.bw_burst_us };
3085 
3086 			ret = SCX_CALL_OP_RET(sch, SCX_KF_UNLOCKED, cgroup_init,
3087 					      NULL, tg->css.cgroup, &args);
3088 			if (ret)
3089 				ret = ops_sanitize_err(sch, "cgroup_init", ret);
3090 		}
3091 		if (ret == 0)
3092 			tg->scx.flags |= SCX_TG_ONLINE | SCX_TG_INITED;
3093 	} else {
3094 		tg->scx.flags |= SCX_TG_ONLINE;
3095 	}
3096 
3097 	return ret;
3098 }
3099 
scx_tg_offline(struct task_group * tg)3100 void scx_tg_offline(struct task_group *tg)
3101 {
3102 	struct scx_sched *sch = scx_root;
3103 
3104 	WARN_ON_ONCE(!(tg->scx.flags & SCX_TG_ONLINE));
3105 
3106 	if (scx_cgroup_enabled && SCX_HAS_OP(sch, cgroup_exit) &&
3107 	    (tg->scx.flags & SCX_TG_INITED))
3108 		SCX_CALL_OP(sch, SCX_KF_UNLOCKED, cgroup_exit, NULL,
3109 			    tg->css.cgroup);
3110 	tg->scx.flags &= ~(SCX_TG_ONLINE | SCX_TG_INITED);
3111 }
3112 
scx_cgroup_can_attach(struct cgroup_taskset * tset)3113 int scx_cgroup_can_attach(struct cgroup_taskset *tset)
3114 {
3115 	struct scx_sched *sch = scx_root;
3116 	struct cgroup_subsys_state *css;
3117 	struct task_struct *p;
3118 	int ret;
3119 
3120 	if (!scx_cgroup_enabled)
3121 		return 0;
3122 
3123 	cgroup_taskset_for_each(p, css, tset) {
3124 		struct cgroup *from = tg_cgrp(task_group(p));
3125 		struct cgroup *to = tg_cgrp(css_tg(css));
3126 
3127 		WARN_ON_ONCE(p->scx.cgrp_moving_from);
3128 
3129 		/*
3130 		 * sched_move_task() omits identity migrations. Let's match the
3131 		 * behavior so that ops.cgroup_prep_move() and ops.cgroup_move()
3132 		 * always match one-to-one.
3133 		 */
3134 		if (from == to)
3135 			continue;
3136 
3137 		if (SCX_HAS_OP(sch, cgroup_prep_move)) {
3138 			ret = SCX_CALL_OP_RET(sch, SCX_KF_UNLOCKED,
3139 					      cgroup_prep_move, NULL,
3140 					      p, from, css->cgroup);
3141 			if (ret)
3142 				goto err;
3143 		}
3144 
3145 		p->scx.cgrp_moving_from = from;
3146 	}
3147 
3148 	return 0;
3149 
3150 err:
3151 	cgroup_taskset_for_each(p, css, tset) {
3152 		if (SCX_HAS_OP(sch, cgroup_cancel_move) &&
3153 		    p->scx.cgrp_moving_from)
3154 			SCX_CALL_OP(sch, SCX_KF_UNLOCKED, cgroup_cancel_move, NULL,
3155 				    p, p->scx.cgrp_moving_from, css->cgroup);
3156 		p->scx.cgrp_moving_from = NULL;
3157 	}
3158 
3159 	return ops_sanitize_err(sch, "cgroup_prep_move", ret);
3160 }
3161 
scx_cgroup_move_task(struct task_struct * p)3162 void scx_cgroup_move_task(struct task_struct *p)
3163 {
3164 	struct scx_sched *sch = scx_root;
3165 
3166 	if (!scx_cgroup_enabled)
3167 		return;
3168 
3169 	/*
3170 	 * @p must have ops.cgroup_prep_move() called on it and thus
3171 	 * cgrp_moving_from set.
3172 	 */
3173 	if (SCX_HAS_OP(sch, cgroup_move) &&
3174 	    !WARN_ON_ONCE(!p->scx.cgrp_moving_from))
3175 		SCX_CALL_OP_TASK(sch, SCX_KF_UNLOCKED, cgroup_move, NULL,
3176 				 p, p->scx.cgrp_moving_from,
3177 				 tg_cgrp(task_group(p)));
3178 	p->scx.cgrp_moving_from = NULL;
3179 }
3180 
scx_cgroup_cancel_attach(struct cgroup_taskset * tset)3181 void scx_cgroup_cancel_attach(struct cgroup_taskset *tset)
3182 {
3183 	struct scx_sched *sch = scx_root;
3184 	struct cgroup_subsys_state *css;
3185 	struct task_struct *p;
3186 
3187 	if (!scx_cgroup_enabled)
3188 		return;
3189 
3190 	cgroup_taskset_for_each(p, css, tset) {
3191 		if (SCX_HAS_OP(sch, cgroup_cancel_move) &&
3192 		    p->scx.cgrp_moving_from)
3193 			SCX_CALL_OP(sch, SCX_KF_UNLOCKED, cgroup_cancel_move, NULL,
3194 				    p, p->scx.cgrp_moving_from, css->cgroup);
3195 		p->scx.cgrp_moving_from = NULL;
3196 	}
3197 }
3198 
scx_group_set_weight(struct task_group * tg,unsigned long weight)3199 void scx_group_set_weight(struct task_group *tg, unsigned long weight)
3200 {
3201 	struct scx_sched *sch = scx_root;
3202 
3203 	percpu_down_read(&scx_cgroup_ops_rwsem);
3204 
3205 	if (scx_cgroup_enabled && SCX_HAS_OP(sch, cgroup_set_weight) &&
3206 	    tg->scx.weight != weight)
3207 		SCX_CALL_OP(sch, SCX_KF_UNLOCKED, cgroup_set_weight, NULL,
3208 			    tg_cgrp(tg), weight);
3209 
3210 	tg->scx.weight = weight;
3211 
3212 	percpu_up_read(&scx_cgroup_ops_rwsem);
3213 }
3214 
scx_group_set_idle(struct task_group * tg,bool idle)3215 void scx_group_set_idle(struct task_group *tg, bool idle)
3216 {
3217 	/* TODO: Implement ops->cgroup_set_idle() */
3218 }
3219 
scx_group_set_bandwidth(struct task_group * tg,u64 period_us,u64 quota_us,u64 burst_us)3220 void scx_group_set_bandwidth(struct task_group *tg,
3221 			     u64 period_us, u64 quota_us, u64 burst_us)
3222 {
3223 	struct scx_sched *sch = scx_root;
3224 
3225 	percpu_down_read(&scx_cgroup_ops_rwsem);
3226 
3227 	if (scx_cgroup_enabled && SCX_HAS_OP(sch, cgroup_set_bandwidth) &&
3228 	    (tg->scx.bw_period_us != period_us ||
3229 	     tg->scx.bw_quota_us != quota_us ||
3230 	     tg->scx.bw_burst_us != burst_us))
3231 		SCX_CALL_OP(sch, SCX_KF_UNLOCKED, cgroup_set_bandwidth, NULL,
3232 			    tg_cgrp(tg), period_us, quota_us, burst_us);
3233 
3234 	tg->scx.bw_period_us = period_us;
3235 	tg->scx.bw_quota_us = quota_us;
3236 	tg->scx.bw_burst_us = burst_us;
3237 
3238 	percpu_up_read(&scx_cgroup_ops_rwsem);
3239 }
3240 
scx_cgroup_lock(void)3241 static void scx_cgroup_lock(void)
3242 {
3243 	percpu_down_write(&scx_cgroup_ops_rwsem);
3244 	cgroup_lock();
3245 }
3246 
scx_cgroup_unlock(void)3247 static void scx_cgroup_unlock(void)
3248 {
3249 	cgroup_unlock();
3250 	percpu_up_write(&scx_cgroup_ops_rwsem);
3251 }
3252 
3253 #else	/* CONFIG_EXT_GROUP_SCHED */
3254 
scx_cgroup_lock(void)3255 static void scx_cgroup_lock(void) {}
scx_cgroup_unlock(void)3256 static void scx_cgroup_unlock(void) {}
3257 
3258 #endif	/* CONFIG_EXT_GROUP_SCHED */
3259 
3260 /*
3261  * Omitted operations:
3262  *
3263  * - wakeup_preempt: NOOP as it isn't useful in the wakeup path because the task
3264  *   isn't tied to the CPU at that point. Preemption is implemented by resetting
3265  *   the victim task's slice to 0 and triggering reschedule on the target CPU.
3266  *
3267  * - migrate_task_rq: Unnecessary as task to cpu mapping is transient.
3268  *
3269  * - task_fork/dead: We need fork/dead notifications for all tasks regardless of
3270  *   their current sched_class. Call them directly from sched core instead.
3271  */
3272 DEFINE_SCHED_CLASS(ext) = {
3273 	.enqueue_task		= enqueue_task_scx,
3274 	.dequeue_task		= dequeue_task_scx,
3275 	.yield_task		= yield_task_scx,
3276 	.yield_to_task		= yield_to_task_scx,
3277 
3278 	.wakeup_preempt		= wakeup_preempt_scx,
3279 
3280 	.balance		= balance_scx,
3281 	.pick_task		= pick_task_scx,
3282 
3283 	.put_prev_task		= put_prev_task_scx,
3284 	.set_next_task		= set_next_task_scx,
3285 
3286 	.select_task_rq		= select_task_rq_scx,
3287 	.task_woken		= task_woken_scx,
3288 	.set_cpus_allowed	= set_cpus_allowed_scx,
3289 
3290 	.rq_online		= rq_online_scx,
3291 	.rq_offline		= rq_offline_scx,
3292 
3293 	.task_tick		= task_tick_scx,
3294 
3295 	.switching_to		= switching_to_scx,
3296 	.switched_from		= switched_from_scx,
3297 	.switched_to		= switched_to_scx,
3298 	.reweight_task		= reweight_task_scx,
3299 	.prio_changed		= prio_changed_scx,
3300 
3301 	.update_curr		= update_curr_scx,
3302 
3303 #ifdef CONFIG_UCLAMP_TASK
3304 	.uclamp_enabled		= 1,
3305 #endif
3306 };
3307 
init_dsq(struct scx_dispatch_q * dsq,u64 dsq_id)3308 static void init_dsq(struct scx_dispatch_q *dsq, u64 dsq_id)
3309 {
3310 	memset(dsq, 0, sizeof(*dsq));
3311 
3312 	raw_spin_lock_init(&dsq->lock);
3313 	INIT_LIST_HEAD(&dsq->list);
3314 	dsq->id = dsq_id;
3315 }
3316 
free_dsq_irq_workfn(struct irq_work * irq_work)3317 static void free_dsq_irq_workfn(struct irq_work *irq_work)
3318 {
3319 	struct llist_node *to_free = llist_del_all(&dsqs_to_free);
3320 	struct scx_dispatch_q *dsq, *tmp_dsq;
3321 
3322 	llist_for_each_entry_safe(dsq, tmp_dsq, to_free, free_node)
3323 		kfree_rcu(dsq, rcu);
3324 }
3325 
3326 static DEFINE_IRQ_WORK(free_dsq_irq_work, free_dsq_irq_workfn);
3327 
destroy_dsq(struct scx_sched * sch,u64 dsq_id)3328 static void destroy_dsq(struct scx_sched *sch, u64 dsq_id)
3329 {
3330 	struct scx_dispatch_q *dsq;
3331 	unsigned long flags;
3332 
3333 	rcu_read_lock();
3334 
3335 	dsq = find_user_dsq(sch, dsq_id);
3336 	if (!dsq)
3337 		goto out_unlock_rcu;
3338 
3339 	raw_spin_lock_irqsave(&dsq->lock, flags);
3340 
3341 	if (dsq->nr) {
3342 		scx_error(sch, "attempting to destroy in-use dsq 0x%016llx (nr=%u)",
3343 			  dsq->id, dsq->nr);
3344 		goto out_unlock_dsq;
3345 	}
3346 
3347 	if (rhashtable_remove_fast(&sch->dsq_hash, &dsq->hash_node,
3348 				   dsq_hash_params))
3349 		goto out_unlock_dsq;
3350 
3351 	/*
3352 	 * Mark dead by invalidating ->id to prevent dispatch_enqueue() from
3353 	 * queueing more tasks. As this function can be called from anywhere,
3354 	 * freeing is bounced through an irq work to avoid nesting RCU
3355 	 * operations inside scheduler locks.
3356 	 */
3357 	dsq->id = SCX_DSQ_INVALID;
3358 	llist_add(&dsq->free_node, &dsqs_to_free);
3359 	irq_work_queue(&free_dsq_irq_work);
3360 
3361 out_unlock_dsq:
3362 	raw_spin_unlock_irqrestore(&dsq->lock, flags);
3363 out_unlock_rcu:
3364 	rcu_read_unlock();
3365 }
3366 
3367 #ifdef CONFIG_EXT_GROUP_SCHED
scx_cgroup_exit(struct scx_sched * sch)3368 static void scx_cgroup_exit(struct scx_sched *sch)
3369 {
3370 	struct cgroup_subsys_state *css;
3371 
3372 	scx_cgroup_enabled = false;
3373 
3374 	/*
3375 	 * scx_tg_on/offline() are excluded through cgroup_lock(). If we walk
3376 	 * cgroups and exit all the inited ones, all online cgroups are exited.
3377 	 */
3378 	css_for_each_descendant_post(css, &root_task_group.css) {
3379 		struct task_group *tg = css_tg(css);
3380 
3381 		if (!(tg->scx.flags & SCX_TG_INITED))
3382 			continue;
3383 		tg->scx.flags &= ~SCX_TG_INITED;
3384 
3385 		if (!sch->ops.cgroup_exit)
3386 			continue;
3387 
3388 		SCX_CALL_OP(sch, SCX_KF_UNLOCKED, cgroup_exit, NULL,
3389 			    css->cgroup);
3390 	}
3391 }
3392 
scx_cgroup_init(struct scx_sched * sch)3393 static int scx_cgroup_init(struct scx_sched *sch)
3394 {
3395 	struct cgroup_subsys_state *css;
3396 	int ret;
3397 
3398 	/*
3399 	 * scx_tg_on/offline() are excluded through cgroup_lock(). If we walk
3400 	 * cgroups and init, all online cgroups are initialized.
3401 	 */
3402 	css_for_each_descendant_pre(css, &root_task_group.css) {
3403 		struct task_group *tg = css_tg(css);
3404 		struct scx_cgroup_init_args args = {
3405 			.weight = tg->scx.weight,
3406 			.bw_period_us = tg->scx.bw_period_us,
3407 			.bw_quota_us = tg->scx.bw_quota_us,
3408 			.bw_burst_us = tg->scx.bw_burst_us,
3409 		};
3410 
3411 		if ((tg->scx.flags &
3412 		     (SCX_TG_ONLINE | SCX_TG_INITED)) != SCX_TG_ONLINE)
3413 			continue;
3414 
3415 		if (!sch->ops.cgroup_init) {
3416 			tg->scx.flags |= SCX_TG_INITED;
3417 			continue;
3418 		}
3419 
3420 		ret = SCX_CALL_OP_RET(sch, SCX_KF_UNLOCKED, cgroup_init, NULL,
3421 				      css->cgroup, &args);
3422 		if (ret) {
3423 			css_put(css);
3424 			scx_error(sch, "ops.cgroup_init() failed (%d)", ret);
3425 			return ret;
3426 		}
3427 		tg->scx.flags |= SCX_TG_INITED;
3428 	}
3429 
3430 	WARN_ON_ONCE(scx_cgroup_enabled);
3431 	scx_cgroup_enabled = true;
3432 
3433 	return 0;
3434 }
3435 
3436 #else
scx_cgroup_exit(struct scx_sched * sch)3437 static void scx_cgroup_exit(struct scx_sched *sch) {}
scx_cgroup_init(struct scx_sched * sch)3438 static int scx_cgroup_init(struct scx_sched *sch) { return 0; }
3439 #endif
3440 
3441 
3442 /********************************************************************************
3443  * Sysfs interface and ops enable/disable.
3444  */
3445 
3446 #define SCX_ATTR(_name)								\
3447 	static struct kobj_attribute scx_attr_##_name = {			\
3448 		.attr = { .name = __stringify(_name), .mode = 0444 },		\
3449 		.show = scx_attr_##_name##_show,				\
3450 	}
3451 
scx_attr_state_show(struct kobject * kobj,struct kobj_attribute * ka,char * buf)3452 static ssize_t scx_attr_state_show(struct kobject *kobj,
3453 				   struct kobj_attribute *ka, char *buf)
3454 {
3455 	return sysfs_emit(buf, "%s\n", scx_enable_state_str[scx_enable_state()]);
3456 }
3457 SCX_ATTR(state);
3458 
scx_attr_switch_all_show(struct kobject * kobj,struct kobj_attribute * ka,char * buf)3459 static ssize_t scx_attr_switch_all_show(struct kobject *kobj,
3460 					struct kobj_attribute *ka, char *buf)
3461 {
3462 	return sysfs_emit(buf, "%d\n", READ_ONCE(scx_switching_all));
3463 }
3464 SCX_ATTR(switch_all);
3465 
scx_attr_nr_rejected_show(struct kobject * kobj,struct kobj_attribute * ka,char * buf)3466 static ssize_t scx_attr_nr_rejected_show(struct kobject *kobj,
3467 					 struct kobj_attribute *ka, char *buf)
3468 {
3469 	return sysfs_emit(buf, "%ld\n", atomic_long_read(&scx_nr_rejected));
3470 }
3471 SCX_ATTR(nr_rejected);
3472 
scx_attr_hotplug_seq_show(struct kobject * kobj,struct kobj_attribute * ka,char * buf)3473 static ssize_t scx_attr_hotplug_seq_show(struct kobject *kobj,
3474 					 struct kobj_attribute *ka, char *buf)
3475 {
3476 	return sysfs_emit(buf, "%ld\n", atomic_long_read(&scx_hotplug_seq));
3477 }
3478 SCX_ATTR(hotplug_seq);
3479 
scx_attr_enable_seq_show(struct kobject * kobj,struct kobj_attribute * ka,char * buf)3480 static ssize_t scx_attr_enable_seq_show(struct kobject *kobj,
3481 					struct kobj_attribute *ka, char *buf)
3482 {
3483 	return sysfs_emit(buf, "%ld\n", atomic_long_read(&scx_enable_seq));
3484 }
3485 SCX_ATTR(enable_seq);
3486 
3487 static struct attribute *scx_global_attrs[] = {
3488 	&scx_attr_state.attr,
3489 	&scx_attr_switch_all.attr,
3490 	&scx_attr_nr_rejected.attr,
3491 	&scx_attr_hotplug_seq.attr,
3492 	&scx_attr_enable_seq.attr,
3493 	NULL,
3494 };
3495 
3496 static const struct attribute_group scx_global_attr_group = {
3497 	.attrs = scx_global_attrs,
3498 };
3499 
3500 static void free_exit_info(struct scx_exit_info *ei);
3501 
scx_sched_free_rcu_work(struct work_struct * work)3502 static void scx_sched_free_rcu_work(struct work_struct *work)
3503 {
3504 	struct rcu_work *rcu_work = to_rcu_work(work);
3505 	struct scx_sched *sch = container_of(rcu_work, struct scx_sched, rcu_work);
3506 	struct rhashtable_iter rht_iter;
3507 	struct scx_dispatch_q *dsq;
3508 	int node;
3509 
3510 	irq_work_sync(&sch->error_irq_work);
3511 	kthread_stop(sch->helper->task);
3512 
3513 	free_percpu(sch->pcpu);
3514 
3515 	for_each_node_state(node, N_POSSIBLE)
3516 		kfree(sch->global_dsqs[node]);
3517 	kfree(sch->global_dsqs);
3518 
3519 	rhashtable_walk_enter(&sch->dsq_hash, &rht_iter);
3520 	do {
3521 		rhashtable_walk_start(&rht_iter);
3522 
3523 		while ((dsq = rhashtable_walk_next(&rht_iter)) && !IS_ERR(dsq))
3524 			destroy_dsq(sch, dsq->id);
3525 
3526 		rhashtable_walk_stop(&rht_iter);
3527 	} while (dsq == ERR_PTR(-EAGAIN));
3528 	rhashtable_walk_exit(&rht_iter);
3529 
3530 	rhashtable_free_and_destroy(&sch->dsq_hash, NULL, NULL);
3531 	free_exit_info(sch->exit_info);
3532 	kfree(sch);
3533 }
3534 
scx_kobj_release(struct kobject * kobj)3535 static void scx_kobj_release(struct kobject *kobj)
3536 {
3537 	struct scx_sched *sch = container_of(kobj, struct scx_sched, kobj);
3538 
3539 	INIT_RCU_WORK(&sch->rcu_work, scx_sched_free_rcu_work);
3540 	queue_rcu_work(system_unbound_wq, &sch->rcu_work);
3541 }
3542 
scx_attr_ops_show(struct kobject * kobj,struct kobj_attribute * ka,char * buf)3543 static ssize_t scx_attr_ops_show(struct kobject *kobj,
3544 				 struct kobj_attribute *ka, char *buf)
3545 {
3546 	return sysfs_emit(buf, "%s\n", scx_root->ops.name);
3547 }
3548 SCX_ATTR(ops);
3549 
3550 #define scx_attr_event_show(buf, at, events, kind) ({				\
3551 	sysfs_emit_at(buf, at, "%s %llu\n", #kind, (events)->kind);		\
3552 })
3553 
scx_attr_events_show(struct kobject * kobj,struct kobj_attribute * ka,char * buf)3554 static ssize_t scx_attr_events_show(struct kobject *kobj,
3555 				    struct kobj_attribute *ka, char *buf)
3556 {
3557 	struct scx_sched *sch = container_of(kobj, struct scx_sched, kobj);
3558 	struct scx_event_stats events;
3559 	int at = 0;
3560 
3561 	scx_read_events(sch, &events);
3562 	at += scx_attr_event_show(buf, at, &events, SCX_EV_SELECT_CPU_FALLBACK);
3563 	at += scx_attr_event_show(buf, at, &events, SCX_EV_DISPATCH_LOCAL_DSQ_OFFLINE);
3564 	at += scx_attr_event_show(buf, at, &events, SCX_EV_DISPATCH_KEEP_LAST);
3565 	at += scx_attr_event_show(buf, at, &events, SCX_EV_ENQ_SKIP_EXITING);
3566 	at += scx_attr_event_show(buf, at, &events, SCX_EV_ENQ_SKIP_MIGRATION_DISABLED);
3567 	at += scx_attr_event_show(buf, at, &events, SCX_EV_REFILL_SLICE_DFL);
3568 	at += scx_attr_event_show(buf, at, &events, SCX_EV_BYPASS_DURATION);
3569 	at += scx_attr_event_show(buf, at, &events, SCX_EV_BYPASS_DISPATCH);
3570 	at += scx_attr_event_show(buf, at, &events, SCX_EV_BYPASS_ACTIVATE);
3571 	return at;
3572 }
3573 SCX_ATTR(events);
3574 
3575 static struct attribute *scx_sched_attrs[] = {
3576 	&scx_attr_ops.attr,
3577 	&scx_attr_events.attr,
3578 	NULL,
3579 };
3580 ATTRIBUTE_GROUPS(scx_sched);
3581 
3582 static const struct kobj_type scx_ktype = {
3583 	.release = scx_kobj_release,
3584 	.sysfs_ops = &kobj_sysfs_ops,
3585 	.default_groups = scx_sched_groups,
3586 };
3587 
scx_uevent(const struct kobject * kobj,struct kobj_uevent_env * env)3588 static int scx_uevent(const struct kobject *kobj, struct kobj_uevent_env *env)
3589 {
3590 	return add_uevent_var(env, "SCXOPS=%s", scx_root->ops.name);
3591 }
3592 
3593 static const struct kset_uevent_ops scx_uevent_ops = {
3594 	.uevent = scx_uevent,
3595 };
3596 
3597 /*
3598  * Used by sched_fork() and __setscheduler_prio() to pick the matching
3599  * sched_class. dl/rt are already handled.
3600  */
task_should_scx(int policy)3601 bool task_should_scx(int policy)
3602 {
3603 	if (!scx_enabled() || unlikely(scx_enable_state() == SCX_DISABLING))
3604 		return false;
3605 	if (READ_ONCE(scx_switching_all))
3606 		return true;
3607 	return policy == SCHED_EXT;
3608 }
3609 
scx_allow_ttwu_queue(const struct task_struct * p)3610 bool scx_allow_ttwu_queue(const struct task_struct *p)
3611 {
3612 	struct scx_sched *sch;
3613 
3614 	if (!scx_enabled())
3615 		return true;
3616 
3617 	sch = rcu_dereference_sched(scx_root);
3618 	if (unlikely(!sch))
3619 		return true;
3620 
3621 	if (sch->ops.flags & SCX_OPS_ALLOW_QUEUED_WAKEUP)
3622 		return true;
3623 
3624 	if (unlikely(p->sched_class != &ext_sched_class))
3625 		return true;
3626 
3627 	return false;
3628 }
3629 
3630 /**
3631  * scx_rcu_cpu_stall - sched_ext RCU CPU stall handler
3632  *
3633  * While there are various reasons why RCU CPU stalls can occur on a system
3634  * that may not be caused by the current BPF scheduler, try kicking out the
3635  * current scheduler in an attempt to recover the system to a good state before
3636  * issuing panics.
3637  */
scx_rcu_cpu_stall(void)3638 bool scx_rcu_cpu_stall(void)
3639 {
3640 	struct scx_sched *sch;
3641 
3642 	rcu_read_lock();
3643 
3644 	sch = rcu_dereference(scx_root);
3645 	if (unlikely(!sch)) {
3646 		rcu_read_unlock();
3647 		return false;
3648 	}
3649 
3650 	switch (scx_enable_state()) {
3651 	case SCX_ENABLING:
3652 	case SCX_ENABLED:
3653 		break;
3654 	default:
3655 		rcu_read_unlock();
3656 		return false;
3657 	}
3658 
3659 	scx_error(sch, "RCU CPU stall detected!");
3660 	rcu_read_unlock();
3661 
3662 	return true;
3663 }
3664 
3665 /**
3666  * scx_softlockup - sched_ext softlockup handler
3667  * @dur_s: number of seconds of CPU stuck due to soft lockup
3668  *
3669  * On some multi-socket setups (e.g. 2x Intel 8480c), the BPF scheduler can
3670  * live-lock the system by making many CPUs target the same DSQ to the point
3671  * where soft-lockup detection triggers. This function is called from
3672  * soft-lockup watchdog when the triggering point is close and tries to unjam
3673  * the system by enabling the breather and aborting the BPF scheduler.
3674  */
scx_softlockup(u32 dur_s)3675 void scx_softlockup(u32 dur_s)
3676 {
3677 	struct scx_sched *sch;
3678 
3679 	rcu_read_lock();
3680 
3681 	sch = rcu_dereference(scx_root);
3682 	if (unlikely(!sch))
3683 		goto out_unlock;
3684 
3685 	switch (scx_enable_state()) {
3686 	case SCX_ENABLING:
3687 	case SCX_ENABLED:
3688 		break;
3689 	default:
3690 		goto out_unlock;
3691 	}
3692 
3693 	/* allow only one instance, cleared at the end of scx_bypass() */
3694 	if (test_and_set_bit(0, &scx_in_softlockup))
3695 		goto out_unlock;
3696 
3697 	printk_deferred(KERN_ERR "sched_ext: Soft lockup - CPU%d stuck for %us, disabling \"%s\"\n",
3698 			smp_processor_id(), dur_s, scx_root->ops.name);
3699 
3700 	/*
3701 	 * Some CPUs may be trapped in the dispatch paths. Enable breather
3702 	 * immediately; otherwise, we might even be able to get to scx_bypass().
3703 	 */
3704 	atomic_inc(&scx_breather_depth);
3705 
3706 	scx_error(sch, "soft lockup - CPU#%d stuck for %us", smp_processor_id(), dur_s);
3707 out_unlock:
3708 	rcu_read_unlock();
3709 }
3710 
scx_clear_softlockup(void)3711 static void scx_clear_softlockup(void)
3712 {
3713 	if (test_and_clear_bit(0, &scx_in_softlockup))
3714 		atomic_dec(&scx_breather_depth);
3715 }
3716 
3717 /**
3718  * scx_bypass - [Un]bypass scx_ops and guarantee forward progress
3719  * @bypass: true for bypass, false for unbypass
3720  *
3721  * Bypassing guarantees that all runnable tasks make forward progress without
3722  * trusting the BPF scheduler. We can't grab any mutexes or rwsems as they might
3723  * be held by tasks that the BPF scheduler is forgetting to run, which
3724  * unfortunately also excludes toggling the static branches.
3725  *
3726  * Let's work around by overriding a couple ops and modifying behaviors based on
3727  * the DISABLING state and then cycling the queued tasks through dequeue/enqueue
3728  * to force global FIFO scheduling.
3729  *
3730  * - ops.select_cpu() is ignored and the default select_cpu() is used.
3731  *
3732  * - ops.enqueue() is ignored and tasks are queued in simple global FIFO order.
3733  *   %SCX_OPS_ENQ_LAST is also ignored.
3734  *
3735  * - ops.dispatch() is ignored.
3736  *
3737  * - balance_scx() does not set %SCX_RQ_BAL_KEEP on non-zero slice as slice
3738  *   can't be trusted. Whenever a tick triggers, the running task is rotated to
3739  *   the tail of the queue with core_sched_at touched.
3740  *
3741  * - pick_next_task() suppresses zero slice warning.
3742  *
3743  * - scx_kick_cpu() is disabled to avoid irq_work malfunction during PM
3744  *   operations.
3745  *
3746  * - scx_prio_less() reverts to the default core_sched_at order.
3747  */
scx_bypass(bool bypass)3748 static void scx_bypass(bool bypass)
3749 {
3750 	static DEFINE_RAW_SPINLOCK(bypass_lock);
3751 	static unsigned long bypass_timestamp;
3752 	struct scx_sched *sch;
3753 	unsigned long flags;
3754 	int cpu;
3755 
3756 	raw_spin_lock_irqsave(&bypass_lock, flags);
3757 	sch = rcu_dereference_bh(scx_root);
3758 
3759 	if (bypass) {
3760 		scx_bypass_depth++;
3761 		WARN_ON_ONCE(scx_bypass_depth <= 0);
3762 		if (scx_bypass_depth != 1)
3763 			goto unlock;
3764 		bypass_timestamp = ktime_get_ns();
3765 		if (sch)
3766 			scx_add_event(sch, SCX_EV_BYPASS_ACTIVATE, 1);
3767 	} else {
3768 		scx_bypass_depth--;
3769 		WARN_ON_ONCE(scx_bypass_depth < 0);
3770 		if (scx_bypass_depth != 0)
3771 			goto unlock;
3772 		if (sch)
3773 			scx_add_event(sch, SCX_EV_BYPASS_DURATION,
3774 				      ktime_get_ns() - bypass_timestamp);
3775 	}
3776 
3777 	atomic_inc(&scx_breather_depth);
3778 
3779 	/*
3780 	 * No task property is changing. We just need to make sure all currently
3781 	 * queued tasks are re-queued according to the new scx_rq_bypassing()
3782 	 * state. As an optimization, walk each rq's runnable_list instead of
3783 	 * the scx_tasks list.
3784 	 *
3785 	 * This function can't trust the scheduler and thus can't use
3786 	 * cpus_read_lock(). Walk all possible CPUs instead of online.
3787 	 */
3788 	for_each_possible_cpu(cpu) {
3789 		struct rq *rq = cpu_rq(cpu);
3790 		struct task_struct *p, *n;
3791 
3792 		raw_spin_rq_lock(rq);
3793 
3794 		if (bypass) {
3795 			WARN_ON_ONCE(rq->scx.flags & SCX_RQ_BYPASSING);
3796 			rq->scx.flags |= SCX_RQ_BYPASSING;
3797 		} else {
3798 			WARN_ON_ONCE(!(rq->scx.flags & SCX_RQ_BYPASSING));
3799 			rq->scx.flags &= ~SCX_RQ_BYPASSING;
3800 		}
3801 
3802 		/*
3803 		 * We need to guarantee that no tasks are on the BPF scheduler
3804 		 * while bypassing. Either we see enabled or the enable path
3805 		 * sees scx_rq_bypassing() before moving tasks to SCX.
3806 		 */
3807 		if (!scx_enabled()) {
3808 			raw_spin_rq_unlock(rq);
3809 			continue;
3810 		}
3811 
3812 		/*
3813 		 * The use of list_for_each_entry_safe_reverse() is required
3814 		 * because each task is going to be removed from and added back
3815 		 * to the runnable_list during iteration. Because they're added
3816 		 * to the tail of the list, safe reverse iteration can still
3817 		 * visit all nodes.
3818 		 */
3819 		list_for_each_entry_safe_reverse(p, n, &rq->scx.runnable_list,
3820 						 scx.runnable_node) {
3821 			struct sched_enq_and_set_ctx ctx;
3822 
3823 			/* cycling deq/enq is enough, see the function comment */
3824 			sched_deq_and_put_task(p, DEQUEUE_SAVE | DEQUEUE_MOVE, &ctx);
3825 			sched_enq_and_set_task(&ctx);
3826 		}
3827 
3828 		/* resched to restore ticks and idle state */
3829 		if (cpu_online(cpu) || cpu == smp_processor_id())
3830 			resched_curr(rq);
3831 
3832 		raw_spin_rq_unlock(rq);
3833 	}
3834 
3835 	atomic_dec(&scx_breather_depth);
3836 unlock:
3837 	raw_spin_unlock_irqrestore(&bypass_lock, flags);
3838 	scx_clear_softlockup();
3839 }
3840 
free_exit_info(struct scx_exit_info * ei)3841 static void free_exit_info(struct scx_exit_info *ei)
3842 {
3843 	kvfree(ei->dump);
3844 	kfree(ei->msg);
3845 	kfree(ei->bt);
3846 	kfree(ei);
3847 }
3848 
alloc_exit_info(size_t exit_dump_len)3849 static struct scx_exit_info *alloc_exit_info(size_t exit_dump_len)
3850 {
3851 	struct scx_exit_info *ei;
3852 
3853 	ei = kzalloc(sizeof(*ei), GFP_KERNEL);
3854 	if (!ei)
3855 		return NULL;
3856 
3857 	ei->bt = kcalloc(SCX_EXIT_BT_LEN, sizeof(ei->bt[0]), GFP_KERNEL);
3858 	ei->msg = kzalloc(SCX_EXIT_MSG_LEN, GFP_KERNEL);
3859 	ei->dump = kvzalloc(exit_dump_len, GFP_KERNEL);
3860 
3861 	if (!ei->bt || !ei->msg || !ei->dump) {
3862 		free_exit_info(ei);
3863 		return NULL;
3864 	}
3865 
3866 	return ei;
3867 }
3868 
scx_exit_reason(enum scx_exit_kind kind)3869 static const char *scx_exit_reason(enum scx_exit_kind kind)
3870 {
3871 	switch (kind) {
3872 	case SCX_EXIT_UNREG:
3873 		return "unregistered from user space";
3874 	case SCX_EXIT_UNREG_BPF:
3875 		return "unregistered from BPF";
3876 	case SCX_EXIT_UNREG_KERN:
3877 		return "unregistered from the main kernel";
3878 	case SCX_EXIT_SYSRQ:
3879 		return "disabled by sysrq-S";
3880 	case SCX_EXIT_ERROR:
3881 		return "runtime error";
3882 	case SCX_EXIT_ERROR_BPF:
3883 		return "scx_bpf_error";
3884 	case SCX_EXIT_ERROR_STALL:
3885 		return "runnable task stall";
3886 	default:
3887 		return "<UNKNOWN>";
3888 	}
3889 }
3890 
free_kick_pseqs_rcu(struct rcu_head * rcu)3891 static void free_kick_pseqs_rcu(struct rcu_head *rcu)
3892 {
3893 	struct scx_kick_pseqs *pseqs = container_of(rcu, struct scx_kick_pseqs, rcu);
3894 
3895 	kvfree(pseqs);
3896 }
3897 
free_kick_pseqs(void)3898 static void free_kick_pseqs(void)
3899 {
3900 	int cpu;
3901 
3902 	for_each_possible_cpu(cpu) {
3903 		struct scx_kick_pseqs **pseqs = per_cpu_ptr(&scx_kick_pseqs, cpu);
3904 		struct scx_kick_pseqs *to_free;
3905 
3906 		to_free = rcu_replace_pointer(*pseqs, NULL, true);
3907 		if (to_free)
3908 			call_rcu(&to_free->rcu, free_kick_pseqs_rcu);
3909 	}
3910 }
3911 
scx_disable_workfn(struct kthread_work * work)3912 static void scx_disable_workfn(struct kthread_work *work)
3913 {
3914 	struct scx_sched *sch = container_of(work, struct scx_sched, disable_work);
3915 	struct scx_exit_info *ei = sch->exit_info;
3916 	struct scx_task_iter sti;
3917 	struct task_struct *p;
3918 	int kind, cpu;
3919 
3920 	kind = atomic_read(&sch->exit_kind);
3921 	while (true) {
3922 		if (kind == SCX_EXIT_DONE)	/* already disabled? */
3923 			return;
3924 		WARN_ON_ONCE(kind == SCX_EXIT_NONE);
3925 		if (atomic_try_cmpxchg(&sch->exit_kind, &kind, SCX_EXIT_DONE))
3926 			break;
3927 	}
3928 	ei->kind = kind;
3929 	ei->reason = scx_exit_reason(ei->kind);
3930 
3931 	/* guarantee forward progress by bypassing scx_ops */
3932 	scx_bypass(true);
3933 
3934 	switch (scx_set_enable_state(SCX_DISABLING)) {
3935 	case SCX_DISABLING:
3936 		WARN_ONCE(true, "sched_ext: duplicate disabling instance?");
3937 		break;
3938 	case SCX_DISABLED:
3939 		pr_warn("sched_ext: ops error detected without ops (%s)\n",
3940 			sch->exit_info->msg);
3941 		WARN_ON_ONCE(scx_set_enable_state(SCX_DISABLED) != SCX_DISABLING);
3942 		goto done;
3943 	default:
3944 		break;
3945 	}
3946 
3947 	/*
3948 	 * Here, every runnable task is guaranteed to make forward progress and
3949 	 * we can safely use blocking synchronization constructs. Actually
3950 	 * disable ops.
3951 	 */
3952 	mutex_lock(&scx_enable_mutex);
3953 
3954 	static_branch_disable(&__scx_switched_all);
3955 	WRITE_ONCE(scx_switching_all, false);
3956 
3957 	/*
3958 	 * Shut down cgroup support before tasks so that the cgroup attach path
3959 	 * doesn't race against scx_exit_task().
3960 	 */
3961 	scx_cgroup_lock();
3962 	scx_cgroup_exit(sch);
3963 	scx_cgroup_unlock();
3964 
3965 	/*
3966 	 * The BPF scheduler is going away. All tasks including %TASK_DEAD ones
3967 	 * must be switched out and exited synchronously.
3968 	 */
3969 	percpu_down_write(&scx_fork_rwsem);
3970 
3971 	scx_init_task_enabled = false;
3972 
3973 	scx_task_iter_start(&sti);
3974 	while ((p = scx_task_iter_next_locked(&sti))) {
3975 		const struct sched_class *old_class = p->sched_class;
3976 		const struct sched_class *new_class =
3977 			__setscheduler_class(p->policy, p->prio);
3978 		struct sched_enq_and_set_ctx ctx;
3979 
3980 		if (old_class != new_class && p->se.sched_delayed)
3981 			dequeue_task(task_rq(p), p, DEQUEUE_SLEEP | DEQUEUE_DELAYED);
3982 
3983 		sched_deq_and_put_task(p, DEQUEUE_SAVE | DEQUEUE_MOVE, &ctx);
3984 
3985 		p->sched_class = new_class;
3986 		check_class_changing(task_rq(p), p, old_class);
3987 
3988 		sched_enq_and_set_task(&ctx);
3989 
3990 		check_class_changed(task_rq(p), p, old_class, p->prio);
3991 		scx_exit_task(p);
3992 	}
3993 	scx_task_iter_stop(&sti);
3994 	percpu_up_write(&scx_fork_rwsem);
3995 
3996 	/*
3997 	 * Invalidate all the rq clocks to prevent getting outdated
3998 	 * rq clocks from a previous scx scheduler.
3999 	 */
4000 	for_each_possible_cpu(cpu) {
4001 		struct rq *rq = cpu_rq(cpu);
4002 		scx_rq_clock_invalidate(rq);
4003 	}
4004 
4005 	/* no task is on scx, turn off all the switches and flush in-progress calls */
4006 	static_branch_disable(&__scx_enabled);
4007 	bitmap_zero(sch->has_op, SCX_OPI_END);
4008 	scx_idle_disable();
4009 	synchronize_rcu();
4010 
4011 	if (ei->kind >= SCX_EXIT_ERROR) {
4012 		pr_err("sched_ext: BPF scheduler \"%s\" disabled (%s)\n",
4013 		       sch->ops.name, ei->reason);
4014 
4015 		if (ei->msg[0] != '\0')
4016 			pr_err("sched_ext: %s: %s\n", sch->ops.name, ei->msg);
4017 #ifdef CONFIG_STACKTRACE
4018 		stack_trace_print(ei->bt, ei->bt_len, 2);
4019 #endif
4020 	} else {
4021 		pr_info("sched_ext: BPF scheduler \"%s\" disabled (%s)\n",
4022 			sch->ops.name, ei->reason);
4023 	}
4024 
4025 	if (sch->ops.exit)
4026 		SCX_CALL_OP(sch, SCX_KF_UNLOCKED, exit, NULL, ei);
4027 
4028 	cancel_delayed_work_sync(&scx_watchdog_work);
4029 
4030 	/*
4031 	 * scx_root clearing must be inside cpus_read_lock(). See
4032 	 * handle_hotplug().
4033 	 */
4034 	cpus_read_lock();
4035 	RCU_INIT_POINTER(scx_root, NULL);
4036 	cpus_read_unlock();
4037 
4038 	/*
4039 	 * Delete the kobject from the hierarchy synchronously. Otherwise, sysfs
4040 	 * could observe an object of the same name still in the hierarchy when
4041 	 * the next scheduler is loaded.
4042 	 */
4043 	kobject_del(&sch->kobj);
4044 
4045 	free_percpu(scx_dsp_ctx);
4046 	scx_dsp_ctx = NULL;
4047 	scx_dsp_max_batch = 0;
4048 	free_kick_pseqs();
4049 
4050 	mutex_unlock(&scx_enable_mutex);
4051 
4052 	WARN_ON_ONCE(scx_set_enable_state(SCX_DISABLED) != SCX_DISABLING);
4053 done:
4054 	scx_bypass(false);
4055 }
4056 
scx_disable(enum scx_exit_kind kind)4057 static void scx_disable(enum scx_exit_kind kind)
4058 {
4059 	int none = SCX_EXIT_NONE;
4060 	struct scx_sched *sch;
4061 
4062 	if (WARN_ON_ONCE(kind == SCX_EXIT_NONE || kind == SCX_EXIT_DONE))
4063 		kind = SCX_EXIT_ERROR;
4064 
4065 	rcu_read_lock();
4066 	sch = rcu_dereference(scx_root);
4067 	if (sch) {
4068 		atomic_try_cmpxchg(&sch->exit_kind, &none, kind);
4069 		kthread_queue_work(sch->helper, &sch->disable_work);
4070 	}
4071 	rcu_read_unlock();
4072 }
4073 
dump_newline(struct seq_buf * s)4074 static void dump_newline(struct seq_buf *s)
4075 {
4076 	trace_sched_ext_dump("");
4077 
4078 	/* @s may be zero sized and seq_buf triggers WARN if so */
4079 	if (s->size)
4080 		seq_buf_putc(s, '\n');
4081 }
4082 
dump_line(struct seq_buf * s,const char * fmt,...)4083 static __printf(2, 3) void dump_line(struct seq_buf *s, const char *fmt, ...)
4084 {
4085 	va_list args;
4086 
4087 #ifdef CONFIG_TRACEPOINTS
4088 	if (trace_sched_ext_dump_enabled()) {
4089 		/* protected by scx_dump_state()::dump_lock */
4090 		static char line_buf[SCX_EXIT_MSG_LEN];
4091 
4092 		va_start(args, fmt);
4093 		vscnprintf(line_buf, sizeof(line_buf), fmt, args);
4094 		va_end(args);
4095 
4096 		trace_sched_ext_dump(line_buf);
4097 	}
4098 #endif
4099 	/* @s may be zero sized and seq_buf triggers WARN if so */
4100 	if (s->size) {
4101 		va_start(args, fmt);
4102 		seq_buf_vprintf(s, fmt, args);
4103 		va_end(args);
4104 
4105 		seq_buf_putc(s, '\n');
4106 	}
4107 }
4108 
dump_stack_trace(struct seq_buf * s,const char * prefix,const unsigned long * bt,unsigned int len)4109 static void dump_stack_trace(struct seq_buf *s, const char *prefix,
4110 			     const unsigned long *bt, unsigned int len)
4111 {
4112 	unsigned int i;
4113 
4114 	for (i = 0; i < len; i++)
4115 		dump_line(s, "%s%pS", prefix, (void *)bt[i]);
4116 }
4117 
ops_dump_init(struct seq_buf * s,const char * prefix)4118 static void ops_dump_init(struct seq_buf *s, const char *prefix)
4119 {
4120 	struct scx_dump_data *dd = &scx_dump_data;
4121 
4122 	lockdep_assert_irqs_disabled();
4123 
4124 	dd->cpu = smp_processor_id();		/* allow scx_bpf_dump() */
4125 	dd->first = true;
4126 	dd->cursor = 0;
4127 	dd->s = s;
4128 	dd->prefix = prefix;
4129 }
4130 
ops_dump_flush(void)4131 static void ops_dump_flush(void)
4132 {
4133 	struct scx_dump_data *dd = &scx_dump_data;
4134 	char *line = dd->buf.line;
4135 
4136 	if (!dd->cursor)
4137 		return;
4138 
4139 	/*
4140 	 * There's something to flush and this is the first line. Insert a blank
4141 	 * line to distinguish ops dump.
4142 	 */
4143 	if (dd->first) {
4144 		dump_newline(dd->s);
4145 		dd->first = false;
4146 	}
4147 
4148 	/*
4149 	 * There may be multiple lines in $line. Scan and emit each line
4150 	 * separately.
4151 	 */
4152 	while (true) {
4153 		char *end = line;
4154 		char c;
4155 
4156 		while (*end != '\n' && *end != '\0')
4157 			end++;
4158 
4159 		/*
4160 		 * If $line overflowed, it may not have newline at the end.
4161 		 * Always emit with a newline.
4162 		 */
4163 		c = *end;
4164 		*end = '\0';
4165 		dump_line(dd->s, "%s%s", dd->prefix, line);
4166 		if (c == '\0')
4167 			break;
4168 
4169 		/* move to the next line */
4170 		end++;
4171 		if (*end == '\0')
4172 			break;
4173 		line = end;
4174 	}
4175 
4176 	dd->cursor = 0;
4177 }
4178 
ops_dump_exit(void)4179 static void ops_dump_exit(void)
4180 {
4181 	ops_dump_flush();
4182 	scx_dump_data.cpu = -1;
4183 }
4184 
scx_dump_task(struct seq_buf * s,struct scx_dump_ctx * dctx,struct task_struct * p,char marker)4185 static void scx_dump_task(struct seq_buf *s, struct scx_dump_ctx *dctx,
4186 			  struct task_struct *p, char marker)
4187 {
4188 	static unsigned long bt[SCX_EXIT_BT_LEN];
4189 	struct scx_sched *sch = scx_root;
4190 	char dsq_id_buf[19] = "(n/a)";
4191 	unsigned long ops_state = atomic_long_read(&p->scx.ops_state);
4192 	unsigned int bt_len = 0;
4193 
4194 	if (p->scx.dsq)
4195 		scnprintf(dsq_id_buf, sizeof(dsq_id_buf), "0x%llx",
4196 			  (unsigned long long)p->scx.dsq->id);
4197 
4198 	dump_newline(s);
4199 	dump_line(s, " %c%c %s[%d] %+ldms",
4200 		  marker, task_state_to_char(p), p->comm, p->pid,
4201 		  jiffies_delta_msecs(p->scx.runnable_at, dctx->at_jiffies));
4202 	dump_line(s, "      scx_state/flags=%u/0x%x dsq_flags=0x%x ops_state/qseq=%lu/%lu",
4203 		  scx_get_task_state(p), p->scx.flags & ~SCX_TASK_STATE_MASK,
4204 		  p->scx.dsq_flags, ops_state & SCX_OPSS_STATE_MASK,
4205 		  ops_state >> SCX_OPSS_QSEQ_SHIFT);
4206 	dump_line(s, "      sticky/holding_cpu=%d/%d dsq_id=%s",
4207 		  p->scx.sticky_cpu, p->scx.holding_cpu, dsq_id_buf);
4208 	dump_line(s, "      dsq_vtime=%llu slice=%llu weight=%u",
4209 		  p->scx.dsq_vtime, p->scx.slice, p->scx.weight);
4210 	dump_line(s, "      cpus=%*pb no_mig=%u", cpumask_pr_args(p->cpus_ptr),
4211 		  p->migration_disabled);
4212 
4213 	if (SCX_HAS_OP(sch, dump_task)) {
4214 		ops_dump_init(s, "    ");
4215 		SCX_CALL_OP(sch, SCX_KF_REST, dump_task, NULL, dctx, p);
4216 		ops_dump_exit();
4217 	}
4218 
4219 #ifdef CONFIG_STACKTRACE
4220 	bt_len = stack_trace_save_tsk(p, bt, SCX_EXIT_BT_LEN, 1);
4221 #endif
4222 	if (bt_len) {
4223 		dump_newline(s);
4224 		dump_stack_trace(s, "    ", bt, bt_len);
4225 	}
4226 }
4227 
scx_dump_state(struct scx_exit_info * ei,size_t dump_len)4228 static void scx_dump_state(struct scx_exit_info *ei, size_t dump_len)
4229 {
4230 	static DEFINE_SPINLOCK(dump_lock);
4231 	static const char trunc_marker[] = "\n\n~~~~ TRUNCATED ~~~~\n";
4232 	struct scx_sched *sch = scx_root;
4233 	struct scx_dump_ctx dctx = {
4234 		.kind = ei->kind,
4235 		.exit_code = ei->exit_code,
4236 		.reason = ei->reason,
4237 		.at_ns = ktime_get_ns(),
4238 		.at_jiffies = jiffies,
4239 	};
4240 	struct seq_buf s;
4241 	struct scx_event_stats events;
4242 	unsigned long flags;
4243 	char *buf;
4244 	int cpu;
4245 
4246 	spin_lock_irqsave(&dump_lock, flags);
4247 
4248 	seq_buf_init(&s, ei->dump, dump_len);
4249 
4250 	if (ei->kind == SCX_EXIT_NONE) {
4251 		dump_line(&s, "Debug dump triggered by %s", ei->reason);
4252 	} else {
4253 		dump_line(&s, "%s[%d] triggered exit kind %d:",
4254 			  current->comm, current->pid, ei->kind);
4255 		dump_line(&s, "  %s (%s)", ei->reason, ei->msg);
4256 		dump_newline(&s);
4257 		dump_line(&s, "Backtrace:");
4258 		dump_stack_trace(&s, "  ", ei->bt, ei->bt_len);
4259 	}
4260 
4261 	if (SCX_HAS_OP(sch, dump)) {
4262 		ops_dump_init(&s, "");
4263 		SCX_CALL_OP(sch, SCX_KF_UNLOCKED, dump, NULL, &dctx);
4264 		ops_dump_exit();
4265 	}
4266 
4267 	dump_newline(&s);
4268 	dump_line(&s, "CPU states");
4269 	dump_line(&s, "----------");
4270 
4271 	for_each_possible_cpu(cpu) {
4272 		struct rq *rq = cpu_rq(cpu);
4273 		struct rq_flags rf;
4274 		struct task_struct *p;
4275 		struct seq_buf ns;
4276 		size_t avail, used;
4277 		bool idle;
4278 
4279 		rq_lock(rq, &rf);
4280 
4281 		idle = list_empty(&rq->scx.runnable_list) &&
4282 			rq->curr->sched_class == &idle_sched_class;
4283 
4284 		if (idle && !SCX_HAS_OP(sch, dump_cpu))
4285 			goto next;
4286 
4287 		/*
4288 		 * We don't yet know whether ops.dump_cpu() will produce output
4289 		 * and we may want to skip the default CPU dump if it doesn't.
4290 		 * Use a nested seq_buf to generate the standard dump so that we
4291 		 * can decide whether to commit later.
4292 		 */
4293 		avail = seq_buf_get_buf(&s, &buf);
4294 		seq_buf_init(&ns, buf, avail);
4295 
4296 		dump_newline(&ns);
4297 		dump_line(&ns, "CPU %-4d: nr_run=%u flags=0x%x cpu_rel=%d ops_qseq=%lu pnt_seq=%lu",
4298 			  cpu, rq->scx.nr_running, rq->scx.flags,
4299 			  rq->scx.cpu_released, rq->scx.ops_qseq,
4300 			  rq->scx.pnt_seq);
4301 		dump_line(&ns, "          curr=%s[%d] class=%ps",
4302 			  rq->curr->comm, rq->curr->pid,
4303 			  rq->curr->sched_class);
4304 		if (!cpumask_empty(rq->scx.cpus_to_kick))
4305 			dump_line(&ns, "  cpus_to_kick   : %*pb",
4306 				  cpumask_pr_args(rq->scx.cpus_to_kick));
4307 		if (!cpumask_empty(rq->scx.cpus_to_kick_if_idle))
4308 			dump_line(&ns, "  idle_to_kick   : %*pb",
4309 				  cpumask_pr_args(rq->scx.cpus_to_kick_if_idle));
4310 		if (!cpumask_empty(rq->scx.cpus_to_preempt))
4311 			dump_line(&ns, "  cpus_to_preempt: %*pb",
4312 				  cpumask_pr_args(rq->scx.cpus_to_preempt));
4313 		if (!cpumask_empty(rq->scx.cpus_to_wait))
4314 			dump_line(&ns, "  cpus_to_wait   : %*pb",
4315 				  cpumask_pr_args(rq->scx.cpus_to_wait));
4316 
4317 		used = seq_buf_used(&ns);
4318 		if (SCX_HAS_OP(sch, dump_cpu)) {
4319 			ops_dump_init(&ns, "  ");
4320 			SCX_CALL_OP(sch, SCX_KF_REST, dump_cpu, NULL,
4321 				    &dctx, cpu, idle);
4322 			ops_dump_exit();
4323 		}
4324 
4325 		/*
4326 		 * If idle && nothing generated by ops.dump_cpu(), there's
4327 		 * nothing interesting. Skip.
4328 		 */
4329 		if (idle && used == seq_buf_used(&ns))
4330 			goto next;
4331 
4332 		/*
4333 		 * $s may already have overflowed when $ns was created. If so,
4334 		 * calling commit on it will trigger BUG.
4335 		 */
4336 		if (avail) {
4337 			seq_buf_commit(&s, seq_buf_used(&ns));
4338 			if (seq_buf_has_overflowed(&ns))
4339 				seq_buf_set_overflow(&s);
4340 		}
4341 
4342 		if (rq->curr->sched_class == &ext_sched_class)
4343 			scx_dump_task(&s, &dctx, rq->curr, '*');
4344 
4345 		list_for_each_entry(p, &rq->scx.runnable_list, scx.runnable_node)
4346 			scx_dump_task(&s, &dctx, p, ' ');
4347 	next:
4348 		rq_unlock(rq, &rf);
4349 	}
4350 
4351 	dump_newline(&s);
4352 	dump_line(&s, "Event counters");
4353 	dump_line(&s, "--------------");
4354 
4355 	scx_read_events(sch, &events);
4356 	scx_dump_event(s, &events, SCX_EV_SELECT_CPU_FALLBACK);
4357 	scx_dump_event(s, &events, SCX_EV_DISPATCH_LOCAL_DSQ_OFFLINE);
4358 	scx_dump_event(s, &events, SCX_EV_DISPATCH_KEEP_LAST);
4359 	scx_dump_event(s, &events, SCX_EV_ENQ_SKIP_EXITING);
4360 	scx_dump_event(s, &events, SCX_EV_ENQ_SKIP_MIGRATION_DISABLED);
4361 	scx_dump_event(s, &events, SCX_EV_REFILL_SLICE_DFL);
4362 	scx_dump_event(s, &events, SCX_EV_BYPASS_DURATION);
4363 	scx_dump_event(s, &events, SCX_EV_BYPASS_DISPATCH);
4364 	scx_dump_event(s, &events, SCX_EV_BYPASS_ACTIVATE);
4365 
4366 	if (seq_buf_has_overflowed(&s) && dump_len >= sizeof(trunc_marker))
4367 		memcpy(ei->dump + dump_len - sizeof(trunc_marker),
4368 		       trunc_marker, sizeof(trunc_marker));
4369 
4370 	spin_unlock_irqrestore(&dump_lock, flags);
4371 }
4372 
scx_error_irq_workfn(struct irq_work * irq_work)4373 static void scx_error_irq_workfn(struct irq_work *irq_work)
4374 {
4375 	struct scx_sched *sch = container_of(irq_work, struct scx_sched, error_irq_work);
4376 	struct scx_exit_info *ei = sch->exit_info;
4377 
4378 	if (ei->kind >= SCX_EXIT_ERROR)
4379 		scx_dump_state(ei, sch->ops.exit_dump_len);
4380 
4381 	kthread_queue_work(sch->helper, &sch->disable_work);
4382 }
4383 
scx_vexit(struct scx_sched * sch,enum scx_exit_kind kind,s64 exit_code,const char * fmt,va_list args)4384 static void scx_vexit(struct scx_sched *sch,
4385 		      enum scx_exit_kind kind, s64 exit_code,
4386 		      const char *fmt, va_list args)
4387 {
4388 	struct scx_exit_info *ei = sch->exit_info;
4389 	int none = SCX_EXIT_NONE;
4390 
4391 	if (!atomic_try_cmpxchg(&sch->exit_kind, &none, kind))
4392 		return;
4393 
4394 	ei->exit_code = exit_code;
4395 #ifdef CONFIG_STACKTRACE
4396 	if (kind >= SCX_EXIT_ERROR)
4397 		ei->bt_len = stack_trace_save(ei->bt, SCX_EXIT_BT_LEN, 1);
4398 #endif
4399 	vscnprintf(ei->msg, SCX_EXIT_MSG_LEN, fmt, args);
4400 
4401 	/*
4402 	 * Set ei->kind and ->reason for scx_dump_state(). They'll be set again
4403 	 * in scx_disable_workfn().
4404 	 */
4405 	ei->kind = kind;
4406 	ei->reason = scx_exit_reason(ei->kind);
4407 
4408 	irq_work_queue(&sch->error_irq_work);
4409 }
4410 
alloc_kick_pseqs(void)4411 static int alloc_kick_pseqs(void)
4412 {
4413 	int cpu;
4414 
4415 	/*
4416 	 * Allocate per-CPU arrays sized by nr_cpu_ids. Use kvzalloc as size
4417 	 * can exceed percpu allocator limits on large machines.
4418 	 */
4419 	for_each_possible_cpu(cpu) {
4420 		struct scx_kick_pseqs **pseqs = per_cpu_ptr(&scx_kick_pseqs, cpu);
4421 		struct scx_kick_pseqs *new_pseqs;
4422 
4423 		WARN_ON_ONCE(rcu_access_pointer(*pseqs));
4424 
4425 		new_pseqs = kvzalloc_node(struct_size(new_pseqs, seqs, nr_cpu_ids),
4426 					  GFP_KERNEL, cpu_to_node(cpu));
4427 		if (!new_pseqs) {
4428 			free_kick_pseqs();
4429 			return -ENOMEM;
4430 		}
4431 
4432 		rcu_assign_pointer(*pseqs, new_pseqs);
4433 	}
4434 
4435 	return 0;
4436 }
4437 
scx_alloc_and_add_sched(struct sched_ext_ops * ops)4438 static struct scx_sched *scx_alloc_and_add_sched(struct sched_ext_ops *ops)
4439 {
4440 	struct scx_sched *sch;
4441 	int node, ret;
4442 
4443 	sch = kzalloc(sizeof(*sch), GFP_KERNEL);
4444 	if (!sch)
4445 		return ERR_PTR(-ENOMEM);
4446 
4447 	sch->exit_info = alloc_exit_info(ops->exit_dump_len);
4448 	if (!sch->exit_info) {
4449 		ret = -ENOMEM;
4450 		goto err_free_sch;
4451 	}
4452 
4453 	ret = rhashtable_init(&sch->dsq_hash, &dsq_hash_params);
4454 	if (ret < 0)
4455 		goto err_free_ei;
4456 
4457 	sch->global_dsqs = kcalloc(nr_node_ids, sizeof(sch->global_dsqs[0]),
4458 				   GFP_KERNEL);
4459 	if (!sch->global_dsqs) {
4460 		ret = -ENOMEM;
4461 		goto err_free_hash;
4462 	}
4463 
4464 	for_each_node_state(node, N_POSSIBLE) {
4465 		struct scx_dispatch_q *dsq;
4466 
4467 		dsq = kzalloc_node(sizeof(*dsq), GFP_KERNEL, node);
4468 		if (!dsq) {
4469 			ret = -ENOMEM;
4470 			goto err_free_gdsqs;
4471 		}
4472 
4473 		init_dsq(dsq, SCX_DSQ_GLOBAL);
4474 		sch->global_dsqs[node] = dsq;
4475 	}
4476 
4477 	sch->pcpu = alloc_percpu(struct scx_sched_pcpu);
4478 	if (!sch->pcpu)
4479 		goto err_free_gdsqs;
4480 
4481 	sch->helper = kthread_run_worker(0, "sched_ext_helper");
4482 	if (!sch->helper)
4483 		goto err_free_pcpu;
4484 	sched_set_fifo(sch->helper->task);
4485 
4486 	atomic_set(&sch->exit_kind, SCX_EXIT_NONE);
4487 	init_irq_work(&sch->error_irq_work, scx_error_irq_workfn);
4488 	kthread_init_work(&sch->disable_work, scx_disable_workfn);
4489 	sch->ops = *ops;
4490 	ops->priv = sch;
4491 
4492 	sch->kobj.kset = scx_kset;
4493 	ret = kobject_init_and_add(&sch->kobj, &scx_ktype, NULL, "root");
4494 	if (ret < 0)
4495 		goto err_stop_helper;
4496 
4497 	return sch;
4498 
4499 err_stop_helper:
4500 	kthread_stop(sch->helper->task);
4501 err_free_pcpu:
4502 	free_percpu(sch->pcpu);
4503 err_free_gdsqs:
4504 	for_each_node_state(node, N_POSSIBLE)
4505 		kfree(sch->global_dsqs[node]);
4506 	kfree(sch->global_dsqs);
4507 err_free_hash:
4508 	rhashtable_free_and_destroy(&sch->dsq_hash, NULL, NULL);
4509 err_free_ei:
4510 	free_exit_info(sch->exit_info);
4511 err_free_sch:
4512 	kfree(sch);
4513 	return ERR_PTR(ret);
4514 }
4515 
check_hotplug_seq(struct scx_sched * sch,const struct sched_ext_ops * ops)4516 static void check_hotplug_seq(struct scx_sched *sch,
4517 			      const struct sched_ext_ops *ops)
4518 {
4519 	unsigned long long global_hotplug_seq;
4520 
4521 	/*
4522 	 * If a hotplug event has occurred between when a scheduler was
4523 	 * initialized, and when we were able to attach, exit and notify user
4524 	 * space about it.
4525 	 */
4526 	if (ops->hotplug_seq) {
4527 		global_hotplug_seq = atomic_long_read(&scx_hotplug_seq);
4528 		if (ops->hotplug_seq != global_hotplug_seq) {
4529 			scx_exit(sch, SCX_EXIT_UNREG_KERN,
4530 				 SCX_ECODE_ACT_RESTART | SCX_ECODE_RSN_HOTPLUG,
4531 				 "expected hotplug seq %llu did not match actual %llu",
4532 				 ops->hotplug_seq, global_hotplug_seq);
4533 		}
4534 	}
4535 }
4536 
validate_ops(struct scx_sched * sch,const struct sched_ext_ops * ops)4537 static int validate_ops(struct scx_sched *sch, const struct sched_ext_ops *ops)
4538 {
4539 	/*
4540 	 * It doesn't make sense to specify the SCX_OPS_ENQ_LAST flag if the
4541 	 * ops.enqueue() callback isn't implemented.
4542 	 */
4543 	if ((ops->flags & SCX_OPS_ENQ_LAST) && !ops->enqueue) {
4544 		scx_error(sch, "SCX_OPS_ENQ_LAST requires ops.enqueue() to be implemented");
4545 		return -EINVAL;
4546 	}
4547 
4548 	/*
4549 	 * SCX_OPS_BUILTIN_IDLE_PER_NODE requires built-in CPU idle
4550 	 * selection policy to be enabled.
4551 	 */
4552 	if ((ops->flags & SCX_OPS_BUILTIN_IDLE_PER_NODE) &&
4553 	    (ops->update_idle && !(ops->flags & SCX_OPS_KEEP_BUILTIN_IDLE))) {
4554 		scx_error(sch, "SCX_OPS_BUILTIN_IDLE_PER_NODE requires CPU idle selection enabled");
4555 		return -EINVAL;
4556 	}
4557 
4558 	if (ops->flags & SCX_OPS_HAS_CGROUP_WEIGHT)
4559 		pr_warn("SCX_OPS_HAS_CGROUP_WEIGHT is deprecated and a noop\n");
4560 
4561 	return 0;
4562 }
4563 
scx_enable(struct sched_ext_ops * ops,struct bpf_link * link)4564 static int scx_enable(struct sched_ext_ops *ops, struct bpf_link *link)
4565 {
4566 	struct scx_sched *sch;
4567 	struct scx_task_iter sti;
4568 	struct task_struct *p;
4569 	unsigned long timeout;
4570 	int i, cpu, ret;
4571 
4572 	if (!cpumask_equal(housekeeping_cpumask(HK_TYPE_DOMAIN),
4573 			   cpu_possible_mask)) {
4574 		pr_err("sched_ext: Not compatible with \"isolcpus=\" domain isolation\n");
4575 		return -EINVAL;
4576 	}
4577 
4578 	mutex_lock(&scx_enable_mutex);
4579 
4580 	if (scx_enable_state() != SCX_DISABLED) {
4581 		ret = -EBUSY;
4582 		goto err_unlock;
4583 	}
4584 
4585 	ret = alloc_kick_pseqs();
4586 	if (ret)
4587 		goto err_unlock;
4588 
4589 	sch = scx_alloc_and_add_sched(ops);
4590 	if (IS_ERR(sch)) {
4591 		ret = PTR_ERR(sch);
4592 		goto err_free_pseqs;
4593 	}
4594 
4595 	/*
4596 	 * Transition to ENABLING and clear exit info to arm the disable path.
4597 	 * Failure triggers full disabling from here on.
4598 	 */
4599 	WARN_ON_ONCE(scx_set_enable_state(SCX_ENABLING) != SCX_DISABLED);
4600 	WARN_ON_ONCE(scx_root);
4601 
4602 	atomic_long_set(&scx_nr_rejected, 0);
4603 
4604 	for_each_possible_cpu(cpu)
4605 		cpu_rq(cpu)->scx.cpuperf_target = SCX_CPUPERF_ONE;
4606 
4607 	/*
4608 	 * Keep CPUs stable during enable so that the BPF scheduler can track
4609 	 * online CPUs by watching ->on/offline_cpu() after ->init().
4610 	 */
4611 	cpus_read_lock();
4612 
4613 	/*
4614 	 * Make the scheduler instance visible. Must be inside cpus_read_lock().
4615 	 * See handle_hotplug().
4616 	 */
4617 	rcu_assign_pointer(scx_root, sch);
4618 
4619 	scx_idle_enable(ops);
4620 
4621 	if (sch->ops.init) {
4622 		ret = SCX_CALL_OP_RET(sch, SCX_KF_UNLOCKED, init, NULL);
4623 		if (ret) {
4624 			ret = ops_sanitize_err(sch, "init", ret);
4625 			cpus_read_unlock();
4626 			scx_error(sch, "ops.init() failed (%d)", ret);
4627 			goto err_disable;
4628 		}
4629 		sch->exit_info->flags |= SCX_EFLAG_INITIALIZED;
4630 	}
4631 
4632 	for (i = SCX_OPI_CPU_HOTPLUG_BEGIN; i < SCX_OPI_CPU_HOTPLUG_END; i++)
4633 		if (((void (**)(void))ops)[i])
4634 			set_bit(i, sch->has_op);
4635 
4636 	check_hotplug_seq(sch, ops);
4637 	scx_idle_update_selcpu_topology(ops);
4638 
4639 	cpus_read_unlock();
4640 
4641 	ret = validate_ops(sch, ops);
4642 	if (ret)
4643 		goto err_disable;
4644 
4645 	WARN_ON_ONCE(scx_dsp_ctx);
4646 	scx_dsp_max_batch = ops->dispatch_max_batch ?: SCX_DSP_DFL_MAX_BATCH;
4647 	scx_dsp_ctx = __alloc_percpu(struct_size_t(struct scx_dsp_ctx, buf,
4648 						   scx_dsp_max_batch),
4649 				     __alignof__(struct scx_dsp_ctx));
4650 	if (!scx_dsp_ctx) {
4651 		ret = -ENOMEM;
4652 		goto err_disable;
4653 	}
4654 
4655 	if (ops->timeout_ms)
4656 		timeout = msecs_to_jiffies(ops->timeout_ms);
4657 	else
4658 		timeout = SCX_WATCHDOG_MAX_TIMEOUT;
4659 
4660 	WRITE_ONCE(scx_watchdog_timeout, timeout);
4661 	WRITE_ONCE(scx_watchdog_timestamp, jiffies);
4662 	queue_delayed_work(system_unbound_wq, &scx_watchdog_work,
4663 			   scx_watchdog_timeout / 2);
4664 
4665 	/*
4666 	 * Once __scx_enabled is set, %current can be switched to SCX anytime.
4667 	 * This can lead to stalls as some BPF schedulers (e.g. userspace
4668 	 * scheduling) may not function correctly before all tasks are switched.
4669 	 * Init in bypass mode to guarantee forward progress.
4670 	 */
4671 	scx_bypass(true);
4672 
4673 	for (i = SCX_OPI_NORMAL_BEGIN; i < SCX_OPI_NORMAL_END; i++)
4674 		if (((void (**)(void))ops)[i])
4675 			set_bit(i, sch->has_op);
4676 
4677 	if (sch->ops.cpu_acquire || sch->ops.cpu_release)
4678 		sch->ops.flags |= SCX_OPS_HAS_CPU_PREEMPT;
4679 
4680 	/*
4681 	 * Lock out forks, cgroup on/offlining and moves before opening the
4682 	 * floodgate so that they don't wander into the operations prematurely.
4683 	 */
4684 	percpu_down_write(&scx_fork_rwsem);
4685 
4686 	WARN_ON_ONCE(scx_init_task_enabled);
4687 	scx_init_task_enabled = true;
4688 
4689 	/*
4690 	 * Enable ops for every task. Fork is excluded by scx_fork_rwsem
4691 	 * preventing new tasks from being added. No need to exclude tasks
4692 	 * leaving as sched_ext_free() can handle both prepped and enabled
4693 	 * tasks. Prep all tasks first and then enable them with preemption
4694 	 * disabled.
4695 	 *
4696 	 * All cgroups should be initialized before scx_init_task() so that the
4697 	 * BPF scheduler can reliably track each task's cgroup membership from
4698 	 * scx_init_task(). Lock out cgroup on/offlining and task migrations
4699 	 * while tasks are being initialized so that scx_cgroup_can_attach()
4700 	 * never sees uninitialized tasks.
4701 	 */
4702 	scx_cgroup_lock();
4703 	ret = scx_cgroup_init(sch);
4704 	if (ret)
4705 		goto err_disable_unlock_all;
4706 
4707 	scx_task_iter_start(&sti);
4708 	while ((p = scx_task_iter_next_locked(&sti))) {
4709 		/*
4710 		 * @p may already be dead, have lost all its usages counts and
4711 		 * be waiting for RCU grace period before being freed. @p can't
4712 		 * be initialized for SCX in such cases and should be ignored.
4713 		 */
4714 		if (!tryget_task_struct(p))
4715 			continue;
4716 
4717 		scx_task_iter_unlock(&sti);
4718 
4719 		ret = scx_init_task(p, task_group(p), false);
4720 		if (ret) {
4721 			put_task_struct(p);
4722 			scx_task_iter_stop(&sti);
4723 			scx_error(sch, "ops.init_task() failed (%d) for %s[%d]",
4724 				  ret, p->comm, p->pid);
4725 			goto err_disable_unlock_all;
4726 		}
4727 
4728 		scx_set_task_state(p, SCX_TASK_READY);
4729 
4730 		put_task_struct(p);
4731 	}
4732 	scx_task_iter_stop(&sti);
4733 	scx_cgroup_unlock();
4734 	percpu_up_write(&scx_fork_rwsem);
4735 
4736 	/*
4737 	 * All tasks are READY. It's safe to turn on scx_enabled() and switch
4738 	 * all eligible tasks.
4739 	 */
4740 	WRITE_ONCE(scx_switching_all, !(ops->flags & SCX_OPS_SWITCH_PARTIAL));
4741 	static_branch_enable(&__scx_enabled);
4742 
4743 	/*
4744 	 * We're fully committed and can't fail. The task READY -> ENABLED
4745 	 * transitions here are synchronized against sched_ext_free() through
4746 	 * scx_tasks_lock.
4747 	 */
4748 	percpu_down_write(&scx_fork_rwsem);
4749 	scx_task_iter_start(&sti);
4750 	while ((p = scx_task_iter_next_locked(&sti))) {
4751 		const struct sched_class *old_class = p->sched_class;
4752 		const struct sched_class *new_class =
4753 			__setscheduler_class(p->policy, p->prio);
4754 		struct sched_enq_and_set_ctx ctx;
4755 
4756 		if (!tryget_task_struct(p))
4757 			continue;
4758 
4759 		if (old_class != new_class && p->se.sched_delayed)
4760 			dequeue_task(task_rq(p), p, DEQUEUE_SLEEP | DEQUEUE_DELAYED);
4761 
4762 		sched_deq_and_put_task(p, DEQUEUE_SAVE | DEQUEUE_MOVE, &ctx);
4763 
4764 		p->scx.slice = SCX_SLICE_DFL;
4765 		p->sched_class = new_class;
4766 		check_class_changing(task_rq(p), p, old_class);
4767 
4768 		sched_enq_and_set_task(&ctx);
4769 
4770 		check_class_changed(task_rq(p), p, old_class, p->prio);
4771 		put_task_struct(p);
4772 	}
4773 	scx_task_iter_stop(&sti);
4774 	percpu_up_write(&scx_fork_rwsem);
4775 
4776 	scx_bypass(false);
4777 
4778 	if (!scx_tryset_enable_state(SCX_ENABLED, SCX_ENABLING)) {
4779 		WARN_ON_ONCE(atomic_read(&sch->exit_kind) == SCX_EXIT_NONE);
4780 		goto err_disable;
4781 	}
4782 
4783 	if (!(ops->flags & SCX_OPS_SWITCH_PARTIAL))
4784 		static_branch_enable(&__scx_switched_all);
4785 
4786 	pr_info("sched_ext: BPF scheduler \"%s\" enabled%s\n",
4787 		sch->ops.name, scx_switched_all() ? "" : " (partial)");
4788 	kobject_uevent(&sch->kobj, KOBJ_ADD);
4789 	mutex_unlock(&scx_enable_mutex);
4790 
4791 	atomic_long_inc(&scx_enable_seq);
4792 
4793 	return 0;
4794 
4795 err_free_pseqs:
4796 	free_kick_pseqs();
4797 err_unlock:
4798 	mutex_unlock(&scx_enable_mutex);
4799 	return ret;
4800 
4801 err_disable_unlock_all:
4802 	scx_cgroup_unlock();
4803 	percpu_up_write(&scx_fork_rwsem);
4804 	/* we'll soon enter disable path, keep bypass on */
4805 err_disable:
4806 	mutex_unlock(&scx_enable_mutex);
4807 	/*
4808 	 * Returning an error code here would not pass all the error information
4809 	 * to userspace. Record errno using scx_error() for cases scx_error()
4810 	 * wasn't already invoked and exit indicating success so that the error
4811 	 * is notified through ops.exit() with all the details.
4812 	 *
4813 	 * Flush scx_disable_work to ensure that error is reported before init
4814 	 * completion. sch's base reference will be put by bpf_scx_unreg().
4815 	 */
4816 	scx_error(sch, "scx_enable() failed (%d)", ret);
4817 	kthread_flush_work(&sch->disable_work);
4818 	return 0;
4819 }
4820 
4821 
4822 /********************************************************************************
4823  * bpf_struct_ops plumbing.
4824  */
4825 #include <linux/bpf_verifier.h>
4826 #include <linux/bpf.h>
4827 #include <linux/btf.h>
4828 
4829 static const struct btf_type *task_struct_type;
4830 
bpf_scx_is_valid_access(int off,int size,enum bpf_access_type type,const struct bpf_prog * prog,struct bpf_insn_access_aux * info)4831 static bool bpf_scx_is_valid_access(int off, int size,
4832 				    enum bpf_access_type type,
4833 				    const struct bpf_prog *prog,
4834 				    struct bpf_insn_access_aux *info)
4835 {
4836 	if (type != BPF_READ)
4837 		return false;
4838 	if (off < 0 || off >= sizeof(__u64) * MAX_BPF_FUNC_ARGS)
4839 		return false;
4840 	if (off % size != 0)
4841 		return false;
4842 
4843 	return btf_ctx_access(off, size, type, prog, info);
4844 }
4845 
bpf_scx_btf_struct_access(struct bpf_verifier_log * log,const struct bpf_reg_state * reg,int off,int size)4846 static int bpf_scx_btf_struct_access(struct bpf_verifier_log *log,
4847 				     const struct bpf_reg_state *reg, int off,
4848 				     int size)
4849 {
4850 	const struct btf_type *t;
4851 
4852 	t = btf_type_by_id(reg->btf, reg->btf_id);
4853 	if (t == task_struct_type) {
4854 		if (off >= offsetof(struct task_struct, scx.slice) &&
4855 		    off + size <= offsetofend(struct task_struct, scx.slice))
4856 			return SCALAR_VALUE;
4857 		if (off >= offsetof(struct task_struct, scx.dsq_vtime) &&
4858 		    off + size <= offsetofend(struct task_struct, scx.dsq_vtime))
4859 			return SCALAR_VALUE;
4860 		if (off >= offsetof(struct task_struct, scx.disallow) &&
4861 		    off + size <= offsetofend(struct task_struct, scx.disallow))
4862 			return SCALAR_VALUE;
4863 	}
4864 
4865 	return -EACCES;
4866 }
4867 
4868 static const struct bpf_verifier_ops bpf_scx_verifier_ops = {
4869 	.get_func_proto = bpf_base_func_proto,
4870 	.is_valid_access = bpf_scx_is_valid_access,
4871 	.btf_struct_access = bpf_scx_btf_struct_access,
4872 };
4873 
bpf_scx_init_member(const struct btf_type * t,const struct btf_member * member,void * kdata,const void * udata)4874 static int bpf_scx_init_member(const struct btf_type *t,
4875 			       const struct btf_member *member,
4876 			       void *kdata, const void *udata)
4877 {
4878 	const struct sched_ext_ops *uops = udata;
4879 	struct sched_ext_ops *ops = kdata;
4880 	u32 moff = __btf_member_bit_offset(t, member) / 8;
4881 	int ret;
4882 
4883 	switch (moff) {
4884 	case offsetof(struct sched_ext_ops, dispatch_max_batch):
4885 		if (*(u32 *)(udata + moff) > INT_MAX)
4886 			return -E2BIG;
4887 		ops->dispatch_max_batch = *(u32 *)(udata + moff);
4888 		return 1;
4889 	case offsetof(struct sched_ext_ops, flags):
4890 		if (*(u64 *)(udata + moff) & ~SCX_OPS_ALL_FLAGS)
4891 			return -EINVAL;
4892 		ops->flags = *(u64 *)(udata + moff);
4893 		return 1;
4894 	case offsetof(struct sched_ext_ops, name):
4895 		ret = bpf_obj_name_cpy(ops->name, uops->name,
4896 				       sizeof(ops->name));
4897 		if (ret < 0)
4898 			return ret;
4899 		if (ret == 0)
4900 			return -EINVAL;
4901 		return 1;
4902 	case offsetof(struct sched_ext_ops, timeout_ms):
4903 		if (msecs_to_jiffies(*(u32 *)(udata + moff)) >
4904 		    SCX_WATCHDOG_MAX_TIMEOUT)
4905 			return -E2BIG;
4906 		ops->timeout_ms = *(u32 *)(udata + moff);
4907 		return 1;
4908 	case offsetof(struct sched_ext_ops, exit_dump_len):
4909 		ops->exit_dump_len =
4910 			*(u32 *)(udata + moff) ?: SCX_EXIT_DUMP_DFL_LEN;
4911 		return 1;
4912 	case offsetof(struct sched_ext_ops, hotplug_seq):
4913 		ops->hotplug_seq = *(u64 *)(udata + moff);
4914 		return 1;
4915 	}
4916 
4917 	return 0;
4918 }
4919 
bpf_scx_check_member(const struct btf_type * t,const struct btf_member * member,const struct bpf_prog * prog)4920 static int bpf_scx_check_member(const struct btf_type *t,
4921 				const struct btf_member *member,
4922 				const struct bpf_prog *prog)
4923 {
4924 	u32 moff = __btf_member_bit_offset(t, member) / 8;
4925 
4926 	switch (moff) {
4927 	case offsetof(struct sched_ext_ops, init_task):
4928 #ifdef CONFIG_EXT_GROUP_SCHED
4929 	case offsetof(struct sched_ext_ops, cgroup_init):
4930 	case offsetof(struct sched_ext_ops, cgroup_exit):
4931 	case offsetof(struct sched_ext_ops, cgroup_prep_move):
4932 #endif
4933 	case offsetof(struct sched_ext_ops, cpu_online):
4934 	case offsetof(struct sched_ext_ops, cpu_offline):
4935 	case offsetof(struct sched_ext_ops, init):
4936 	case offsetof(struct sched_ext_ops, exit):
4937 		break;
4938 	default:
4939 		if (prog->sleepable)
4940 			return -EINVAL;
4941 	}
4942 
4943 	return 0;
4944 }
4945 
bpf_scx_reg(void * kdata,struct bpf_link * link)4946 static int bpf_scx_reg(void *kdata, struct bpf_link *link)
4947 {
4948 	return scx_enable(kdata, link);
4949 }
4950 
bpf_scx_unreg(void * kdata,struct bpf_link * link)4951 static void bpf_scx_unreg(void *kdata, struct bpf_link *link)
4952 {
4953 	struct sched_ext_ops *ops = kdata;
4954 	struct scx_sched *sch = ops->priv;
4955 
4956 	scx_disable(SCX_EXIT_UNREG);
4957 	kthread_flush_work(&sch->disable_work);
4958 	kobject_put(&sch->kobj);
4959 }
4960 
bpf_scx_init(struct btf * btf)4961 static int bpf_scx_init(struct btf *btf)
4962 {
4963 	task_struct_type = btf_type_by_id(btf, btf_tracing_ids[BTF_TRACING_TYPE_TASK]);
4964 
4965 	return 0;
4966 }
4967 
bpf_scx_update(void * kdata,void * old_kdata,struct bpf_link * link)4968 static int bpf_scx_update(void *kdata, void *old_kdata, struct bpf_link *link)
4969 {
4970 	/*
4971 	 * sched_ext does not support updating the actively-loaded BPF
4972 	 * scheduler, as registering a BPF scheduler can always fail if the
4973 	 * scheduler returns an error code for e.g. ops.init(), ops.init_task(),
4974 	 * etc. Similarly, we can always race with unregistration happening
4975 	 * elsewhere, such as with sysrq.
4976 	 */
4977 	return -EOPNOTSUPP;
4978 }
4979 
bpf_scx_validate(void * kdata)4980 static int bpf_scx_validate(void *kdata)
4981 {
4982 	return 0;
4983 }
4984 
sched_ext_ops__select_cpu(struct task_struct * p,s32 prev_cpu,u64 wake_flags)4985 static s32 sched_ext_ops__select_cpu(struct task_struct *p, s32 prev_cpu, u64 wake_flags) { return -EINVAL; }
sched_ext_ops__enqueue(struct task_struct * p,u64 enq_flags)4986 static void sched_ext_ops__enqueue(struct task_struct *p, u64 enq_flags) {}
sched_ext_ops__dequeue(struct task_struct * p,u64 enq_flags)4987 static void sched_ext_ops__dequeue(struct task_struct *p, u64 enq_flags) {}
sched_ext_ops__dispatch(s32 prev_cpu,struct task_struct * prev__nullable)4988 static void sched_ext_ops__dispatch(s32 prev_cpu, struct task_struct *prev__nullable) {}
sched_ext_ops__tick(struct task_struct * p)4989 static void sched_ext_ops__tick(struct task_struct *p) {}
sched_ext_ops__runnable(struct task_struct * p,u64 enq_flags)4990 static void sched_ext_ops__runnable(struct task_struct *p, u64 enq_flags) {}
sched_ext_ops__running(struct task_struct * p)4991 static void sched_ext_ops__running(struct task_struct *p) {}
sched_ext_ops__stopping(struct task_struct * p,bool runnable)4992 static void sched_ext_ops__stopping(struct task_struct *p, bool runnable) {}
sched_ext_ops__quiescent(struct task_struct * p,u64 deq_flags)4993 static void sched_ext_ops__quiescent(struct task_struct *p, u64 deq_flags) {}
sched_ext_ops__yield(struct task_struct * from,struct task_struct * to__nullable)4994 static bool sched_ext_ops__yield(struct task_struct *from, struct task_struct *to__nullable) { return false; }
sched_ext_ops__core_sched_before(struct task_struct * a,struct task_struct * b)4995 static bool sched_ext_ops__core_sched_before(struct task_struct *a, struct task_struct *b) { return false; }
sched_ext_ops__set_weight(struct task_struct * p,u32 weight)4996 static void sched_ext_ops__set_weight(struct task_struct *p, u32 weight) {}
sched_ext_ops__set_cpumask(struct task_struct * p,const struct cpumask * mask)4997 static void sched_ext_ops__set_cpumask(struct task_struct *p, const struct cpumask *mask) {}
sched_ext_ops__update_idle(s32 cpu,bool idle)4998 static void sched_ext_ops__update_idle(s32 cpu, bool idle) {}
sched_ext_ops__cpu_acquire(s32 cpu,struct scx_cpu_acquire_args * args)4999 static void sched_ext_ops__cpu_acquire(s32 cpu, struct scx_cpu_acquire_args *args) {}
sched_ext_ops__cpu_release(s32 cpu,struct scx_cpu_release_args * args)5000 static void sched_ext_ops__cpu_release(s32 cpu, struct scx_cpu_release_args *args) {}
sched_ext_ops__init_task(struct task_struct * p,struct scx_init_task_args * args)5001 static s32 sched_ext_ops__init_task(struct task_struct *p, struct scx_init_task_args *args) { return -EINVAL; }
sched_ext_ops__exit_task(struct task_struct * p,struct scx_exit_task_args * args)5002 static void sched_ext_ops__exit_task(struct task_struct *p, struct scx_exit_task_args *args) {}
sched_ext_ops__enable(struct task_struct * p)5003 static void sched_ext_ops__enable(struct task_struct *p) {}
sched_ext_ops__disable(struct task_struct * p)5004 static void sched_ext_ops__disable(struct task_struct *p) {}
5005 #ifdef CONFIG_EXT_GROUP_SCHED
sched_ext_ops__cgroup_init(struct cgroup * cgrp,struct scx_cgroup_init_args * args)5006 static s32 sched_ext_ops__cgroup_init(struct cgroup *cgrp, struct scx_cgroup_init_args *args) { return -EINVAL; }
sched_ext_ops__cgroup_exit(struct cgroup * cgrp)5007 static void sched_ext_ops__cgroup_exit(struct cgroup *cgrp) {}
sched_ext_ops__cgroup_prep_move(struct task_struct * p,struct cgroup * from,struct cgroup * to)5008 static s32 sched_ext_ops__cgroup_prep_move(struct task_struct *p, struct cgroup *from, struct cgroup *to) { return -EINVAL; }
sched_ext_ops__cgroup_move(struct task_struct * p,struct cgroup * from,struct cgroup * to)5009 static void sched_ext_ops__cgroup_move(struct task_struct *p, struct cgroup *from, struct cgroup *to) {}
sched_ext_ops__cgroup_cancel_move(struct task_struct * p,struct cgroup * from,struct cgroup * to)5010 static void sched_ext_ops__cgroup_cancel_move(struct task_struct *p, struct cgroup *from, struct cgroup *to) {}
sched_ext_ops__cgroup_set_weight(struct cgroup * cgrp,u32 weight)5011 static void sched_ext_ops__cgroup_set_weight(struct cgroup *cgrp, u32 weight) {}
sched_ext_ops__cgroup_set_bandwidth(struct cgroup * cgrp,u64 period_us,u64 quota_us,u64 burst_us)5012 static void sched_ext_ops__cgroup_set_bandwidth(struct cgroup *cgrp, u64 period_us, u64 quota_us, u64 burst_us) {}
5013 #endif
sched_ext_ops__cpu_online(s32 cpu)5014 static void sched_ext_ops__cpu_online(s32 cpu) {}
sched_ext_ops__cpu_offline(s32 cpu)5015 static void sched_ext_ops__cpu_offline(s32 cpu) {}
sched_ext_ops__init(void)5016 static s32 sched_ext_ops__init(void) { return -EINVAL; }
sched_ext_ops__exit(struct scx_exit_info * info)5017 static void sched_ext_ops__exit(struct scx_exit_info *info) {}
sched_ext_ops__dump(struct scx_dump_ctx * ctx)5018 static void sched_ext_ops__dump(struct scx_dump_ctx *ctx) {}
sched_ext_ops__dump_cpu(struct scx_dump_ctx * ctx,s32 cpu,bool idle)5019 static void sched_ext_ops__dump_cpu(struct scx_dump_ctx *ctx, s32 cpu, bool idle) {}
sched_ext_ops__dump_task(struct scx_dump_ctx * ctx,struct task_struct * p)5020 static void sched_ext_ops__dump_task(struct scx_dump_ctx *ctx, struct task_struct *p) {}
5021 
5022 static struct sched_ext_ops __bpf_ops_sched_ext_ops = {
5023 	.select_cpu		= sched_ext_ops__select_cpu,
5024 	.enqueue		= sched_ext_ops__enqueue,
5025 	.dequeue		= sched_ext_ops__dequeue,
5026 	.dispatch		= sched_ext_ops__dispatch,
5027 	.tick			= sched_ext_ops__tick,
5028 	.runnable		= sched_ext_ops__runnable,
5029 	.running		= sched_ext_ops__running,
5030 	.stopping		= sched_ext_ops__stopping,
5031 	.quiescent		= sched_ext_ops__quiescent,
5032 	.yield			= sched_ext_ops__yield,
5033 	.core_sched_before	= sched_ext_ops__core_sched_before,
5034 	.set_weight		= sched_ext_ops__set_weight,
5035 	.set_cpumask		= sched_ext_ops__set_cpumask,
5036 	.update_idle		= sched_ext_ops__update_idle,
5037 	.cpu_acquire		= sched_ext_ops__cpu_acquire,
5038 	.cpu_release		= sched_ext_ops__cpu_release,
5039 	.init_task		= sched_ext_ops__init_task,
5040 	.exit_task		= sched_ext_ops__exit_task,
5041 	.enable			= sched_ext_ops__enable,
5042 	.disable		= sched_ext_ops__disable,
5043 #ifdef CONFIG_EXT_GROUP_SCHED
5044 	.cgroup_init		= sched_ext_ops__cgroup_init,
5045 	.cgroup_exit		= sched_ext_ops__cgroup_exit,
5046 	.cgroup_prep_move	= sched_ext_ops__cgroup_prep_move,
5047 	.cgroup_move		= sched_ext_ops__cgroup_move,
5048 	.cgroup_cancel_move	= sched_ext_ops__cgroup_cancel_move,
5049 	.cgroup_set_weight	= sched_ext_ops__cgroup_set_weight,
5050 	.cgroup_set_bandwidth	= sched_ext_ops__cgroup_set_bandwidth,
5051 #endif
5052 	.cpu_online		= sched_ext_ops__cpu_online,
5053 	.cpu_offline		= sched_ext_ops__cpu_offline,
5054 	.init			= sched_ext_ops__init,
5055 	.exit			= sched_ext_ops__exit,
5056 	.dump			= sched_ext_ops__dump,
5057 	.dump_cpu		= sched_ext_ops__dump_cpu,
5058 	.dump_task		= sched_ext_ops__dump_task,
5059 };
5060 
5061 static struct bpf_struct_ops bpf_sched_ext_ops = {
5062 	.verifier_ops = &bpf_scx_verifier_ops,
5063 	.reg = bpf_scx_reg,
5064 	.unreg = bpf_scx_unreg,
5065 	.check_member = bpf_scx_check_member,
5066 	.init_member = bpf_scx_init_member,
5067 	.init = bpf_scx_init,
5068 	.update = bpf_scx_update,
5069 	.validate = bpf_scx_validate,
5070 	.name = "sched_ext_ops",
5071 	.owner = THIS_MODULE,
5072 	.cfi_stubs = &__bpf_ops_sched_ext_ops
5073 };
5074 
5075 
5076 /********************************************************************************
5077  * System integration and init.
5078  */
5079 
sysrq_handle_sched_ext_reset(u8 key)5080 static void sysrq_handle_sched_ext_reset(u8 key)
5081 {
5082 	scx_disable(SCX_EXIT_SYSRQ);
5083 }
5084 
5085 static const struct sysrq_key_op sysrq_sched_ext_reset_op = {
5086 	.handler	= sysrq_handle_sched_ext_reset,
5087 	.help_msg	= "reset-sched-ext(S)",
5088 	.action_msg	= "Disable sched_ext and revert all tasks to CFS",
5089 	.enable_mask	= SYSRQ_ENABLE_RTNICE,
5090 };
5091 
sysrq_handle_sched_ext_dump(u8 key)5092 static void sysrq_handle_sched_ext_dump(u8 key)
5093 {
5094 	struct scx_exit_info ei = { .kind = SCX_EXIT_NONE, .reason = "SysRq-D" };
5095 
5096 	if (scx_enabled())
5097 		scx_dump_state(&ei, 0);
5098 }
5099 
5100 static const struct sysrq_key_op sysrq_sched_ext_dump_op = {
5101 	.handler	= sysrq_handle_sched_ext_dump,
5102 	.help_msg	= "dump-sched-ext(D)",
5103 	.action_msg	= "Trigger sched_ext debug dump",
5104 	.enable_mask	= SYSRQ_ENABLE_RTNICE,
5105 };
5106 
can_skip_idle_kick(struct rq * rq)5107 static bool can_skip_idle_kick(struct rq *rq)
5108 {
5109 	lockdep_assert_rq_held(rq);
5110 
5111 	/*
5112 	 * We can skip idle kicking if @rq is going to go through at least one
5113 	 * full SCX scheduling cycle before going idle. Just checking whether
5114 	 * curr is not idle is insufficient because we could be racing
5115 	 * balance_one() trying to pull the next task from a remote rq, which
5116 	 * may fail, and @rq may become idle afterwards.
5117 	 *
5118 	 * The race window is small and we don't and can't guarantee that @rq is
5119 	 * only kicked while idle anyway. Skip only when sure.
5120 	 */
5121 	return !is_idle_task(rq->curr) && !(rq->scx.flags & SCX_RQ_IN_BALANCE);
5122 }
5123 
kick_one_cpu(s32 cpu,struct rq * this_rq,unsigned long * pseqs)5124 static bool kick_one_cpu(s32 cpu, struct rq *this_rq, unsigned long *pseqs)
5125 {
5126 	struct rq *rq = cpu_rq(cpu);
5127 	struct scx_rq *this_scx = &this_rq->scx;
5128 	bool should_wait = false;
5129 	unsigned long flags;
5130 
5131 	raw_spin_rq_lock_irqsave(rq, flags);
5132 
5133 	/*
5134 	 * During CPU hotplug, a CPU may depend on kicking itself to make
5135 	 * forward progress. Allow kicking self regardless of online state.
5136 	 */
5137 	if (cpu_online(cpu) || cpu == cpu_of(this_rq)) {
5138 		if (cpumask_test_cpu(cpu, this_scx->cpus_to_preempt)) {
5139 			if (rq->curr->sched_class == &ext_sched_class)
5140 				rq->curr->scx.slice = 0;
5141 			cpumask_clear_cpu(cpu, this_scx->cpus_to_preempt);
5142 		}
5143 
5144 		if (cpumask_test_cpu(cpu, this_scx->cpus_to_wait)) {
5145 			pseqs[cpu] = rq->scx.pnt_seq;
5146 			should_wait = true;
5147 		}
5148 
5149 		resched_curr(rq);
5150 	} else {
5151 		cpumask_clear_cpu(cpu, this_scx->cpus_to_preempt);
5152 		cpumask_clear_cpu(cpu, this_scx->cpus_to_wait);
5153 	}
5154 
5155 	raw_spin_rq_unlock_irqrestore(rq, flags);
5156 
5157 	return should_wait;
5158 }
5159 
kick_one_cpu_if_idle(s32 cpu,struct rq * this_rq)5160 static void kick_one_cpu_if_idle(s32 cpu, struct rq *this_rq)
5161 {
5162 	struct rq *rq = cpu_rq(cpu);
5163 	unsigned long flags;
5164 
5165 	raw_spin_rq_lock_irqsave(rq, flags);
5166 
5167 	if (!can_skip_idle_kick(rq) &&
5168 	    (cpu_online(cpu) || cpu == cpu_of(this_rq)))
5169 		resched_curr(rq);
5170 
5171 	raw_spin_rq_unlock_irqrestore(rq, flags);
5172 }
5173 
kick_cpus_irq_workfn(struct irq_work * irq_work)5174 static void kick_cpus_irq_workfn(struct irq_work *irq_work)
5175 {
5176 	struct rq *this_rq = this_rq();
5177 	struct scx_rq *this_scx = &this_rq->scx;
5178 	struct scx_kick_pseqs __rcu *pseqs_pcpu = __this_cpu_read(scx_kick_pseqs);
5179 	bool should_wait = false;
5180 	unsigned long *pseqs;
5181 	s32 cpu;
5182 
5183 	if (unlikely(!pseqs_pcpu)) {
5184 		pr_warn_once("kick_cpus_irq_workfn() called with NULL scx_kick_pseqs");
5185 		return;
5186 	}
5187 
5188 	pseqs = rcu_dereference_bh(pseqs_pcpu)->seqs;
5189 
5190 	for_each_cpu(cpu, this_scx->cpus_to_kick) {
5191 		should_wait |= kick_one_cpu(cpu, this_rq, pseqs);
5192 		cpumask_clear_cpu(cpu, this_scx->cpus_to_kick);
5193 		cpumask_clear_cpu(cpu, this_scx->cpus_to_kick_if_idle);
5194 	}
5195 
5196 	for_each_cpu(cpu, this_scx->cpus_to_kick_if_idle) {
5197 		kick_one_cpu_if_idle(cpu, this_rq);
5198 		cpumask_clear_cpu(cpu, this_scx->cpus_to_kick_if_idle);
5199 	}
5200 
5201 	if (!should_wait)
5202 		return;
5203 
5204 	for_each_cpu(cpu, this_scx->cpus_to_wait) {
5205 		unsigned long *wait_pnt_seq = &cpu_rq(cpu)->scx.pnt_seq;
5206 
5207 		if (cpu != cpu_of(this_rq)) {
5208 			/*
5209 			 * Pairs with smp_store_release() issued by this CPU in
5210 			 * switch_class() on the resched path.
5211 			 *
5212 			 * We busy-wait here to guarantee that no other task can
5213 			 * be scheduled on our core before the target CPU has
5214 			 * entered the resched path.
5215 			 */
5216 			while (smp_load_acquire(wait_pnt_seq) == pseqs[cpu])
5217 				cpu_relax();
5218 		}
5219 
5220 		cpumask_clear_cpu(cpu, this_scx->cpus_to_wait);
5221 	}
5222 }
5223 
5224 /**
5225  * print_scx_info - print out sched_ext scheduler state
5226  * @log_lvl: the log level to use when printing
5227  * @p: target task
5228  *
5229  * If a sched_ext scheduler is enabled, print the name and state of the
5230  * scheduler. If @p is on sched_ext, print further information about the task.
5231  *
5232  * This function can be safely called on any task as long as the task_struct
5233  * itself is accessible. While safe, this function isn't synchronized and may
5234  * print out mixups or garbages of limited length.
5235  */
print_scx_info(const char * log_lvl,struct task_struct * p)5236 void print_scx_info(const char *log_lvl, struct task_struct *p)
5237 {
5238 	struct scx_sched *sch = scx_root;
5239 	enum scx_enable_state state = scx_enable_state();
5240 	const char *all = READ_ONCE(scx_switching_all) ? "+all" : "";
5241 	char runnable_at_buf[22] = "?";
5242 	struct sched_class *class;
5243 	unsigned long runnable_at;
5244 
5245 	if (state == SCX_DISABLED)
5246 		return;
5247 
5248 	/*
5249 	 * Carefully check if the task was running on sched_ext, and then
5250 	 * carefully copy the time it's been runnable, and its state.
5251 	 */
5252 	if (copy_from_kernel_nofault(&class, &p->sched_class, sizeof(class)) ||
5253 	    class != &ext_sched_class) {
5254 		printk("%sSched_ext: %s (%s%s)", log_lvl, sch->ops.name,
5255 		       scx_enable_state_str[state], all);
5256 		return;
5257 	}
5258 
5259 	if (!copy_from_kernel_nofault(&runnable_at, &p->scx.runnable_at,
5260 				      sizeof(runnable_at)))
5261 		scnprintf(runnable_at_buf, sizeof(runnable_at_buf), "%+ldms",
5262 			  jiffies_delta_msecs(runnable_at, jiffies));
5263 
5264 	/* print everything onto one line to conserve console space */
5265 	printk("%sSched_ext: %s (%s%s), task: runnable_at=%s",
5266 	       log_lvl, sch->ops.name, scx_enable_state_str[state], all,
5267 	       runnable_at_buf);
5268 }
5269 
scx_pm_handler(struct notifier_block * nb,unsigned long event,void * ptr)5270 static int scx_pm_handler(struct notifier_block *nb, unsigned long event, void *ptr)
5271 {
5272 	/*
5273 	 * SCX schedulers often have userspace components which are sometimes
5274 	 * involved in critial scheduling paths. PM operations involve freezing
5275 	 * userspace which can lead to scheduling misbehaviors including stalls.
5276 	 * Let's bypass while PM operations are in progress.
5277 	 */
5278 	switch (event) {
5279 	case PM_HIBERNATION_PREPARE:
5280 	case PM_SUSPEND_PREPARE:
5281 	case PM_RESTORE_PREPARE:
5282 		scx_bypass(true);
5283 		break;
5284 	case PM_POST_HIBERNATION:
5285 	case PM_POST_SUSPEND:
5286 	case PM_POST_RESTORE:
5287 		scx_bypass(false);
5288 		break;
5289 	}
5290 
5291 	return NOTIFY_OK;
5292 }
5293 
5294 static struct notifier_block scx_pm_notifier = {
5295 	.notifier_call = scx_pm_handler,
5296 };
5297 
init_sched_ext_class(void)5298 void __init init_sched_ext_class(void)
5299 {
5300 	s32 cpu, v;
5301 
5302 	/*
5303 	 * The following is to prevent the compiler from optimizing out the enum
5304 	 * definitions so that BPF scheduler implementations can use them
5305 	 * through the generated vmlinux.h.
5306 	 */
5307 	WRITE_ONCE(v, SCX_ENQ_WAKEUP | SCX_DEQ_SLEEP | SCX_KICK_PREEMPT |
5308 		   SCX_TG_ONLINE);
5309 
5310 	scx_idle_init_masks();
5311 
5312 	for_each_possible_cpu(cpu) {
5313 		struct rq *rq = cpu_rq(cpu);
5314 		int  n = cpu_to_node(cpu);
5315 
5316 		init_dsq(&rq->scx.local_dsq, SCX_DSQ_LOCAL);
5317 		INIT_LIST_HEAD(&rq->scx.runnable_list);
5318 		INIT_LIST_HEAD(&rq->scx.ddsp_deferred_locals);
5319 
5320 		BUG_ON(!zalloc_cpumask_var_node(&rq->scx.cpus_to_kick, GFP_KERNEL, n));
5321 		BUG_ON(!zalloc_cpumask_var_node(&rq->scx.cpus_to_kick_if_idle, GFP_KERNEL, n));
5322 		BUG_ON(!zalloc_cpumask_var_node(&rq->scx.cpus_to_preempt, GFP_KERNEL, n));
5323 		BUG_ON(!zalloc_cpumask_var_node(&rq->scx.cpus_to_wait, GFP_KERNEL, n));
5324 		init_irq_work(&rq->scx.deferred_irq_work, deferred_irq_workfn);
5325 		init_irq_work(&rq->scx.kick_cpus_irq_work, kick_cpus_irq_workfn);
5326 
5327 		if (cpu_online(cpu))
5328 			cpu_rq(cpu)->scx.flags |= SCX_RQ_ONLINE;
5329 	}
5330 
5331 	register_sysrq_key('S', &sysrq_sched_ext_reset_op);
5332 	register_sysrq_key('D', &sysrq_sched_ext_dump_op);
5333 	INIT_DELAYED_WORK(&scx_watchdog_work, scx_watchdog_workfn);
5334 }
5335 
5336 
5337 /********************************************************************************
5338  * Helpers that can be called from the BPF scheduler.
5339  */
scx_dsq_insert_preamble(struct scx_sched * sch,struct task_struct * p,u64 enq_flags)5340 static bool scx_dsq_insert_preamble(struct scx_sched *sch, struct task_struct *p,
5341 				    u64 enq_flags)
5342 {
5343 	if (!scx_kf_allowed(sch, SCX_KF_ENQUEUE | SCX_KF_DISPATCH))
5344 		return false;
5345 
5346 	lockdep_assert_irqs_disabled();
5347 
5348 	if (unlikely(!p)) {
5349 		scx_error(sch, "called with NULL task");
5350 		return false;
5351 	}
5352 
5353 	if (unlikely(enq_flags & __SCX_ENQ_INTERNAL_MASK)) {
5354 		scx_error(sch, "invalid enq_flags 0x%llx", enq_flags);
5355 		return false;
5356 	}
5357 
5358 	return true;
5359 }
5360 
scx_dsq_insert_commit(struct scx_sched * sch,struct task_struct * p,u64 dsq_id,u64 enq_flags)5361 static void scx_dsq_insert_commit(struct scx_sched *sch, struct task_struct *p,
5362 				  u64 dsq_id, u64 enq_flags)
5363 {
5364 	struct scx_dsp_ctx *dspc = this_cpu_ptr(scx_dsp_ctx);
5365 	struct task_struct *ddsp_task;
5366 
5367 	ddsp_task = __this_cpu_read(direct_dispatch_task);
5368 	if (ddsp_task) {
5369 		mark_direct_dispatch(sch, ddsp_task, p, dsq_id, enq_flags);
5370 		return;
5371 	}
5372 
5373 	if (unlikely(dspc->cursor >= scx_dsp_max_batch)) {
5374 		scx_error(sch, "dispatch buffer overflow");
5375 		return;
5376 	}
5377 
5378 	dspc->buf[dspc->cursor++] = (struct scx_dsp_buf_ent){
5379 		.task = p,
5380 		.qseq = atomic_long_read(&p->scx.ops_state) & SCX_OPSS_QSEQ_MASK,
5381 		.dsq_id = dsq_id,
5382 		.enq_flags = enq_flags,
5383 	};
5384 }
5385 
5386 __bpf_kfunc_start_defs();
5387 
5388 /**
5389  * scx_bpf_dsq_insert - Insert a task into the FIFO queue of a DSQ
5390  * @p: task_struct to insert
5391  * @dsq_id: DSQ to insert into
5392  * @slice: duration @p can run for in nsecs, 0 to keep the current value
5393  * @enq_flags: SCX_ENQ_*
5394  *
5395  * Insert @p into the FIFO queue of the DSQ identified by @dsq_id. It is safe to
5396  * call this function spuriously. Can be called from ops.enqueue(),
5397  * ops.select_cpu(), and ops.dispatch().
5398  *
5399  * When called from ops.select_cpu() or ops.enqueue(), it's for direct dispatch
5400  * and @p must match the task being enqueued.
5401  *
5402  * When called from ops.select_cpu(), @enq_flags and @dsp_id are stored, and @p
5403  * will be directly inserted into the corresponding dispatch queue after
5404  * ops.select_cpu() returns. If @p is inserted into SCX_DSQ_LOCAL, it will be
5405  * inserted into the local DSQ of the CPU returned by ops.select_cpu().
5406  * @enq_flags are OR'd with the enqueue flags on the enqueue path before the
5407  * task is inserted.
5408  *
5409  * When called from ops.dispatch(), there are no restrictions on @p or @dsq_id
5410  * and this function can be called upto ops.dispatch_max_batch times to insert
5411  * multiple tasks. scx_bpf_dispatch_nr_slots() returns the number of the
5412  * remaining slots. scx_bpf_dsq_move_to_local() flushes the batch and resets the
5413  * counter.
5414  *
5415  * This function doesn't have any locking restrictions and may be called under
5416  * BPF locks (in the future when BPF introduces more flexible locking).
5417  *
5418  * @p is allowed to run for @slice. The scheduling path is triggered on slice
5419  * exhaustion. If zero, the current residual slice is maintained. If
5420  * %SCX_SLICE_INF, @p never expires and the BPF scheduler must kick the CPU with
5421  * scx_bpf_kick_cpu() to trigger scheduling.
5422  */
scx_bpf_dsq_insert(struct task_struct * p,u64 dsq_id,u64 slice,u64 enq_flags)5423 __bpf_kfunc void scx_bpf_dsq_insert(struct task_struct *p, u64 dsq_id, u64 slice,
5424 				    u64 enq_flags)
5425 {
5426 	struct scx_sched *sch;
5427 
5428 	guard(rcu)();
5429 	sch = rcu_dereference(scx_root);
5430 	if (unlikely(!sch))
5431 		return;
5432 
5433 	if (!scx_dsq_insert_preamble(sch, p, enq_flags))
5434 		return;
5435 
5436 	if (slice)
5437 		p->scx.slice = slice;
5438 	else
5439 		p->scx.slice = p->scx.slice ?: 1;
5440 
5441 	scx_dsq_insert_commit(sch, p, dsq_id, enq_flags);
5442 }
5443 
5444 /**
5445  * scx_bpf_dsq_insert_vtime - Insert a task into the vtime priority queue of a DSQ
5446  * @p: task_struct to insert
5447  * @dsq_id: DSQ to insert into
5448  * @slice: duration @p can run for in nsecs, 0 to keep the current value
5449  * @vtime: @p's ordering inside the vtime-sorted queue of the target DSQ
5450  * @enq_flags: SCX_ENQ_*
5451  *
5452  * Insert @p into the vtime priority queue of the DSQ identified by @dsq_id.
5453  * Tasks queued into the priority queue are ordered by @vtime. All other aspects
5454  * are identical to scx_bpf_dsq_insert().
5455  *
5456  * @vtime ordering is according to time_before64() which considers wrapping. A
5457  * numerically larger vtime may indicate an earlier position in the ordering and
5458  * vice-versa.
5459  *
5460  * A DSQ can only be used as a FIFO or priority queue at any given time and this
5461  * function must not be called on a DSQ which already has one or more FIFO tasks
5462  * queued and vice-versa. Also, the built-in DSQs (SCX_DSQ_LOCAL and
5463  * SCX_DSQ_GLOBAL) cannot be used as priority queues.
5464  */
scx_bpf_dsq_insert_vtime(struct task_struct * p,u64 dsq_id,u64 slice,u64 vtime,u64 enq_flags)5465 __bpf_kfunc void scx_bpf_dsq_insert_vtime(struct task_struct *p, u64 dsq_id,
5466 					  u64 slice, u64 vtime, u64 enq_flags)
5467 {
5468 	struct scx_sched *sch;
5469 
5470 	guard(rcu)();
5471 	sch = rcu_dereference(scx_root);
5472 	if (unlikely(!sch))
5473 		return;
5474 
5475 	if (!scx_dsq_insert_preamble(sch, p, enq_flags))
5476 		return;
5477 
5478 	if (slice)
5479 		p->scx.slice = slice;
5480 	else
5481 		p->scx.slice = p->scx.slice ?: 1;
5482 
5483 	p->scx.dsq_vtime = vtime;
5484 
5485 	scx_dsq_insert_commit(sch, p, dsq_id, enq_flags | SCX_ENQ_DSQ_PRIQ);
5486 }
5487 
5488 __bpf_kfunc_end_defs();
5489 
5490 BTF_KFUNCS_START(scx_kfunc_ids_enqueue_dispatch)
5491 BTF_ID_FLAGS(func, scx_bpf_dsq_insert, KF_RCU)
5492 BTF_ID_FLAGS(func, scx_bpf_dsq_insert_vtime, KF_RCU)
5493 BTF_KFUNCS_END(scx_kfunc_ids_enqueue_dispatch)
5494 
5495 static const struct btf_kfunc_id_set scx_kfunc_set_enqueue_dispatch = {
5496 	.owner			= THIS_MODULE,
5497 	.set			= &scx_kfunc_ids_enqueue_dispatch,
5498 };
5499 
scx_dsq_move(struct bpf_iter_scx_dsq_kern * kit,struct task_struct * p,u64 dsq_id,u64 enq_flags)5500 static bool scx_dsq_move(struct bpf_iter_scx_dsq_kern *kit,
5501 			 struct task_struct *p, u64 dsq_id, u64 enq_flags)
5502 {
5503 	struct scx_sched *sch = scx_root;
5504 	struct scx_dispatch_q *src_dsq = kit->dsq, *dst_dsq;
5505 	struct rq *this_rq, *src_rq, *locked_rq;
5506 	bool dispatched = false;
5507 	bool in_balance;
5508 	unsigned long flags;
5509 
5510 	if (!scx_kf_allowed_if_unlocked() &&
5511 	    !scx_kf_allowed(sch, SCX_KF_DISPATCH))
5512 		return false;
5513 
5514 	/*
5515 	 * Can be called from either ops.dispatch() locking this_rq() or any
5516 	 * context where no rq lock is held. If latter, lock @p's task_rq which
5517 	 * we'll likely need anyway.
5518 	 */
5519 	src_rq = task_rq(p);
5520 
5521 	local_irq_save(flags);
5522 	this_rq = this_rq();
5523 	in_balance = this_rq->scx.flags & SCX_RQ_IN_BALANCE;
5524 
5525 	if (in_balance) {
5526 		if (this_rq != src_rq) {
5527 			raw_spin_rq_unlock(this_rq);
5528 			raw_spin_rq_lock(src_rq);
5529 		}
5530 	} else {
5531 		raw_spin_rq_lock(src_rq);
5532 	}
5533 
5534 	/*
5535 	 * If the BPF scheduler keeps calling this function repeatedly, it can
5536 	 * cause similar live-lock conditions as consume_dispatch_q(). Insert a
5537 	 * breather if necessary.
5538 	 */
5539 	scx_breather(src_rq);
5540 
5541 	locked_rq = src_rq;
5542 	raw_spin_lock(&src_dsq->lock);
5543 
5544 	/*
5545 	 * Did someone else get to it? @p could have already left $src_dsq, got
5546 	 * re-enqueud, or be in the process of being consumed by someone else.
5547 	 */
5548 	if (unlikely(p->scx.dsq != src_dsq ||
5549 		     u32_before(kit->cursor.priv, p->scx.dsq_seq) ||
5550 		     p->scx.holding_cpu >= 0) ||
5551 	    WARN_ON_ONCE(src_rq != task_rq(p))) {
5552 		raw_spin_unlock(&src_dsq->lock);
5553 		goto out;
5554 	}
5555 
5556 	/* @p is still on $src_dsq and stable, determine the destination */
5557 	dst_dsq = find_dsq_for_dispatch(sch, this_rq, dsq_id, p);
5558 
5559 	/*
5560 	 * Apply vtime and slice updates before moving so that the new time is
5561 	 * visible before inserting into $dst_dsq. @p is still on $src_dsq but
5562 	 * this is safe as we're locking it.
5563 	 */
5564 	if (kit->cursor.flags & __SCX_DSQ_ITER_HAS_VTIME)
5565 		p->scx.dsq_vtime = kit->vtime;
5566 	if (kit->cursor.flags & __SCX_DSQ_ITER_HAS_SLICE)
5567 		p->scx.slice = kit->slice;
5568 
5569 	/* execute move */
5570 	locked_rq = move_task_between_dsqs(sch, p, enq_flags, src_dsq, dst_dsq);
5571 	dispatched = true;
5572 out:
5573 	if (in_balance) {
5574 		if (this_rq != locked_rq) {
5575 			raw_spin_rq_unlock(locked_rq);
5576 			raw_spin_rq_lock(this_rq);
5577 		}
5578 	} else {
5579 		raw_spin_rq_unlock_irqrestore(locked_rq, flags);
5580 	}
5581 
5582 	kit->cursor.flags &= ~(__SCX_DSQ_ITER_HAS_SLICE |
5583 			       __SCX_DSQ_ITER_HAS_VTIME);
5584 	return dispatched;
5585 }
5586 
5587 __bpf_kfunc_start_defs();
5588 
5589 /**
5590  * scx_bpf_dispatch_nr_slots - Return the number of remaining dispatch slots
5591  *
5592  * Can only be called from ops.dispatch().
5593  */
scx_bpf_dispatch_nr_slots(void)5594 __bpf_kfunc u32 scx_bpf_dispatch_nr_slots(void)
5595 {
5596 	struct scx_sched *sch;
5597 
5598 	guard(rcu)();
5599 
5600 	sch = rcu_dereference(scx_root);
5601 	if (unlikely(!sch))
5602 		return 0;
5603 
5604 	if (!scx_kf_allowed(sch, SCX_KF_DISPATCH))
5605 		return 0;
5606 
5607 	return scx_dsp_max_batch - __this_cpu_read(scx_dsp_ctx->cursor);
5608 }
5609 
5610 /**
5611  * scx_bpf_dispatch_cancel - Cancel the latest dispatch
5612  *
5613  * Cancel the latest dispatch. Can be called multiple times to cancel further
5614  * dispatches. Can only be called from ops.dispatch().
5615  */
scx_bpf_dispatch_cancel(void)5616 __bpf_kfunc void scx_bpf_dispatch_cancel(void)
5617 {
5618 	struct scx_dsp_ctx *dspc = this_cpu_ptr(scx_dsp_ctx);
5619 	struct scx_sched *sch;
5620 
5621 	guard(rcu)();
5622 
5623 	sch = rcu_dereference(scx_root);
5624 	if (unlikely(!sch))
5625 		return;
5626 
5627 	if (!scx_kf_allowed(sch, SCX_KF_DISPATCH))
5628 		return;
5629 
5630 	if (dspc->cursor > 0)
5631 		dspc->cursor--;
5632 	else
5633 		scx_error(sch, "dispatch buffer underflow");
5634 }
5635 
5636 /**
5637  * scx_bpf_dsq_move_to_local - move a task from a DSQ to the current CPU's local DSQ
5638  * @dsq_id: DSQ to move task from
5639  *
5640  * Move a task from the non-local DSQ identified by @dsq_id to the current CPU's
5641  * local DSQ for execution. Can only be called from ops.dispatch().
5642  *
5643  * This function flushes the in-flight dispatches from scx_bpf_dsq_insert()
5644  * before trying to move from the specified DSQ. It may also grab rq locks and
5645  * thus can't be called under any BPF locks.
5646  *
5647  * Returns %true if a task has been moved, %false if there isn't any task to
5648  * move.
5649  */
scx_bpf_dsq_move_to_local(u64 dsq_id)5650 __bpf_kfunc bool scx_bpf_dsq_move_to_local(u64 dsq_id)
5651 {
5652 	struct scx_dsp_ctx *dspc = this_cpu_ptr(scx_dsp_ctx);
5653 	struct scx_dispatch_q *dsq;
5654 	struct scx_sched *sch;
5655 
5656 	guard(rcu)();
5657 
5658 	sch = rcu_dereference(scx_root);
5659 	if (unlikely(!sch))
5660 		return false;
5661 
5662 	if (!scx_kf_allowed(sch, SCX_KF_DISPATCH))
5663 		return false;
5664 
5665 	flush_dispatch_buf(sch, dspc->rq);
5666 
5667 	dsq = find_user_dsq(sch, dsq_id);
5668 	if (unlikely(!dsq)) {
5669 		scx_error(sch, "invalid DSQ ID 0x%016llx", dsq_id);
5670 		return false;
5671 	}
5672 
5673 	if (consume_dispatch_q(sch, dspc->rq, dsq)) {
5674 		/*
5675 		 * A successfully consumed task can be dequeued before it starts
5676 		 * running while the CPU is trying to migrate other dispatched
5677 		 * tasks. Bump nr_tasks to tell balance_scx() to retry on empty
5678 		 * local DSQ.
5679 		 */
5680 		dspc->nr_tasks++;
5681 		return true;
5682 	} else {
5683 		return false;
5684 	}
5685 }
5686 
5687 /**
5688  * scx_bpf_dsq_move_set_slice - Override slice when moving between DSQs
5689  * @it__iter: DSQ iterator in progress
5690  * @slice: duration the moved task can run for in nsecs
5691  *
5692  * Override the slice of the next task that will be moved from @it__iter using
5693  * scx_bpf_dsq_move[_vtime](). If this function is not called, the previous
5694  * slice duration is kept.
5695  */
scx_bpf_dsq_move_set_slice(struct bpf_iter_scx_dsq * it__iter,u64 slice)5696 __bpf_kfunc void scx_bpf_dsq_move_set_slice(struct bpf_iter_scx_dsq *it__iter,
5697 					    u64 slice)
5698 {
5699 	struct bpf_iter_scx_dsq_kern *kit = (void *)it__iter;
5700 
5701 	kit->slice = slice;
5702 	kit->cursor.flags |= __SCX_DSQ_ITER_HAS_SLICE;
5703 }
5704 
5705 /**
5706  * scx_bpf_dsq_move_set_vtime - Override vtime when moving between DSQs
5707  * @it__iter: DSQ iterator in progress
5708  * @vtime: task's ordering inside the vtime-sorted queue of the target DSQ
5709  *
5710  * Override the vtime of the next task that will be moved from @it__iter using
5711  * scx_bpf_dsq_move_vtime(). If this function is not called, the previous slice
5712  * vtime is kept. If scx_bpf_dsq_move() is used to dispatch the next task, the
5713  * override is ignored and cleared.
5714  */
scx_bpf_dsq_move_set_vtime(struct bpf_iter_scx_dsq * it__iter,u64 vtime)5715 __bpf_kfunc void scx_bpf_dsq_move_set_vtime(struct bpf_iter_scx_dsq *it__iter,
5716 					    u64 vtime)
5717 {
5718 	struct bpf_iter_scx_dsq_kern *kit = (void *)it__iter;
5719 
5720 	kit->vtime = vtime;
5721 	kit->cursor.flags |= __SCX_DSQ_ITER_HAS_VTIME;
5722 }
5723 
5724 /**
5725  * scx_bpf_dsq_move - Move a task from DSQ iteration to a DSQ
5726  * @it__iter: DSQ iterator in progress
5727  * @p: task to transfer
5728  * @dsq_id: DSQ to move @p to
5729  * @enq_flags: SCX_ENQ_*
5730  *
5731  * Transfer @p which is on the DSQ currently iterated by @it__iter to the DSQ
5732  * specified by @dsq_id. All DSQs - local DSQs, global DSQ and user DSQs - can
5733  * be the destination.
5734  *
5735  * For the transfer to be successful, @p must still be on the DSQ and have been
5736  * queued before the DSQ iteration started. This function doesn't care whether
5737  * @p was obtained from the DSQ iteration. @p just has to be on the DSQ and have
5738  * been queued before the iteration started.
5739  *
5740  * @p's slice is kept by default. Use scx_bpf_dsq_move_set_slice() to update.
5741  *
5742  * Can be called from ops.dispatch() or any BPF context which doesn't hold a rq
5743  * lock (e.g. BPF timers or SYSCALL programs).
5744  *
5745  * Returns %true if @p has been consumed, %false if @p had already been consumed
5746  * or dequeued.
5747  */
scx_bpf_dsq_move(struct bpf_iter_scx_dsq * it__iter,struct task_struct * p,u64 dsq_id,u64 enq_flags)5748 __bpf_kfunc bool scx_bpf_dsq_move(struct bpf_iter_scx_dsq *it__iter,
5749 				  struct task_struct *p, u64 dsq_id,
5750 				  u64 enq_flags)
5751 {
5752 	return scx_dsq_move((struct bpf_iter_scx_dsq_kern *)it__iter,
5753 			    p, dsq_id, enq_flags);
5754 }
5755 
5756 /**
5757  * scx_bpf_dsq_move_vtime - Move a task from DSQ iteration to a PRIQ DSQ
5758  * @it__iter: DSQ iterator in progress
5759  * @p: task to transfer
5760  * @dsq_id: DSQ to move @p to
5761  * @enq_flags: SCX_ENQ_*
5762  *
5763  * Transfer @p which is on the DSQ currently iterated by @it__iter to the
5764  * priority queue of the DSQ specified by @dsq_id. The destination must be a
5765  * user DSQ as only user DSQs support priority queue.
5766  *
5767  * @p's slice and vtime are kept by default. Use scx_bpf_dsq_move_set_slice()
5768  * and scx_bpf_dsq_move_set_vtime() to update.
5769  *
5770  * All other aspects are identical to scx_bpf_dsq_move(). See
5771  * scx_bpf_dsq_insert_vtime() for more information on @vtime.
5772  */
scx_bpf_dsq_move_vtime(struct bpf_iter_scx_dsq * it__iter,struct task_struct * p,u64 dsq_id,u64 enq_flags)5773 __bpf_kfunc bool scx_bpf_dsq_move_vtime(struct bpf_iter_scx_dsq *it__iter,
5774 					struct task_struct *p, u64 dsq_id,
5775 					u64 enq_flags)
5776 {
5777 	return scx_dsq_move((struct bpf_iter_scx_dsq_kern *)it__iter,
5778 			    p, dsq_id, enq_flags | SCX_ENQ_DSQ_PRIQ);
5779 }
5780 
5781 __bpf_kfunc_end_defs();
5782 
5783 BTF_KFUNCS_START(scx_kfunc_ids_dispatch)
5784 BTF_ID_FLAGS(func, scx_bpf_dispatch_nr_slots)
5785 BTF_ID_FLAGS(func, scx_bpf_dispatch_cancel)
5786 BTF_ID_FLAGS(func, scx_bpf_dsq_move_to_local)
5787 BTF_ID_FLAGS(func, scx_bpf_dsq_move_set_slice, KF_RCU)
5788 BTF_ID_FLAGS(func, scx_bpf_dsq_move_set_vtime, KF_RCU)
5789 BTF_ID_FLAGS(func, scx_bpf_dsq_move, KF_RCU)
5790 BTF_ID_FLAGS(func, scx_bpf_dsq_move_vtime, KF_RCU)
5791 BTF_KFUNCS_END(scx_kfunc_ids_dispatch)
5792 
5793 static const struct btf_kfunc_id_set scx_kfunc_set_dispatch = {
5794 	.owner			= THIS_MODULE,
5795 	.set			= &scx_kfunc_ids_dispatch,
5796 };
5797 
5798 __bpf_kfunc_start_defs();
5799 
5800 /**
5801  * scx_bpf_reenqueue_local - Re-enqueue tasks on a local DSQ
5802  *
5803  * Iterate over all of the tasks currently enqueued on the local DSQ of the
5804  * caller's CPU, and re-enqueue them in the BPF scheduler. Returns the number of
5805  * processed tasks. Can only be called from ops.cpu_release().
5806  */
scx_bpf_reenqueue_local(void)5807 __bpf_kfunc u32 scx_bpf_reenqueue_local(void)
5808 {
5809 	struct scx_sched *sch;
5810 	LIST_HEAD(tasks);
5811 	u32 nr_enqueued = 0;
5812 	struct rq *rq;
5813 	struct task_struct *p, *n;
5814 
5815 	guard(rcu)();
5816 	sch = rcu_dereference(scx_root);
5817 	if (unlikely(!sch))
5818 		return 0;
5819 
5820 	if (!scx_kf_allowed(sch, SCX_KF_CPU_RELEASE))
5821 		return 0;
5822 
5823 	rq = cpu_rq(smp_processor_id());
5824 	lockdep_assert_rq_held(rq);
5825 
5826 	/*
5827 	 * The BPF scheduler may choose to dispatch tasks back to
5828 	 * @rq->scx.local_dsq. Move all candidate tasks off to a private list
5829 	 * first to avoid processing the same tasks repeatedly.
5830 	 */
5831 	list_for_each_entry_safe(p, n, &rq->scx.local_dsq.list,
5832 				 scx.dsq_list.node) {
5833 		/*
5834 		 * If @p is being migrated, @p's current CPU may not agree with
5835 		 * its allowed CPUs and the migration_cpu_stop is about to
5836 		 * deactivate and re-activate @p anyway. Skip re-enqueueing.
5837 		 *
5838 		 * While racing sched property changes may also dequeue and
5839 		 * re-enqueue a migrating task while its current CPU and allowed
5840 		 * CPUs disagree, they use %ENQUEUE_RESTORE which is bypassed to
5841 		 * the current local DSQ for running tasks and thus are not
5842 		 * visible to the BPF scheduler.
5843 		 */
5844 		if (p->migration_pending)
5845 			continue;
5846 
5847 		dispatch_dequeue(rq, p);
5848 		list_add_tail(&p->scx.dsq_list.node, &tasks);
5849 	}
5850 
5851 	list_for_each_entry_safe(p, n, &tasks, scx.dsq_list.node) {
5852 		list_del_init(&p->scx.dsq_list.node);
5853 		do_enqueue_task(rq, p, SCX_ENQ_REENQ, -1);
5854 		nr_enqueued++;
5855 	}
5856 
5857 	return nr_enqueued;
5858 }
5859 
5860 __bpf_kfunc_end_defs();
5861 
5862 BTF_KFUNCS_START(scx_kfunc_ids_cpu_release)
5863 BTF_ID_FLAGS(func, scx_bpf_reenqueue_local)
5864 BTF_KFUNCS_END(scx_kfunc_ids_cpu_release)
5865 
5866 static const struct btf_kfunc_id_set scx_kfunc_set_cpu_release = {
5867 	.owner			= THIS_MODULE,
5868 	.set			= &scx_kfunc_ids_cpu_release,
5869 };
5870 
5871 __bpf_kfunc_start_defs();
5872 
5873 /**
5874  * scx_bpf_create_dsq - Create a custom DSQ
5875  * @dsq_id: DSQ to create
5876  * @node: NUMA node to allocate from
5877  *
5878  * Create a custom DSQ identified by @dsq_id. Can be called from any sleepable
5879  * scx callback, and any BPF_PROG_TYPE_SYSCALL prog.
5880  */
scx_bpf_create_dsq(u64 dsq_id,s32 node)5881 __bpf_kfunc s32 scx_bpf_create_dsq(u64 dsq_id, s32 node)
5882 {
5883 	struct scx_dispatch_q *dsq;
5884 	struct scx_sched *sch;
5885 	s32 ret;
5886 
5887 	if (unlikely(node >= (int)nr_node_ids ||
5888 		     (node < 0 && node != NUMA_NO_NODE)))
5889 		return -EINVAL;
5890 
5891 	if (unlikely(dsq_id & SCX_DSQ_FLAG_BUILTIN))
5892 		return -EINVAL;
5893 
5894 	dsq = kmalloc_node(sizeof(*dsq), GFP_KERNEL, node);
5895 	if (!dsq)
5896 		return -ENOMEM;
5897 
5898 	init_dsq(dsq, dsq_id);
5899 
5900 	rcu_read_lock();
5901 
5902 	sch = rcu_dereference(scx_root);
5903 	if (sch)
5904 		ret = rhashtable_lookup_insert_fast(&sch->dsq_hash, &dsq->hash_node,
5905 						    dsq_hash_params);
5906 	else
5907 		ret = -ENODEV;
5908 
5909 	rcu_read_unlock();
5910 	if (ret)
5911 		kfree(dsq);
5912 	return ret;
5913 }
5914 
5915 __bpf_kfunc_end_defs();
5916 
5917 BTF_KFUNCS_START(scx_kfunc_ids_unlocked)
5918 BTF_ID_FLAGS(func, scx_bpf_create_dsq, KF_SLEEPABLE)
5919 BTF_ID_FLAGS(func, scx_bpf_dsq_move_set_slice, KF_RCU)
5920 BTF_ID_FLAGS(func, scx_bpf_dsq_move_set_vtime, KF_RCU)
5921 BTF_ID_FLAGS(func, scx_bpf_dsq_move, KF_RCU)
5922 BTF_ID_FLAGS(func, scx_bpf_dsq_move_vtime, KF_RCU)
5923 BTF_KFUNCS_END(scx_kfunc_ids_unlocked)
5924 
5925 static const struct btf_kfunc_id_set scx_kfunc_set_unlocked = {
5926 	.owner			= THIS_MODULE,
5927 	.set			= &scx_kfunc_ids_unlocked,
5928 };
5929 
5930 __bpf_kfunc_start_defs();
5931 
scx_kick_cpu(struct scx_sched * sch,s32 cpu,u64 flags)5932 static void scx_kick_cpu(struct scx_sched *sch, s32 cpu, u64 flags)
5933 {
5934 	struct rq *this_rq;
5935 	unsigned long irq_flags;
5936 
5937 	if (!ops_cpu_valid(sch, cpu, NULL))
5938 		return;
5939 
5940 	local_irq_save(irq_flags);
5941 
5942 	this_rq = this_rq();
5943 
5944 	/*
5945 	 * While bypassing for PM ops, IRQ handling may not be online which can
5946 	 * lead to irq_work_queue() malfunction such as infinite busy wait for
5947 	 * IRQ status update. Suppress kicking.
5948 	 */
5949 	if (scx_rq_bypassing(this_rq))
5950 		goto out;
5951 
5952 	/*
5953 	 * Actual kicking is bounced to kick_cpus_irq_workfn() to avoid nesting
5954 	 * rq locks. We can probably be smarter and avoid bouncing if called
5955 	 * from ops which don't hold a rq lock.
5956 	 */
5957 	if (flags & SCX_KICK_IDLE) {
5958 		struct rq *target_rq = cpu_rq(cpu);
5959 
5960 		if (unlikely(flags & (SCX_KICK_PREEMPT | SCX_KICK_WAIT)))
5961 			scx_error(sch, "PREEMPT/WAIT cannot be used with SCX_KICK_IDLE");
5962 
5963 		if (raw_spin_rq_trylock(target_rq)) {
5964 			if (can_skip_idle_kick(target_rq)) {
5965 				raw_spin_rq_unlock(target_rq);
5966 				goto out;
5967 			}
5968 			raw_spin_rq_unlock(target_rq);
5969 		}
5970 		cpumask_set_cpu(cpu, this_rq->scx.cpus_to_kick_if_idle);
5971 	} else {
5972 		cpumask_set_cpu(cpu, this_rq->scx.cpus_to_kick);
5973 
5974 		if (flags & SCX_KICK_PREEMPT)
5975 			cpumask_set_cpu(cpu, this_rq->scx.cpus_to_preempt);
5976 		if (flags & SCX_KICK_WAIT)
5977 			cpumask_set_cpu(cpu, this_rq->scx.cpus_to_wait);
5978 	}
5979 
5980 	irq_work_queue(&this_rq->scx.kick_cpus_irq_work);
5981 out:
5982 	local_irq_restore(irq_flags);
5983 }
5984 
5985 /**
5986  * scx_bpf_kick_cpu - Trigger reschedule on a CPU
5987  * @cpu: cpu to kick
5988  * @flags: %SCX_KICK_* flags
5989  *
5990  * Kick @cpu into rescheduling. This can be used to wake up an idle CPU or
5991  * trigger rescheduling on a busy CPU. This can be called from any online
5992  * scx_ops operation and the actual kicking is performed asynchronously through
5993  * an irq work.
5994  */
scx_bpf_kick_cpu(s32 cpu,u64 flags)5995 __bpf_kfunc void scx_bpf_kick_cpu(s32 cpu, u64 flags)
5996 {
5997 	struct scx_sched *sch;
5998 
5999 	guard(rcu)();
6000 	sch = rcu_dereference(scx_root);
6001 	if (likely(sch))
6002 		scx_kick_cpu(sch, cpu, flags);
6003 }
6004 
6005 /**
6006  * scx_bpf_dsq_nr_queued - Return the number of queued tasks
6007  * @dsq_id: id of the DSQ
6008  *
6009  * Return the number of tasks in the DSQ matching @dsq_id. If not found,
6010  * -%ENOENT is returned.
6011  */
scx_bpf_dsq_nr_queued(u64 dsq_id)6012 __bpf_kfunc s32 scx_bpf_dsq_nr_queued(u64 dsq_id)
6013 {
6014 	struct scx_sched *sch;
6015 	struct scx_dispatch_q *dsq;
6016 	s32 ret;
6017 
6018 	preempt_disable();
6019 
6020 	sch = rcu_dereference_sched(scx_root);
6021 	if (unlikely(!sch)) {
6022 		ret = -ENODEV;
6023 		goto out;
6024 	}
6025 
6026 	if (dsq_id == SCX_DSQ_LOCAL) {
6027 		ret = READ_ONCE(this_rq()->scx.local_dsq.nr);
6028 		goto out;
6029 	} else if ((dsq_id & SCX_DSQ_LOCAL_ON) == SCX_DSQ_LOCAL_ON) {
6030 		s32 cpu = dsq_id & SCX_DSQ_LOCAL_CPU_MASK;
6031 
6032 		if (ops_cpu_valid(sch, cpu, NULL)) {
6033 			ret = READ_ONCE(cpu_rq(cpu)->scx.local_dsq.nr);
6034 			goto out;
6035 		}
6036 	} else {
6037 		dsq = find_user_dsq(sch, dsq_id);
6038 		if (dsq) {
6039 			ret = READ_ONCE(dsq->nr);
6040 			goto out;
6041 		}
6042 	}
6043 	ret = -ENOENT;
6044 out:
6045 	preempt_enable();
6046 	return ret;
6047 }
6048 
6049 /**
6050  * scx_bpf_destroy_dsq - Destroy a custom DSQ
6051  * @dsq_id: DSQ to destroy
6052  *
6053  * Destroy the custom DSQ identified by @dsq_id. Only DSQs created with
6054  * scx_bpf_create_dsq() can be destroyed. The caller must ensure that the DSQ is
6055  * empty and no further tasks are dispatched to it. Ignored if called on a DSQ
6056  * which doesn't exist. Can be called from any online scx_ops operations.
6057  */
scx_bpf_destroy_dsq(u64 dsq_id)6058 __bpf_kfunc void scx_bpf_destroy_dsq(u64 dsq_id)
6059 {
6060 	struct scx_sched *sch;
6061 
6062 	rcu_read_lock();
6063 	sch = rcu_dereference(scx_root);
6064 	if (sch)
6065 		destroy_dsq(sch, dsq_id);
6066 	rcu_read_unlock();
6067 }
6068 
6069 /**
6070  * bpf_iter_scx_dsq_new - Create a DSQ iterator
6071  * @it: iterator to initialize
6072  * @dsq_id: DSQ to iterate
6073  * @flags: %SCX_DSQ_ITER_*
6074  *
6075  * Initialize BPF iterator @it which can be used with bpf_for_each() to walk
6076  * tasks in the DSQ specified by @dsq_id. Iteration using @it only includes
6077  * tasks which are already queued when this function is invoked.
6078  */
bpf_iter_scx_dsq_new(struct bpf_iter_scx_dsq * it,u64 dsq_id,u64 flags)6079 __bpf_kfunc int bpf_iter_scx_dsq_new(struct bpf_iter_scx_dsq *it, u64 dsq_id,
6080 				     u64 flags)
6081 {
6082 	struct bpf_iter_scx_dsq_kern *kit = (void *)it;
6083 	struct scx_sched *sch;
6084 
6085 	BUILD_BUG_ON(sizeof(struct bpf_iter_scx_dsq_kern) >
6086 		     sizeof(struct bpf_iter_scx_dsq));
6087 	BUILD_BUG_ON(__alignof__(struct bpf_iter_scx_dsq_kern) !=
6088 		     __alignof__(struct bpf_iter_scx_dsq));
6089 
6090 	/*
6091 	 * next() and destroy() will be called regardless of the return value.
6092 	 * Always clear $kit->dsq.
6093 	 */
6094 	kit->dsq = NULL;
6095 
6096 	sch = rcu_dereference_check(scx_root, rcu_read_lock_bh_held());
6097 	if (unlikely(!sch))
6098 		return -ENODEV;
6099 
6100 	if (flags & ~__SCX_DSQ_ITER_USER_FLAGS)
6101 		return -EINVAL;
6102 
6103 	kit->dsq = find_user_dsq(sch, dsq_id);
6104 	if (!kit->dsq)
6105 		return -ENOENT;
6106 
6107 	INIT_LIST_HEAD(&kit->cursor.node);
6108 	kit->cursor.flags = SCX_DSQ_LNODE_ITER_CURSOR | flags;
6109 	kit->cursor.priv = READ_ONCE(kit->dsq->seq);
6110 
6111 	return 0;
6112 }
6113 
6114 /**
6115  * bpf_iter_scx_dsq_next - Progress a DSQ iterator
6116  * @it: iterator to progress
6117  *
6118  * Return the next task. See bpf_iter_scx_dsq_new().
6119  */
bpf_iter_scx_dsq_next(struct bpf_iter_scx_dsq * it)6120 __bpf_kfunc struct task_struct *bpf_iter_scx_dsq_next(struct bpf_iter_scx_dsq *it)
6121 {
6122 	struct bpf_iter_scx_dsq_kern *kit = (void *)it;
6123 	bool rev = kit->cursor.flags & SCX_DSQ_ITER_REV;
6124 	struct task_struct *p;
6125 	unsigned long flags;
6126 
6127 	if (!kit->dsq)
6128 		return NULL;
6129 
6130 	raw_spin_lock_irqsave(&kit->dsq->lock, flags);
6131 
6132 	if (list_empty(&kit->cursor.node))
6133 		p = NULL;
6134 	else
6135 		p = container_of(&kit->cursor, struct task_struct, scx.dsq_list);
6136 
6137 	/*
6138 	 * Only tasks which were queued before the iteration started are
6139 	 * visible. This bounds BPF iterations and guarantees that vtime never
6140 	 * jumps in the other direction while iterating.
6141 	 */
6142 	do {
6143 		p = nldsq_next_task(kit->dsq, p, rev);
6144 	} while (p && unlikely(u32_before(kit->cursor.priv, p->scx.dsq_seq)));
6145 
6146 	if (p) {
6147 		if (rev)
6148 			list_move_tail(&kit->cursor.node, &p->scx.dsq_list.node);
6149 		else
6150 			list_move(&kit->cursor.node, &p->scx.dsq_list.node);
6151 	} else {
6152 		list_del_init(&kit->cursor.node);
6153 	}
6154 
6155 	raw_spin_unlock_irqrestore(&kit->dsq->lock, flags);
6156 
6157 	return p;
6158 }
6159 
6160 /**
6161  * bpf_iter_scx_dsq_destroy - Destroy a DSQ iterator
6162  * @it: iterator to destroy
6163  *
6164  * Undo scx_iter_scx_dsq_new().
6165  */
bpf_iter_scx_dsq_destroy(struct bpf_iter_scx_dsq * it)6166 __bpf_kfunc void bpf_iter_scx_dsq_destroy(struct bpf_iter_scx_dsq *it)
6167 {
6168 	struct bpf_iter_scx_dsq_kern *kit = (void *)it;
6169 
6170 	if (!kit->dsq)
6171 		return;
6172 
6173 	if (!list_empty(&kit->cursor.node)) {
6174 		unsigned long flags;
6175 
6176 		raw_spin_lock_irqsave(&kit->dsq->lock, flags);
6177 		list_del_init(&kit->cursor.node);
6178 		raw_spin_unlock_irqrestore(&kit->dsq->lock, flags);
6179 	}
6180 	kit->dsq = NULL;
6181 }
6182 
6183 __bpf_kfunc_end_defs();
6184 
__bstr_format(struct scx_sched * sch,u64 * data_buf,char * line_buf,size_t line_size,char * fmt,unsigned long long * data,u32 data__sz)6185 static s32 __bstr_format(struct scx_sched *sch, u64 *data_buf, char *line_buf,
6186 			 size_t line_size, char *fmt, unsigned long long *data,
6187 			 u32 data__sz)
6188 {
6189 	struct bpf_bprintf_data bprintf_data = { .get_bin_args = true };
6190 	s32 ret;
6191 
6192 	if (data__sz % 8 || data__sz > MAX_BPRINTF_VARARGS * 8 ||
6193 	    (data__sz && !data)) {
6194 		scx_error(sch, "invalid data=%p and data__sz=%u", (void *)data, data__sz);
6195 		return -EINVAL;
6196 	}
6197 
6198 	ret = copy_from_kernel_nofault(data_buf, data, data__sz);
6199 	if (ret < 0) {
6200 		scx_error(sch, "failed to read data fields (%d)", ret);
6201 		return ret;
6202 	}
6203 
6204 	ret = bpf_bprintf_prepare(fmt, UINT_MAX, data_buf, data__sz / 8,
6205 				  &bprintf_data);
6206 	if (ret < 0) {
6207 		scx_error(sch, "format preparation failed (%d)", ret);
6208 		return ret;
6209 	}
6210 
6211 	ret = bstr_printf(line_buf, line_size, fmt,
6212 			  bprintf_data.bin_args);
6213 	bpf_bprintf_cleanup(&bprintf_data);
6214 	if (ret < 0) {
6215 		scx_error(sch, "(\"%s\", %p, %u) failed to format", fmt, data, data__sz);
6216 		return ret;
6217 	}
6218 
6219 	return ret;
6220 }
6221 
bstr_format(struct scx_sched * sch,struct scx_bstr_buf * buf,char * fmt,unsigned long long * data,u32 data__sz)6222 static s32 bstr_format(struct scx_sched *sch, struct scx_bstr_buf *buf,
6223 		       char *fmt, unsigned long long *data, u32 data__sz)
6224 {
6225 	return __bstr_format(sch, buf->data, buf->line, sizeof(buf->line),
6226 			     fmt, data, data__sz);
6227 }
6228 
6229 __bpf_kfunc_start_defs();
6230 
6231 /**
6232  * scx_bpf_exit_bstr - Gracefully exit the BPF scheduler.
6233  * @exit_code: Exit value to pass to user space via struct scx_exit_info.
6234  * @fmt: error message format string
6235  * @data: format string parameters packaged using ___bpf_fill() macro
6236  * @data__sz: @data len, must end in '__sz' for the verifier
6237  *
6238  * Indicate that the BPF scheduler wants to exit gracefully, and initiate ops
6239  * disabling.
6240  */
scx_bpf_exit_bstr(s64 exit_code,char * fmt,unsigned long long * data,u32 data__sz)6241 __bpf_kfunc void scx_bpf_exit_bstr(s64 exit_code, char *fmt,
6242 				   unsigned long long *data, u32 data__sz)
6243 {
6244 	struct scx_sched *sch;
6245 	unsigned long flags;
6246 
6247 	raw_spin_lock_irqsave(&scx_exit_bstr_buf_lock, flags);
6248 	sch = rcu_dereference_bh(scx_root);
6249 	if (likely(sch) &&
6250 	    bstr_format(sch, &scx_exit_bstr_buf, fmt, data, data__sz) >= 0)
6251 		scx_exit(sch, SCX_EXIT_UNREG_BPF, exit_code, "%s", scx_exit_bstr_buf.line);
6252 	raw_spin_unlock_irqrestore(&scx_exit_bstr_buf_lock, flags);
6253 }
6254 
6255 /**
6256  * scx_bpf_error_bstr - Indicate fatal error
6257  * @fmt: error message format string
6258  * @data: format string parameters packaged using ___bpf_fill() macro
6259  * @data__sz: @data len, must end in '__sz' for the verifier
6260  *
6261  * Indicate that the BPF scheduler encountered a fatal error and initiate ops
6262  * disabling.
6263  */
scx_bpf_error_bstr(char * fmt,unsigned long long * data,u32 data__sz)6264 __bpf_kfunc void scx_bpf_error_bstr(char *fmt, unsigned long long *data,
6265 				    u32 data__sz)
6266 {
6267 	struct scx_sched *sch;
6268 	unsigned long flags;
6269 
6270 	raw_spin_lock_irqsave(&scx_exit_bstr_buf_lock, flags);
6271 	sch = rcu_dereference_bh(scx_root);
6272 	if (likely(sch) &&
6273 	    bstr_format(sch, &scx_exit_bstr_buf, fmt, data, data__sz) >= 0)
6274 		scx_exit(sch, SCX_EXIT_ERROR_BPF, 0, "%s", scx_exit_bstr_buf.line);
6275 	raw_spin_unlock_irqrestore(&scx_exit_bstr_buf_lock, flags);
6276 }
6277 
6278 /**
6279  * scx_bpf_dump_bstr - Generate extra debug dump specific to the BPF scheduler
6280  * @fmt: format string
6281  * @data: format string parameters packaged using ___bpf_fill() macro
6282  * @data__sz: @data len, must end in '__sz' for the verifier
6283  *
6284  * To be called through scx_bpf_dump() helper from ops.dump(), dump_cpu() and
6285  * dump_task() to generate extra debug dump specific to the BPF scheduler.
6286  *
6287  * The extra dump may be multiple lines. A single line may be split over
6288  * multiple calls. The last line is automatically terminated.
6289  */
scx_bpf_dump_bstr(char * fmt,unsigned long long * data,u32 data__sz)6290 __bpf_kfunc void scx_bpf_dump_bstr(char *fmt, unsigned long long *data,
6291 				   u32 data__sz)
6292 {
6293 	struct scx_sched *sch;
6294 	struct scx_dump_data *dd = &scx_dump_data;
6295 	struct scx_bstr_buf *buf = &dd->buf;
6296 	s32 ret;
6297 
6298 	guard(rcu)();
6299 
6300 	sch = rcu_dereference(scx_root);
6301 	if (unlikely(!sch))
6302 		return;
6303 
6304 	if (raw_smp_processor_id() != dd->cpu) {
6305 		scx_error(sch, "scx_bpf_dump() must only be called from ops.dump() and friends");
6306 		return;
6307 	}
6308 
6309 	/* append the formatted string to the line buf */
6310 	ret = __bstr_format(sch, buf->data, buf->line + dd->cursor,
6311 			    sizeof(buf->line) - dd->cursor, fmt, data, data__sz);
6312 	if (ret < 0) {
6313 		dump_line(dd->s, "%s[!] (\"%s\", %p, %u) failed to format (%d)",
6314 			  dd->prefix, fmt, data, data__sz, ret);
6315 		return;
6316 	}
6317 
6318 	dd->cursor += ret;
6319 	dd->cursor = min_t(s32, dd->cursor, sizeof(buf->line));
6320 
6321 	if (!dd->cursor)
6322 		return;
6323 
6324 	/*
6325 	 * If the line buf overflowed or ends in a newline, flush it into the
6326 	 * dump. This is to allow the caller to generate a single line over
6327 	 * multiple calls. As ops_dump_flush() can also handle multiple lines in
6328 	 * the line buf, the only case which can lead to an unexpected
6329 	 * truncation is when the caller keeps generating newlines in the middle
6330 	 * instead of the end consecutively. Don't do that.
6331 	 */
6332 	if (dd->cursor >= sizeof(buf->line) || buf->line[dd->cursor - 1] == '\n')
6333 		ops_dump_flush();
6334 }
6335 
6336 /**
6337  * scx_bpf_cpuperf_cap - Query the maximum relative capacity of a CPU
6338  * @cpu: CPU of interest
6339  *
6340  * Return the maximum relative capacity of @cpu in relation to the most
6341  * performant CPU in the system. The return value is in the range [1,
6342  * %SCX_CPUPERF_ONE]. See scx_bpf_cpuperf_cur().
6343  */
scx_bpf_cpuperf_cap(s32 cpu)6344 __bpf_kfunc u32 scx_bpf_cpuperf_cap(s32 cpu)
6345 {
6346 	struct scx_sched *sch;
6347 
6348 	guard(rcu)();
6349 
6350 	sch = rcu_dereference(scx_root);
6351 	if (likely(sch) && ops_cpu_valid(sch, cpu, NULL))
6352 		return arch_scale_cpu_capacity(cpu);
6353 	else
6354 		return SCX_CPUPERF_ONE;
6355 }
6356 
6357 /**
6358  * scx_bpf_cpuperf_cur - Query the current relative performance of a CPU
6359  * @cpu: CPU of interest
6360  *
6361  * Return the current relative performance of @cpu in relation to its maximum.
6362  * The return value is in the range [1, %SCX_CPUPERF_ONE].
6363  *
6364  * The current performance level of a CPU in relation to the maximum performance
6365  * available in the system can be calculated as follows:
6366  *
6367  *   scx_bpf_cpuperf_cap() * scx_bpf_cpuperf_cur() / %SCX_CPUPERF_ONE
6368  *
6369  * The result is in the range [1, %SCX_CPUPERF_ONE].
6370  */
scx_bpf_cpuperf_cur(s32 cpu)6371 __bpf_kfunc u32 scx_bpf_cpuperf_cur(s32 cpu)
6372 {
6373 	struct scx_sched *sch;
6374 
6375 	guard(rcu)();
6376 
6377 	sch = rcu_dereference(scx_root);
6378 	if (likely(sch) && ops_cpu_valid(sch, cpu, NULL))
6379 		return arch_scale_freq_capacity(cpu);
6380 	else
6381 		return SCX_CPUPERF_ONE;
6382 }
6383 
6384 /**
6385  * scx_bpf_cpuperf_set - Set the relative performance target of a CPU
6386  * @cpu: CPU of interest
6387  * @perf: target performance level [0, %SCX_CPUPERF_ONE]
6388  *
6389  * Set the target performance level of @cpu to @perf. @perf is in linear
6390  * relative scale between 0 and %SCX_CPUPERF_ONE. This determines how the
6391  * schedutil cpufreq governor chooses the target frequency.
6392  *
6393  * The actual performance level chosen, CPU grouping, and the overhead and
6394  * latency of the operations are dependent on the hardware and cpufreq driver in
6395  * use. Consult hardware and cpufreq documentation for more information. The
6396  * current performance level can be monitored using scx_bpf_cpuperf_cur().
6397  */
scx_bpf_cpuperf_set(s32 cpu,u32 perf)6398 __bpf_kfunc void scx_bpf_cpuperf_set(s32 cpu, u32 perf)
6399 {
6400 	struct scx_sched *sch;
6401 
6402 	guard(rcu)();
6403 
6404 	sch = rcu_dereference(sch);
6405 	if (unlikely(!sch))
6406 		return;
6407 
6408 	if (unlikely(perf > SCX_CPUPERF_ONE)) {
6409 		scx_error(sch, "Invalid cpuperf target %u for CPU %d", perf, cpu);
6410 		return;
6411 	}
6412 
6413 	if (ops_cpu_valid(sch, cpu, NULL)) {
6414 		struct rq *rq = cpu_rq(cpu), *locked_rq = scx_locked_rq();
6415 		struct rq_flags rf;
6416 
6417 		/*
6418 		 * When called with an rq lock held, restrict the operation
6419 		 * to the corresponding CPU to prevent ABBA deadlocks.
6420 		 */
6421 		if (locked_rq && rq != locked_rq) {
6422 			scx_error(sch, "Invalid target CPU %d", cpu);
6423 			return;
6424 		}
6425 
6426 		/*
6427 		 * If no rq lock is held, allow to operate on any CPU by
6428 		 * acquiring the corresponding rq lock.
6429 		 */
6430 		if (!locked_rq) {
6431 			rq_lock_irqsave(rq, &rf);
6432 			update_rq_clock(rq);
6433 		}
6434 
6435 		rq->scx.cpuperf_target = perf;
6436 		cpufreq_update_util(rq, 0);
6437 
6438 		if (!locked_rq)
6439 			rq_unlock_irqrestore(rq, &rf);
6440 	}
6441 }
6442 
6443 /**
6444  * scx_bpf_nr_node_ids - Return the number of possible node IDs
6445  *
6446  * All valid node IDs in the system are smaller than the returned value.
6447  */
scx_bpf_nr_node_ids(void)6448 __bpf_kfunc u32 scx_bpf_nr_node_ids(void)
6449 {
6450 	return nr_node_ids;
6451 }
6452 
6453 /**
6454  * scx_bpf_nr_cpu_ids - Return the number of possible CPU IDs
6455  *
6456  * All valid CPU IDs in the system are smaller than the returned value.
6457  */
scx_bpf_nr_cpu_ids(void)6458 __bpf_kfunc u32 scx_bpf_nr_cpu_ids(void)
6459 {
6460 	return nr_cpu_ids;
6461 }
6462 
6463 /**
6464  * scx_bpf_get_possible_cpumask - Get a referenced kptr to cpu_possible_mask
6465  */
scx_bpf_get_possible_cpumask(void)6466 __bpf_kfunc const struct cpumask *scx_bpf_get_possible_cpumask(void)
6467 {
6468 	return cpu_possible_mask;
6469 }
6470 
6471 /**
6472  * scx_bpf_get_online_cpumask - Get a referenced kptr to cpu_online_mask
6473  */
scx_bpf_get_online_cpumask(void)6474 __bpf_kfunc const struct cpumask *scx_bpf_get_online_cpumask(void)
6475 {
6476 	return cpu_online_mask;
6477 }
6478 
6479 /**
6480  * scx_bpf_put_cpumask - Release a possible/online cpumask
6481  * @cpumask: cpumask to release
6482  */
scx_bpf_put_cpumask(const struct cpumask * cpumask)6483 __bpf_kfunc void scx_bpf_put_cpumask(const struct cpumask *cpumask)
6484 {
6485 	/*
6486 	 * Empty function body because we aren't actually acquiring or releasing
6487 	 * a reference to a global cpumask, which is read-only in the caller and
6488 	 * is never released. The acquire / release semantics here are just used
6489 	 * to make the cpumask is a trusted pointer in the caller.
6490 	 */
6491 }
6492 
6493 /**
6494  * scx_bpf_task_running - Is task currently running?
6495  * @p: task of interest
6496  */
scx_bpf_task_running(const struct task_struct * p)6497 __bpf_kfunc bool scx_bpf_task_running(const struct task_struct *p)
6498 {
6499 	return task_rq(p)->curr == p;
6500 }
6501 
6502 /**
6503  * scx_bpf_task_cpu - CPU a task is currently associated with
6504  * @p: task of interest
6505  */
scx_bpf_task_cpu(const struct task_struct * p)6506 __bpf_kfunc s32 scx_bpf_task_cpu(const struct task_struct *p)
6507 {
6508 	return task_cpu(p);
6509 }
6510 
6511 /**
6512  * scx_bpf_cpu_rq - Fetch the rq of a CPU
6513  * @cpu: CPU of the rq
6514  */
scx_bpf_cpu_rq(s32 cpu)6515 __bpf_kfunc struct rq *scx_bpf_cpu_rq(s32 cpu)
6516 {
6517 	struct scx_sched *sch;
6518 
6519 	guard(rcu)();
6520 
6521 	sch = rcu_dereference(scx_root);
6522 	if (unlikely(!sch))
6523 		return NULL;
6524 
6525 	if (!ops_cpu_valid(sch, cpu, NULL))
6526 		return NULL;
6527 
6528 	if (!sch->warned_deprecated_rq) {
6529 		printk_deferred(KERN_WARNING "sched_ext: %s() is deprecated; "
6530 				"use scx_bpf_locked_rq() when holding rq lock "
6531 				"or scx_bpf_cpu_curr() to read remote curr safely.\n", __func__);
6532 		sch->warned_deprecated_rq = true;
6533 	}
6534 
6535 	return cpu_rq(cpu);
6536 }
6537 
6538 /**
6539  * scx_bpf_locked_rq - Return the rq currently locked by SCX
6540  *
6541  * Returns the rq if a rq lock is currently held by SCX.
6542  * Otherwise emits an error and returns NULL.
6543  */
scx_bpf_locked_rq(void)6544 __bpf_kfunc struct rq *scx_bpf_locked_rq(void)
6545 {
6546 	struct scx_sched *sch;
6547 	struct rq *rq;
6548 
6549 	guard(preempt)();
6550 
6551 	sch = rcu_dereference_sched(scx_root);
6552 	if (unlikely(!sch))
6553 		return NULL;
6554 
6555 	rq = scx_locked_rq();
6556 	if (!rq) {
6557 		scx_error(sch, "accessing rq without holding rq lock");
6558 		return NULL;
6559 	}
6560 
6561 	return rq;
6562 }
6563 
6564 /**
6565  * scx_bpf_cpu_curr - Return remote CPU's curr task
6566  * @cpu: CPU of interest
6567  *
6568  * Callers must hold RCU read lock (KF_RCU).
6569  */
scx_bpf_cpu_curr(s32 cpu)6570 __bpf_kfunc struct task_struct *scx_bpf_cpu_curr(s32 cpu)
6571 {
6572 	struct scx_sched *sch;
6573 
6574 	guard(rcu)();
6575 
6576 	sch = rcu_dereference(scx_root);
6577 	if (unlikely(!sch))
6578 		return NULL;
6579 
6580 	if (!ops_cpu_valid(sch, cpu, NULL))
6581 		return NULL;
6582 
6583 	return rcu_dereference(cpu_rq(cpu)->curr);
6584 }
6585 
6586 /**
6587  * scx_bpf_task_cgroup - Return the sched cgroup of a task
6588  * @p: task of interest
6589  *
6590  * @p->sched_task_group->css.cgroup represents the cgroup @p is associated with
6591  * from the scheduler's POV. SCX operations should use this function to
6592  * determine @p's current cgroup as, unlike following @p->cgroups,
6593  * @p->sched_task_group is protected by @p's rq lock and thus atomic w.r.t. all
6594  * rq-locked operations. Can be called on the parameter tasks of rq-locked
6595  * operations. The restriction guarantees that @p's rq is locked by the caller.
6596  */
6597 #ifdef CONFIG_CGROUP_SCHED
scx_bpf_task_cgroup(struct task_struct * p)6598 __bpf_kfunc struct cgroup *scx_bpf_task_cgroup(struct task_struct *p)
6599 {
6600 	struct task_group *tg = p->sched_task_group;
6601 	struct cgroup *cgrp = &cgrp_dfl_root.cgrp;
6602 	struct scx_sched *sch;
6603 
6604 	guard(rcu)();
6605 
6606 	sch = rcu_dereference(scx_root);
6607 	if (unlikely(!sch))
6608 		goto out;
6609 
6610 	if (!scx_kf_allowed_on_arg_tasks(sch, __SCX_KF_RQ_LOCKED, p))
6611 		goto out;
6612 
6613 	cgrp = tg_cgrp(tg);
6614 
6615 out:
6616 	cgroup_get(cgrp);
6617 	return cgrp;
6618 }
6619 #endif
6620 
6621 /**
6622  * scx_bpf_now - Returns a high-performance monotonically non-decreasing
6623  * clock for the current CPU. The clock returned is in nanoseconds.
6624  *
6625  * It provides the following properties:
6626  *
6627  * 1) High performance: Many BPF schedulers call bpf_ktime_get_ns() frequently
6628  *  to account for execution time and track tasks' runtime properties.
6629  *  Unfortunately, in some hardware platforms, bpf_ktime_get_ns() -- which
6630  *  eventually reads a hardware timestamp counter -- is neither performant nor
6631  *  scalable. scx_bpf_now() aims to provide a high-performance clock by
6632  *  using the rq clock in the scheduler core whenever possible.
6633  *
6634  * 2) High enough resolution for the BPF scheduler use cases: In most BPF
6635  *  scheduler use cases, the required clock resolution is lower than the most
6636  *  accurate hardware clock (e.g., rdtsc in x86). scx_bpf_now() basically
6637  *  uses the rq clock in the scheduler core whenever it is valid. It considers
6638  *  that the rq clock is valid from the time the rq clock is updated
6639  *  (update_rq_clock) until the rq is unlocked (rq_unpin_lock).
6640  *
6641  * 3) Monotonically non-decreasing clock for the same CPU: scx_bpf_now()
6642  *  guarantees the clock never goes backward when comparing them in the same
6643  *  CPU. On the other hand, when comparing clocks in different CPUs, there
6644  *  is no such guarantee -- the clock can go backward. It provides a
6645  *  monotonically *non-decreasing* clock so that it would provide the same
6646  *  clock values in two different scx_bpf_now() calls in the same CPU
6647  *  during the same period of when the rq clock is valid.
6648  */
scx_bpf_now(void)6649 __bpf_kfunc u64 scx_bpf_now(void)
6650 {
6651 	struct rq *rq;
6652 	u64 clock;
6653 
6654 	preempt_disable();
6655 
6656 	rq = this_rq();
6657 	if (smp_load_acquire(&rq->scx.flags) & SCX_RQ_CLK_VALID) {
6658 		/*
6659 		 * If the rq clock is valid, use the cached rq clock.
6660 		 *
6661 		 * Note that scx_bpf_now() is re-entrant between a process
6662 		 * context and an interrupt context (e.g., timer interrupt).
6663 		 * However, we don't need to consider the race between them
6664 		 * because such race is not observable from a caller.
6665 		 */
6666 		clock = READ_ONCE(rq->scx.clock);
6667 	} else {
6668 		/*
6669 		 * Otherwise, return a fresh rq clock.
6670 		 *
6671 		 * The rq clock is updated outside of the rq lock.
6672 		 * In this case, keep the updated rq clock invalid so the next
6673 		 * kfunc call outside the rq lock gets a fresh rq clock.
6674 		 */
6675 		clock = sched_clock_cpu(cpu_of(rq));
6676 	}
6677 
6678 	preempt_enable();
6679 
6680 	return clock;
6681 }
6682 
scx_read_events(struct scx_sched * sch,struct scx_event_stats * events)6683 static void scx_read_events(struct scx_sched *sch, struct scx_event_stats *events)
6684 {
6685 	struct scx_event_stats *e_cpu;
6686 	int cpu;
6687 
6688 	/* Aggregate per-CPU event counters into @events. */
6689 	memset(events, 0, sizeof(*events));
6690 	for_each_possible_cpu(cpu) {
6691 		e_cpu = &per_cpu_ptr(sch->pcpu, cpu)->event_stats;
6692 		scx_agg_event(events, e_cpu, SCX_EV_SELECT_CPU_FALLBACK);
6693 		scx_agg_event(events, e_cpu, SCX_EV_DISPATCH_LOCAL_DSQ_OFFLINE);
6694 		scx_agg_event(events, e_cpu, SCX_EV_DISPATCH_KEEP_LAST);
6695 		scx_agg_event(events, e_cpu, SCX_EV_ENQ_SKIP_EXITING);
6696 		scx_agg_event(events, e_cpu, SCX_EV_ENQ_SKIP_MIGRATION_DISABLED);
6697 		scx_agg_event(events, e_cpu, SCX_EV_REFILL_SLICE_DFL);
6698 		scx_agg_event(events, e_cpu, SCX_EV_BYPASS_DURATION);
6699 		scx_agg_event(events, e_cpu, SCX_EV_BYPASS_DISPATCH);
6700 		scx_agg_event(events, e_cpu, SCX_EV_BYPASS_ACTIVATE);
6701 	}
6702 }
6703 
6704 /*
6705  * scx_bpf_events - Get a system-wide event counter to
6706  * @events: output buffer from a BPF program
6707  * @events__sz: @events len, must end in '__sz'' for the verifier
6708  */
scx_bpf_events(struct scx_event_stats * events,size_t events__sz)6709 __bpf_kfunc void scx_bpf_events(struct scx_event_stats *events,
6710 				size_t events__sz)
6711 {
6712 	struct scx_sched *sch;
6713 	struct scx_event_stats e_sys;
6714 
6715 	rcu_read_lock();
6716 	sch = rcu_dereference(scx_root);
6717 	if (sch)
6718 		scx_read_events(sch, &e_sys);
6719 	else
6720 		memset(&e_sys, 0, sizeof(e_sys));
6721 	rcu_read_unlock();
6722 
6723 	/*
6724 	 * We cannot entirely trust a BPF-provided size since a BPF program
6725 	 * might be compiled against a different vmlinux.h, of which
6726 	 * scx_event_stats would be larger (a newer vmlinux.h) or smaller
6727 	 * (an older vmlinux.h). Hence, we use the smaller size to avoid
6728 	 * memory corruption.
6729 	 */
6730 	events__sz = min(events__sz, sizeof(*events));
6731 	memcpy(events, &e_sys, events__sz);
6732 }
6733 
6734 __bpf_kfunc_end_defs();
6735 
6736 BTF_KFUNCS_START(scx_kfunc_ids_any)
6737 BTF_ID_FLAGS(func, scx_bpf_kick_cpu)
6738 BTF_ID_FLAGS(func, scx_bpf_dsq_nr_queued)
6739 BTF_ID_FLAGS(func, scx_bpf_destroy_dsq)
6740 BTF_ID_FLAGS(func, bpf_iter_scx_dsq_new, KF_ITER_NEW | KF_RCU_PROTECTED)
6741 BTF_ID_FLAGS(func, bpf_iter_scx_dsq_next, KF_ITER_NEXT | KF_RET_NULL)
6742 BTF_ID_FLAGS(func, bpf_iter_scx_dsq_destroy, KF_ITER_DESTROY)
6743 BTF_ID_FLAGS(func, scx_bpf_exit_bstr, KF_TRUSTED_ARGS)
6744 BTF_ID_FLAGS(func, scx_bpf_error_bstr, KF_TRUSTED_ARGS)
6745 BTF_ID_FLAGS(func, scx_bpf_dump_bstr, KF_TRUSTED_ARGS)
6746 BTF_ID_FLAGS(func, scx_bpf_cpuperf_cap)
6747 BTF_ID_FLAGS(func, scx_bpf_cpuperf_cur)
6748 BTF_ID_FLAGS(func, scx_bpf_cpuperf_set)
6749 BTF_ID_FLAGS(func, scx_bpf_nr_node_ids)
6750 BTF_ID_FLAGS(func, scx_bpf_nr_cpu_ids)
6751 BTF_ID_FLAGS(func, scx_bpf_get_possible_cpumask, KF_ACQUIRE)
6752 BTF_ID_FLAGS(func, scx_bpf_get_online_cpumask, KF_ACQUIRE)
6753 BTF_ID_FLAGS(func, scx_bpf_put_cpumask, KF_RELEASE)
6754 BTF_ID_FLAGS(func, scx_bpf_task_running, KF_RCU)
6755 BTF_ID_FLAGS(func, scx_bpf_task_cpu, KF_RCU)
6756 BTF_ID_FLAGS(func, scx_bpf_cpu_rq)
6757 BTF_ID_FLAGS(func, scx_bpf_locked_rq, KF_RET_NULL)
6758 BTF_ID_FLAGS(func, scx_bpf_cpu_curr, KF_RET_NULL | KF_RCU_PROTECTED)
6759 #ifdef CONFIG_CGROUP_SCHED
6760 BTF_ID_FLAGS(func, scx_bpf_task_cgroup, KF_RCU | KF_ACQUIRE)
6761 #endif
6762 BTF_ID_FLAGS(func, scx_bpf_now)
6763 BTF_ID_FLAGS(func, scx_bpf_events, KF_TRUSTED_ARGS)
6764 BTF_KFUNCS_END(scx_kfunc_ids_any)
6765 
6766 static const struct btf_kfunc_id_set scx_kfunc_set_any = {
6767 	.owner			= THIS_MODULE,
6768 	.set			= &scx_kfunc_ids_any,
6769 };
6770 
scx_init(void)6771 static int __init scx_init(void)
6772 {
6773 	int ret;
6774 
6775 	/*
6776 	 * kfunc registration can't be done from init_sched_ext_class() as
6777 	 * register_btf_kfunc_id_set() needs most of the system to be up.
6778 	 *
6779 	 * Some kfuncs are context-sensitive and can only be called from
6780 	 * specific SCX ops. They are grouped into BTF sets accordingly.
6781 	 * Unfortunately, BPF currently doesn't have a way of enforcing such
6782 	 * restrictions. Eventually, the verifier should be able to enforce
6783 	 * them. For now, register them the same and make each kfunc explicitly
6784 	 * check using scx_kf_allowed().
6785 	 */
6786 	if ((ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_STRUCT_OPS,
6787 					     &scx_kfunc_set_enqueue_dispatch)) ||
6788 	    (ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_STRUCT_OPS,
6789 					     &scx_kfunc_set_dispatch)) ||
6790 	    (ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_STRUCT_OPS,
6791 					     &scx_kfunc_set_cpu_release)) ||
6792 	    (ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_STRUCT_OPS,
6793 					     &scx_kfunc_set_unlocked)) ||
6794 	    (ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_SYSCALL,
6795 					     &scx_kfunc_set_unlocked)) ||
6796 	    (ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_STRUCT_OPS,
6797 					     &scx_kfunc_set_any)) ||
6798 	    (ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_TRACING,
6799 					     &scx_kfunc_set_any)) ||
6800 	    (ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_SYSCALL,
6801 					     &scx_kfunc_set_any))) {
6802 		pr_err("sched_ext: Failed to register kfunc sets (%d)\n", ret);
6803 		return ret;
6804 	}
6805 
6806 	ret = scx_idle_init();
6807 	if (ret) {
6808 		pr_err("sched_ext: Failed to initialize idle tracking (%d)\n", ret);
6809 		return ret;
6810 	}
6811 
6812 	ret = register_bpf_struct_ops(&bpf_sched_ext_ops, sched_ext_ops);
6813 	if (ret) {
6814 		pr_err("sched_ext: Failed to register struct_ops (%d)\n", ret);
6815 		return ret;
6816 	}
6817 
6818 	ret = register_pm_notifier(&scx_pm_notifier);
6819 	if (ret) {
6820 		pr_err("sched_ext: Failed to register PM notifier (%d)\n", ret);
6821 		return ret;
6822 	}
6823 
6824 	scx_kset = kset_create_and_add("sched_ext", &scx_uevent_ops, kernel_kobj);
6825 	if (!scx_kset) {
6826 		pr_err("sched_ext: Failed to create /sys/kernel/sched_ext\n");
6827 		return -ENOMEM;
6828 	}
6829 
6830 	ret = sysfs_create_group(&scx_kset->kobj, &scx_global_attr_group);
6831 	if (ret < 0) {
6832 		pr_err("sched_ext: Failed to add global attributes\n");
6833 		return ret;
6834 	}
6835 
6836 	return 0;
6837 }
6838 __initcall(scx_init);
6839