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