1 /* SPDX-License-Identifier: GPL-2.0 */ 2 /* 3 * BPF extensible scheduler class: Documentation/scheduler/sched-ext.rst 4 * 5 * Copyright (c) 2025 Meta Platforms, Inc. and affiliates. 6 * Copyright (c) 2025 Tejun Heo <tj@kernel.org> 7 */ 8 #ifndef _KERNEL_SCHED_EXT_INTERNAL_H 9 #define _KERNEL_SCHED_EXT_INTERNAL_H 10 11 #include "../sched.h" 12 #include "types.h" 13 14 #include <trace/events/sched_ext.h> 15 16 /** 17 * scx_add_event - Increase an event counter for 'name' by 'cnt' 18 * @sch: scx_sched to account events for 19 * @name: an event name defined in struct scx_event_stats 20 * @cnt: the number of the event occurred 21 * 22 * This can be used when preemption is not disabled. 23 */ 24 #define scx_add_event(sch, name, cnt) do { \ 25 this_cpu_add((sch)->pcpu->event_stats.name, (cnt)); \ 26 trace_sched_ext_event(#name, (cnt)); \ 27 } while(0) 28 29 /** 30 * __scx_add_event - Increase an event counter for 'name' by 'cnt' 31 * @sch: scx_sched to account events for 32 * @name: an event name defined in struct scx_event_stats 33 * @cnt: the number of the event occurred 34 * 35 * This should be used only when preemption is disabled. 36 */ 37 #define __scx_add_event(sch, name, cnt) do { \ 38 __this_cpu_add((sch)->pcpu->event_stats.name, (cnt)); \ 39 trace_sched_ext_event(#name, cnt); \ 40 } while(0) 41 42 #define SCX_OP_IDX(op) (offsetof(struct sched_ext_ops, op) / sizeof(void (*)(void))) 43 #define SCX_MOFF_IDX(moff) ((moff) / sizeof(void (*)(void))) 44 45 enum scx_exit_kind { 46 SCX_EXIT_NONE, 47 SCX_EXIT_DONE, 48 49 SCX_EXIT_UNREG = 64, /* user-space initiated unregistration */ 50 SCX_EXIT_UNREG_BPF, /* BPF-initiated unregistration */ 51 SCX_EXIT_UNREG_KERN, /* kernel-initiated unregistration */ 52 SCX_EXIT_SYSRQ, /* requested by 'S' sysrq */ 53 SCX_EXIT_PARENT, /* parent exiting */ 54 SCX_EXIT_PARENT_KILL, /* killed by parent scheduler */ 55 56 SCX_EXIT_ERROR = 1024, /* runtime error, error msg contains details */ 57 SCX_EXIT_ERROR_BPF, /* ERROR but triggered through scx_bpf_error() */ 58 SCX_EXIT_ERROR_STALL, /* watchdog detected stalled runnable tasks */ 59 SCX_EXIT_ERROR_REENQ, /* task hit reenqueue limit without running */ 60 }; 61 62 /* 63 * An exit code can be specified when exiting with scx_bpf_exit() or scx_exit(), 64 * corresponding to exit_kind UNREG_BPF and UNREG_KERN respectively. The codes 65 * are 64bit of the format: 66 * 67 * Bits: [63 .. 48 47 .. 32 31 .. 0] 68 * [ SYS ACT ] [ SYS RSN ] [ USR ] 69 * 70 * SYS ACT: System-defined exit actions 71 * SYS RSN: System-defined exit reasons 72 * USR : User-defined exit codes and reasons 73 * 74 * Using the above, users may communicate intention and context by ORing system 75 * actions and/or system reasons with a user-defined exit code. 76 */ 77 enum scx_exit_code { 78 /* Reasons */ 79 SCX_ECODE_RSN_HOTPLUG = 1LLU << 32, 80 SCX_ECODE_RSN_CGROUP_OFFLINE = 2LLU << 32, 81 82 /* Actions */ 83 SCX_ECODE_ACT_RESTART = 1LLU << 48, 84 }; 85 86 enum scx_exit_flags { 87 /* 88 * ops.exit() may be called even if the loading failed before ops.init() 89 * finishes successfully. This is because ops.exit() allows rich exit 90 * info communication. The following flag indicates whether ops.init() 91 * finished successfully. 92 */ 93 SCX_EFLAG_INITIALIZED = 1LLU << 0, 94 }; 95 96 /* 97 * scx_exit_info is passed to ops.exit() to describe why the BPF scheduler is 98 * being disabled. 99 */ 100 struct scx_exit_info { 101 /* %SCX_EXIT_* - broad category of the exit reason */ 102 enum scx_exit_kind kind; 103 104 /* 105 * CPU that initiated the exit, valid once @kind has been set. 106 * Negative if the exit path didn't identify a CPU. 107 */ 108 s32 exit_cpu; 109 110 /* exit code if gracefully exiting */ 111 s64 exit_code; 112 113 /* %SCX_EFLAG_* */ 114 u64 flags; 115 116 /* textual representation of the above */ 117 const char *reason; 118 119 /* backtrace if exiting due to an error */ 120 unsigned long *bt; 121 u32 bt_len; 122 123 /* informational message */ 124 char *msg; 125 126 /* debug dump */ 127 char *dump; 128 }; 129 130 /* sched_ext_ops.flags */ 131 enum scx_ops_flags { 132 /* 133 * Keep built-in idle tracking even if ops.update_idle() is implemented. 134 */ 135 SCX_OPS_KEEP_BUILTIN_IDLE = 1LLU << 0, 136 137 /* 138 * By default, if there are no other task to run on the CPU, ext core 139 * keeps running the current task even after its slice expires. If this 140 * flag is specified, such tasks are passed to ops.enqueue() with 141 * %SCX_ENQ_LAST. See the comment above %SCX_ENQ_LAST for more info. 142 */ 143 SCX_OPS_ENQ_LAST = 1LLU << 1, 144 145 /* 146 * An exiting task may schedule after PF_EXITING is set. In such cases, 147 * bpf_task_from_pid() may not be able to find the task and if the BPF 148 * scheduler depends on pid lookup for dispatching, the task will be 149 * lost leading to various issues including RCU grace period stalls. 150 * 151 * To mask this problem, by default, unhashed tasks are automatically 152 * dispatched to the local DSQ on enqueue. If the BPF scheduler doesn't 153 * depend on pid lookups and wants to handle these tasks directly, the 154 * following flag can be used. With %SCX_OPS_TID_TO_TASK, 155 * scx_bpf_tid_to_task() can find exiting tasks reliably. 156 */ 157 SCX_OPS_ENQ_EXITING = 1LLU << 2, 158 159 /* 160 * If set, only tasks with policy set to SCHED_EXT are attached to 161 * sched_ext. If clear, SCHED_NORMAL tasks are also included. 162 */ 163 SCX_OPS_SWITCH_PARTIAL = 1LLU << 3, 164 165 /* 166 * A migration disabled task can only execute on its current CPU. By 167 * default, such tasks are automatically put on the CPU's local DSQ with 168 * the default slice on enqueue. If this ops flag is set, they also go 169 * through ops.enqueue(). 170 * 171 * A migration disabled task never invokes ops.select_cpu() as it can 172 * only select the current CPU. Also, p->cpus_ptr will only contain its 173 * current CPU while p->nr_cpus_allowed keeps tracking p->user_cpus_ptr 174 * and thus may disagree with cpumask_weight(p->cpus_ptr). 175 */ 176 SCX_OPS_ENQ_MIGRATION_DISABLED = 1LLU << 4, 177 178 /* 179 * Queued wakeup (ttwu_queue) is a wakeup optimization that invokes 180 * ops.enqueue() on the ops.select_cpu() selected or the wakee's 181 * previous CPU via IPI (inter-processor interrupt) to reduce cacheline 182 * transfers. When this optimization is enabled, ops.select_cpu() is 183 * skipped in some cases (when racing against the wakee switching out). 184 * As the BPF scheduler may depend on ops.select_cpu() being invoked 185 * during wakeups, queued wakeup is disabled by default. 186 * 187 * If this ops flag is set, queued wakeup optimization is enabled and 188 * the BPF scheduler must be able to handle ops.enqueue() invoked on the 189 * wakee's CPU without preceding ops.select_cpu() even for tasks which 190 * may be executed on multiple CPUs. 191 */ 192 SCX_OPS_ALLOW_QUEUED_WAKEUP = 1LLU << 5, 193 194 /* 195 * If set, enable per-node idle cpumasks. If clear, use a single global 196 * flat idle cpumask. 197 */ 198 SCX_OPS_BUILTIN_IDLE_PER_NODE = 1LLU << 6, 199 200 /* 201 * If set, %SCX_ENQ_IMMED is assumed to be set on all local DSQ 202 * enqueues. 203 */ 204 SCX_OPS_ALWAYS_ENQ_IMMED = 1LLU << 7, 205 206 /* 207 * Maintain a mapping from p->scx.tid to task_struct so the BPF 208 * scheduler can recover task pointers from stored tids via 209 * scx_bpf_tid_to_task(). 210 * 211 * Only the root scheduler turns this on. A sub-sched may set the flag 212 * to declare a dependency on the lookup; if the root scheduler hasn't 213 * enabled it, attaching the sub-sched is rejected. 214 */ 215 SCX_OPS_TID_TO_TASK = 1LLU << 8, 216 217 SCX_OPS_ALL_FLAGS = SCX_OPS_KEEP_BUILTIN_IDLE | 218 SCX_OPS_ENQ_LAST | 219 SCX_OPS_ENQ_EXITING | 220 SCX_OPS_ENQ_MIGRATION_DISABLED | 221 SCX_OPS_ALLOW_QUEUED_WAKEUP | 222 SCX_OPS_SWITCH_PARTIAL | 223 SCX_OPS_BUILTIN_IDLE_PER_NODE | 224 SCX_OPS_ALWAYS_ENQ_IMMED | 225 SCX_OPS_TID_TO_TASK, 226 227 /* high 8 bits are internal, don't include in SCX_OPS_ALL_FLAGS */ 228 __SCX_OPS_INTERNAL_MASK = 0xffLLU << 56, 229 230 SCX_OPS_HAS_CPU_PREEMPT = 1LLU << 56, 231 }; 232 233 /* argument container for ops.init_task() */ 234 struct scx_init_task_args { 235 /* 236 * Set if ops.init_task() is being invoked on the fork path, as opposed 237 * to the scheduler transition path. 238 */ 239 bool fork; 240 #ifdef CONFIG_EXT_GROUP_SCHED 241 /* the cgroup the task is joining */ 242 struct cgroup *cgroup; 243 #endif 244 }; 245 246 /* argument container for ops.exit_task() */ 247 struct scx_exit_task_args { 248 /* Whether the task exited before running on sched_ext. */ 249 bool cancelled; 250 }; 251 252 /* argument container for ops.cgroup_init() */ 253 struct scx_cgroup_init_args { 254 /* the weight of the cgroup [1..10000] */ 255 u32 weight; 256 257 /* bandwidth control parameters from cpu.max and cpu.max.burst */ 258 u64 bw_period_us; 259 u64 bw_quota_us; 260 u64 bw_burst_us; 261 }; 262 263 enum scx_cpu_preempt_reason { 264 /* next task is being scheduled by &sched_class_rt */ 265 SCX_CPU_PREEMPT_RT, 266 /* next task is being scheduled by &sched_class_dl */ 267 SCX_CPU_PREEMPT_DL, 268 /* next task is being scheduled by &sched_class_stop */ 269 SCX_CPU_PREEMPT_STOP, 270 /* unknown reason for SCX being preempted */ 271 SCX_CPU_PREEMPT_UNKNOWN, 272 }; 273 274 /* 275 * Argument container for ops.cpu_acquire(). Currently empty, but may be 276 * expanded in the future. 277 */ 278 struct scx_cpu_acquire_args {}; 279 280 /* argument container for ops.cpu_release() */ 281 struct scx_cpu_release_args { 282 /* the reason the CPU was preempted */ 283 enum scx_cpu_preempt_reason reason; 284 285 /* the task that's going to be scheduled on the CPU */ 286 struct task_struct *task; 287 }; 288 289 /* informational context provided to dump operations */ 290 struct scx_dump_ctx { 291 enum scx_exit_kind kind; 292 s64 exit_code; 293 const char *reason; 294 u64 at_ns; 295 u64 at_jiffies; 296 }; 297 298 /* argument container for ops.sub_attach() */ 299 struct scx_sub_attach_args { 300 struct sched_ext_ops *ops; 301 char *cgroup_path; 302 }; 303 304 /* argument container for ops.sub_detach() */ 305 struct scx_sub_detach_args { 306 struct sched_ext_ops *ops; 307 char *cgroup_path; 308 }; 309 310 /** 311 * struct sched_ext_ops - Operation table for BPF scheduler implementation 312 * 313 * A BPF scheduler can implement an arbitrary scheduling policy by 314 * implementing and loading operations in this table. Note that a userland 315 * scheduling policy can also be implemented using the BPF scheduler 316 * as a shim layer. 317 */ 318 struct sched_ext_ops { 319 /** 320 * @select_cpu: Pick the target CPU for a task which is being woken up 321 * @p: task being woken up 322 * @prev_cpu: the cpu @p was on before sleeping 323 * @wake_flags: SCX_WAKE_* 324 * 325 * Decision made here isn't final. @p may be moved to any CPU while it 326 * is getting dispatched for execution later. However, as @p is not on 327 * the rq at this point, getting the eventual execution CPU right here 328 * saves a small bit of overhead down the line. 329 * 330 * If an idle CPU is returned, the CPU is kicked and will try to 331 * dispatch. While an explicit custom mechanism can be added, 332 * select_cpu() serves as the default way to wake up idle CPUs. 333 * 334 * @p may be inserted into a DSQ directly by calling 335 * scx_bpf_dsq_insert(). If so, the ops.enqueue() will be skipped. 336 * Directly inserting into %SCX_DSQ_LOCAL will put @p in the local DSQ 337 * of the CPU returned by this operation. 338 * 339 * Note that select_cpu() is never called for tasks that can only run 340 * on a single CPU or tasks with migration disabled, as they don't have 341 * the option to select a different CPU. See select_task_rq() for 342 * details. 343 */ 344 s32 (*select_cpu)(struct task_struct *p, s32 prev_cpu, u64 wake_flags); 345 346 /** 347 * @enqueue: Enqueue a task on the BPF scheduler 348 * @p: task being enqueued 349 * @enq_flags: %SCX_ENQ_* 350 * 351 * @p is ready to run. Insert directly into a DSQ by calling 352 * scx_bpf_dsq_insert() or enqueue on the BPF scheduler. If not directly 353 * inserted, the bpf scheduler owns @p and if it fails to dispatch @p, 354 * the task will stall. 355 * 356 * If @p was inserted into a DSQ from ops.select_cpu(), this callback is 357 * skipped. 358 */ 359 void (*enqueue)(struct task_struct *p, u64 enq_flags); 360 361 /** 362 * @dequeue: Remove a task from the BPF scheduler 363 * @p: task being dequeued 364 * @deq_flags: %SCX_DEQ_* 365 * 366 * Remove @p from the BPF scheduler. This is usually called to isolate 367 * the task while updating its scheduling properties (e.g. priority). 368 * 369 * The ext core keeps track of whether the BPF side owns a given task or 370 * not and can gracefully ignore spurious dispatches from BPF side, 371 * which makes it safe to not implement this method. However, depending 372 * on the scheduling logic, this can lead to confusing behaviors - e.g. 373 * scheduling position not being updated across a priority change. 374 */ 375 void (*dequeue)(struct task_struct *p, u64 deq_flags); 376 377 /** 378 * @dispatch: Dispatch tasks from the BPF scheduler and/or user DSQs 379 * @cpu: CPU to dispatch tasks for 380 * @prev: previous task being switched out 381 * 382 * Called when a CPU's local dsq is empty. The operation should dispatch 383 * one or more tasks from the BPF scheduler into the DSQs using 384 * scx_bpf_dsq_insert() and/or move from user DSQs into the local DSQ 385 * using scx_bpf_dsq_move_to_local(). 386 * 387 * The maximum number of times scx_bpf_dsq_insert() can be called 388 * without an intervening scx_bpf_dsq_move_to_local() is specified by 389 * ops.dispatch_max_batch. See the comments on top of the two functions 390 * for more details. 391 * 392 * When not %NULL, @prev is an SCX task with its slice depleted. If 393 * @prev is still runnable as indicated by set %SCX_TASK_QUEUED in 394 * @prev->scx.flags, it is not enqueued yet and will be enqueued after 395 * ops.dispatch() returns. To keep executing @prev, return without 396 * dispatching or moving any tasks. Also see %SCX_OPS_ENQ_LAST. 397 */ 398 void (*dispatch)(s32 cpu, struct task_struct *prev); 399 400 /** 401 * @tick: Periodic tick 402 * @p: task running currently 403 * 404 * This operation is called every 1/HZ seconds on CPUs which are 405 * executing an SCX task. Setting a slice of 0 for @p with 406 * scx_bpf_task_set_slice() will trigger an immediate dispatch cycle on 407 * the CPU. 408 */ 409 void (*tick)(struct task_struct *p); 410 411 /** 412 * @runnable: A task is becoming runnable on its associated CPU 413 * @p: task becoming runnable 414 * @enq_flags: %SCX_ENQ_* 415 * 416 * This and the following three functions can be used to track a task's 417 * execution state transitions. A task becomes ->runnable() on a CPU, 418 * and then goes through one or more ->running() and ->stopping() pairs 419 * as it runs on the CPU, and eventually becomes ->quiescent() when it's 420 * done running on the CPU. 421 * 422 * @p is becoming runnable on the CPU because it's 423 * 424 * - waking up (%SCX_ENQ_WAKEUP) 425 * - being moved from another CPU 426 * - being restored after temporarily taken off the queue for an 427 * attribute change. 428 * 429 * This and ->enqueue() are related but not coupled. This operation 430 * notifies @p's state transition and may not be followed by ->enqueue() 431 * e.g. when @p is being dispatched to a remote CPU, or when @p is 432 * being enqueued on a CPU experiencing a hotplug event. Likewise, a 433 * task may be ->enqueue()'d without being preceded by this operation 434 * e.g. after exhausting its slice. 435 */ 436 void (*runnable)(struct task_struct *p, u64 enq_flags); 437 438 /** 439 * @running: A task is starting to run on its associated CPU 440 * @p: task starting to run 441 * 442 * Note that this callback may be called from a CPU other than the 443 * one the task is going to run on. This can happen when a task 444 * property is changed (i.e., affinity), since scx_next_task_scx(), 445 * which triggers this callback, may run on a CPU different from 446 * the task's assigned CPU. 447 * 448 * Therefore, always use scx_bpf_task_cpu(@p) to determine the 449 * target CPU the task is going to use. 450 * 451 * See ->runnable() for explanation on the task state notifiers. 452 */ 453 void (*running)(struct task_struct *p); 454 455 /** 456 * @stopping: A task is stopping execution 457 * @p: task stopping to run 458 * @runnable: is task @p still runnable? 459 * 460 * Note that this callback may be called from a CPU other than the 461 * one the task was running on. This can happen when a task 462 * property is changed (i.e., affinity), since dequeue_task_scx(), 463 * which triggers this callback, may run on a CPU different from 464 * the task's assigned CPU. 465 * 466 * Therefore, always use scx_bpf_task_cpu(@p) to retrieve the CPU 467 * the task was running on. 468 * 469 * See ->runnable() for explanation on the task state notifiers. If 470 * !@runnable, ->quiescent() will be invoked after this operation 471 * returns. 472 */ 473 void (*stopping)(struct task_struct *p, bool runnable); 474 475 /** 476 * @quiescent: A task is becoming not runnable on its associated CPU 477 * @p: task becoming not runnable 478 * @deq_flags: %SCX_DEQ_* 479 * 480 * See ->runnable() for explanation on the task state notifiers. 481 * 482 * @p is becoming quiescent on the CPU because it's 483 * 484 * - sleeping (%SCX_DEQ_SLEEP) 485 * - being moved to another CPU 486 * - being temporarily taken off the queue for an attribute change 487 * (%SCX_DEQ_SAVE) 488 * 489 * This and ->dequeue() are related but not coupled. This operation 490 * notifies @p's state transition and may not be preceded by ->dequeue() 491 * e.g. when @p is being dispatched to a remote CPU. 492 */ 493 void (*quiescent)(struct task_struct *p, u64 deq_flags); 494 495 /** 496 * @yield: Yield CPU 497 * @from: yielding task 498 * @to: optional yield target task 499 * 500 * If @to is NULL, @from is yielding the CPU to other runnable tasks. 501 * The BPF scheduler should ensure that other available tasks are 502 * dispatched before the yielding task. Return value is ignored in this 503 * case. 504 * 505 * If @to is not-NULL, @from wants to yield the CPU to @to. If the bpf 506 * scheduler can implement the request, return %true; otherwise, %false. 507 */ 508 bool (*yield)(struct task_struct *from, struct task_struct *to); 509 510 /** 511 * @core_sched_before: Task ordering for core-sched 512 * @a: task A 513 * @b: task B 514 * 515 * Used by core-sched to determine the ordering between two tasks. See 516 * Documentation/admin-guide/hw-vuln/core-scheduling.rst for details on 517 * core-sched. 518 * 519 * Both @a and @b are runnable and may or may not currently be queued on 520 * the BPF scheduler. Should return %true if @a should run before @b. 521 * %false if there's no required ordering or @b should run before @a. 522 * 523 * If not specified, the default is ordering them according to when they 524 * became runnable. 525 */ 526 bool (*core_sched_before)(struct task_struct *a, struct task_struct *b); 527 528 /** 529 * @set_weight: Set task weight 530 * @p: task to set weight for 531 * @weight: new weight [1..10000] 532 * 533 * Update @p's weight to @weight. 534 */ 535 void (*set_weight)(struct task_struct *p, u32 weight); 536 537 /** 538 * @set_cpumask: Set CPU affinity 539 * @p: task to set CPU affinity for 540 * @cpumask: cpumask of cpus that @p can run on 541 * 542 * Update @p's CPU affinity to @cpumask. 543 */ 544 void (*set_cpumask)(struct task_struct *p, 545 const struct cpumask *cpumask); 546 547 /** 548 * @update_idle: Update the idle state of a CPU 549 * @cpu: CPU to update the idle state for 550 * @idle: whether entering or exiting the idle state 551 * 552 * This operation is called when @rq's CPU goes or leaves the idle 553 * state. By default, implementing this operation disables the built-in 554 * idle CPU tracking and the following helpers become unavailable: 555 * 556 * - scx_bpf_select_cpu_dfl() 557 * - scx_bpf_select_cpu_and() 558 * - scx_bpf_test_and_clear_cpu_idle() 559 * - scx_bpf_pick_idle_cpu() 560 * 561 * The user also must implement ops.select_cpu() as the default 562 * implementation relies on scx_bpf_select_cpu_dfl(). 563 * 564 * Specify the %SCX_OPS_KEEP_BUILTIN_IDLE flag to keep the built-in idle 565 * tracking. 566 */ 567 void (*update_idle)(s32 cpu, bool idle); 568 569 /** 570 * @init_task: Initialize a task to run in a BPF scheduler 571 * @p: task to initialize for BPF scheduling 572 * @args: init arguments, see the struct definition 573 * 574 * Either we're loading a BPF scheduler or a new task is being forked. 575 * Initialize @p for BPF scheduling. This operation may block and can 576 * be used for allocations, and is called exactly once for a task. 577 * 578 * Return 0 for success, -errno for failure. An error return while 579 * loading will abort loading of the BPF scheduler. During a fork, it 580 * will abort that specific fork. 581 */ 582 s32 (*init_task)(struct task_struct *p, struct scx_init_task_args *args); 583 584 /** 585 * @exit_task: Exit a previously-running task from the system 586 * @p: task to exit 587 * @args: exit arguments, see the struct definition 588 * 589 * @p is exiting or the BPF scheduler is being unloaded. Perform any 590 * necessary cleanup for @p. 591 */ 592 void (*exit_task)(struct task_struct *p, struct scx_exit_task_args *args); 593 594 /** 595 * @enable: Enable BPF scheduling for a task 596 * @p: task to enable BPF scheduling for 597 * 598 * Enable @p for BPF scheduling. enable() is called on @p any time it 599 * enters SCX, and is always paired with a matching disable(). 600 */ 601 void (*enable)(struct task_struct *p); 602 603 /** 604 * @disable: Disable BPF scheduling for a task 605 * @p: task to disable BPF scheduling for 606 * 607 * @p is exiting, leaving SCX or the BPF scheduler is being unloaded. 608 * Disable BPF scheduling for @p. A disable() call is always matched 609 * with a prior enable() call. 610 */ 611 void (*disable)(struct task_struct *p); 612 613 /** 614 * @dump: Dump BPF scheduler state on error 615 * @ctx: debug dump context 616 * 617 * Use scx_bpf_dump() to generate BPF scheduler specific debug dump. 618 */ 619 void (*dump)(struct scx_dump_ctx *ctx); 620 621 /** 622 * @dump_cpu: Dump BPF scheduler state for a CPU on error 623 * @ctx: debug dump context 624 * @cpu: CPU to generate debug dump for 625 * @idle: @cpu is currently idle without any runnable tasks 626 * 627 * Use scx_bpf_dump() to generate BPF scheduler specific debug dump for 628 * @cpu. If @idle is %true and this operation doesn't produce any 629 * output, @cpu is skipped for dump. 630 */ 631 void (*dump_cpu)(struct scx_dump_ctx *ctx, s32 cpu, bool idle); 632 633 /** 634 * @dump_task: Dump BPF scheduler state for a runnable task on error 635 * @ctx: debug dump context 636 * @p: runnable task to generate debug dump for 637 * 638 * Use scx_bpf_dump() to generate BPF scheduler specific debug dump for 639 * @p. 640 */ 641 void (*dump_task)(struct scx_dump_ctx *ctx, struct task_struct *p); 642 643 #ifdef CONFIG_EXT_GROUP_SCHED 644 /** 645 * @cgroup_init: Initialize a cgroup 646 * @cgrp: cgroup being initialized 647 * @args: init arguments, see the struct definition 648 * 649 * Initialize @cgrp for sched_ext, delivered to @cgrp's sched either 650 * when the BPF scheduler is being loaded or when @cgrp is created. This 651 * operation may block. 652 * 653 * Cgroup handovers also generate these ops: an enabling sub-scheduler 654 * receives ops.cgroup_init() for every cgroup in its subtree while the 655 * previous sched receives ops.cgroup_exit(), and disabling reverses the 656 * two. 657 * 658 * When the BPF scheduler is being loaded or cgroups are being handed 659 * over, @cgrp may already have been removed by userspace: a removed 660 * cgroup stays schedulable until its dying tasks finish their final 661 * context switches. 662 * 663 * Return 0 for success, -errno for failure. An error return while 664 * loading will abort loading of the BPF scheduler. During cgroup 665 * creation, it will abort the specific cgroup creation. 666 */ 667 s32 (*cgroup_init)(struct cgroup *cgrp, 668 struct scx_cgroup_init_args *args); 669 670 /** 671 * @cgroup_exit: Exit a cgroup 672 * @cgrp: cgroup being exited 673 * 674 * Exit @cgrp for sched_ext, delivered to the sched whose 675 * ops.cgroup_init() it pairs with, either when the BPF scheduler is 676 * being unloaded or when @cgrp is destroyed. This operation may block. 677 * 678 * For a destroyed @cgrp, delivery follows the last scheduling event on 679 * it: a removed cgroup stays schedulable until its dying tasks finish 680 * their final context switches. 681 */ 682 void (*cgroup_exit)(struct cgroup *cgrp); 683 684 /** 685 * @cgroup_prep_move: Prepare a task to be moved to a different cgroup 686 * @p: task being moved 687 * @from: cgroup @p is being moved from 688 * @to: cgroup @p is being moved to 689 * 690 * Prepare @p for move from cgroup @from to @to. This operation may 691 * block and can be used for allocations. 692 * 693 * The cgroup_move ops are delivered to @p's sched, and only for moves 694 * that don't re-home @p. A re-homing move is reported through 695 * ops.exit_task() and ops.init_task() instead. @from and @to can 696 * reference cgroups the sched never received ops.cgroup_init() for, as 697 * the cpu controller can be coarser than the sub-scheduler topology. 698 * 699 * Return 0 for success, -errno for failure. An error return aborts the 700 * migration. 701 */ 702 s32 (*cgroup_prep_move)(struct task_struct *p, 703 struct cgroup *from, struct cgroup *to); 704 705 /** 706 * @cgroup_move: Commit cgroup move 707 * @p: task being moved 708 * @from: cgroup @p is being moved from 709 * @to: cgroup @p is being moved to 710 * 711 * Commit the move. @p is dequeued during this operation. 712 */ 713 void (*cgroup_move)(struct task_struct *p, 714 struct cgroup *from, struct cgroup *to); 715 716 /** 717 * @cgroup_cancel_move: Cancel cgroup move 718 * @p: task whose cgroup move is being canceled 719 * @from: cgroup @p was being moved from 720 * @to: cgroup @p was being moved to 721 * 722 * @p was cgroup_prep_move()'d but failed before reaching cgroup_move(). 723 * Undo the preparation. 724 */ 725 void (*cgroup_cancel_move)(struct task_struct *p, 726 struct cgroup *from, struct cgroup *to); 727 728 /** 729 * @cgroup_set_weight: A cgroup's weight is being changed 730 * @cgrp: cgroup whose weight is being updated 731 * @weight: new weight [1..10000] 732 * 733 * Update @cgrp's weight to @weight. 734 * 735 * Knobs of a cgroup belong to the parent, so the set_* ops are 736 * delivered to @cgrp's parent's sched. That sched may never have seen 737 * ops.cgroup_init() for @cgrp - at a sub-scheduler attach point, the 738 * parent sched tracks @cgrp through ops.sub_attach() instead. 739 */ 740 void (*cgroup_set_weight)(struct cgroup *cgrp, u32 weight); 741 742 /** 743 * @cgroup_set_bandwidth: A cgroup's bandwidth is being changed 744 * @cgrp: cgroup whose bandwidth is being updated 745 * @period_us: bandwidth control period 746 * @quota_us: bandwidth control quota 747 * @burst_us: bandwidth control burst 748 * 749 * Update @cgrp's bandwidth control parameters. This is from the cpu.max 750 * cgroup interface. 751 * 752 * @quota_us / @period_us determines the CPU bandwidth @cgrp is entitled 753 * to. For example, if @period_us is 1_000_000 and @quota_us is 754 * 2_500_000. @cgrp is entitled to 2.5 CPUs. @burst_us can be 755 * interpreted in the same fashion and specifies how much @cgrp can 756 * burst temporarily. The specific control mechanism and thus the 757 * interpretation of @period_us and burstiness is up to the BPF 758 * scheduler. 759 * 760 * Delivery follows the same rule as cgroup_set_weight(). 761 */ 762 void (*cgroup_set_bandwidth)(struct cgroup *cgrp, 763 u64 period_us, u64 quota_us, u64 burst_us); 764 765 /** 766 * @cgroup_set_idle: A cgroup's idle state is being changed 767 * @cgrp: cgroup whose idle state is being updated 768 * @idle: whether the cgroup is entering or exiting idle state 769 * 770 * Update @cgrp's idle state to @idle. This callback is invoked when 771 * a cgroup transitions between idle and non-idle states, allowing the 772 * BPF scheduler to adjust its behavior accordingly. 773 * 774 * Delivery follows the same rule as cgroup_set_weight(). 775 */ 776 void (*cgroup_set_idle)(struct cgroup *cgrp, bool idle); 777 778 #endif /* CONFIG_EXT_GROUP_SCHED */ 779 780 /** 781 * @sub_attach: Attach a sub-scheduler 782 * @args: argument container, see the struct definition 783 * 784 * Return 0 to accept the sub-scheduler. -errno to reject. 785 */ 786 s32 (*sub_attach)(struct scx_sub_attach_args *args); 787 788 /** 789 * @sub_detach: Detach a sub-scheduler 790 * @args: argument container, see the struct definition 791 */ 792 void (*sub_detach)(struct scx_sub_detach_args *args); 793 794 /** 795 * @sub_caps_updated: Caps on this sub-sched's shard changed 796 * @cmask: cids whose caps changed (cmask->base identifies the shard) 797 * @caps: SCX_CAP_* that changed 798 * 799 * Invoked after grant or revoke modifies caps on a shard. There can be 800 * only one in-flight invocation per shard. @cmask and @caps coalesce 801 * all changes since the last delivery. Direction (set vs cleared) isn't 802 * encoded. Query current state with scx_bpf_sub_caps(). 803 * 804 * Delivered asynchronously after the change is recorded, and may run 805 * before it takes effect on any given cpu. Use it to track which caps 806 * the sub-sched holds and propagate to its own children, not to decide 807 * if a task can run on a cpu now. sub_ecaps_updated() reports that per 808 * cpu, once it is in effect. 809 * 810 * May call scx_bpf_sub_grant() / scx_bpf_sub_revoke() on children. 811 */ 812 void (*sub_caps_updated)(const struct scx_cmask *cmask, u64 caps); 813 814 /** 815 * @sub_ecaps_updated: This sub-sched's effective caps on a cid changed 816 * @cid: the cid whose effective caps changed 817 * @before: effective caps as of the last delivery 818 * @after: effective caps now 819 * 820 * Invoked when this sub-sched's effective caps on @cid change, once the 821 * change is in effect on the cpu. Runs in dispatch context with rq lock 822 * held, and can perform all operations allowed in ops.dispatch() 823 * including inserting/moving tasks. 824 */ 825 void (*sub_ecaps_updated)(s32 cid, u64 before, u64 after); 826 827 /* 828 * All online ops must come before ops.cpu_online(). 829 */ 830 831 /** 832 * @cpu_online: A CPU became online 833 * @cpu: CPU which just came up 834 * 835 * @cpu just came online. @cpu will not call ops.enqueue() or 836 * ops.dispatch(), nor run tasks associated with other CPUs beforehand. 837 */ 838 void (*cpu_online)(s32 cpu); 839 840 /** 841 * @cpu_offline: A CPU is going offline 842 * @cpu: CPU which is going offline 843 * 844 * @cpu is going offline. @cpu will not call ops.enqueue() or 845 * ops.dispatch(), nor run tasks associated with other CPUs afterwards. 846 */ 847 void (*cpu_offline)(s32 cpu); 848 849 /* 850 * All CPU hotplug ops must come before ops.init_cids(). 851 */ 852 853 /** 854 * @init_cids: Finalize the cid layout (cid-form only) 855 * 856 * Runs after the default cid layout is built, before caps and shards 857 * are finalized. A cid-form scheduler may call scx_bpf_cid_override() 858 * here for a custom layout. Ignored for cpu-form schedulers. 859 */ 860 s32 (*init_cids)(void); 861 862 /** 863 * @init: Initialize the BPF scheduler 864 */ 865 s32 (*init)(void); 866 867 /** 868 * @exit: Clean up after the BPF scheduler 869 * @info: Exit info 870 * 871 * ops.exit() is also called on ops.init() failure, which is a bit 872 * unusual. This is to allow rich reporting through @info on how 873 * ops.init() failed. 874 */ 875 void (*exit)(struct scx_exit_info *info); 876 877 /* 878 * Data fields must comes after all ops fields. 879 */ 880 881 /** 882 * @dispatch_max_batch: Max nr of tasks that dispatch() can dispatch 883 */ 884 u32 dispatch_max_batch; 885 886 /** 887 * @flags: %SCX_OPS_* flags 888 */ 889 u64 flags; 890 891 /** 892 * @timeout_ms: The maximum amount of time, in milliseconds, that a 893 * runnable task should be able to wait before being scheduled. The 894 * maximum timeout may not exceed the default timeout of 30 seconds. 895 * 896 * Defaults to the maximum allowed timeout value of 30 seconds. 897 */ 898 u32 timeout_ms; 899 900 /** 901 * @exit_dump_len: scx_exit_info.dump buffer length. If 0, the default 902 * value of 32768 is used. 903 */ 904 u32 exit_dump_len; 905 906 /** 907 * @hotplug_seq: A sequence number that may be set by the scheduler to 908 * detect when a hotplug event has occurred during the loading process. 909 * If 0, no detection occurs. Otherwise, the scheduler will fail to 910 * load if the sequence number does not match @scx_hotplug_seq on the 911 * enable path. 912 */ 913 u64 hotplug_seq; 914 915 /** 916 * @cid_shard_size: Target number of CIDs per shard 917 * 918 * Shards are contiguous CID ranges used as operation and locking 919 * domains for sub-scheduling. Each LLC is divided into ceil(nr_cpus / 920 * @cid_shard_size) shards, then cores are distributed across them 921 * evenly. If one core has more logical CPUs than @cid_shard_size, its 922 * shard will become larger than @cid_shard_size. Values above 923 * SCX_CID_SHARD_MAX_CPUS are capped. 0 means use the default (24). 924 */ 925 u32 cid_shard_size; 926 927 /** 928 * @sub_cgroup_id: When >1, attach the scheduler as a sub-scheduler 929 * on the specified cgroup. 930 */ 931 u64 sub_cgroup_id; 932 933 /** 934 * @name: BPF scheduler's name 935 * 936 * Must be a non-zero valid BPF object name including only isalnum(), 937 * '_' and '.' chars. Shows up in kernel.sched_ext_ops sysctl while the 938 * BPF scheduler is enabled. 939 */ 940 char name[SCX_OPS_NAME_LEN]; 941 942 /* internal use only, must be NULL */ 943 void __rcu *priv; 944 945 /* 946 * Deprecated callbacks. Kept at the end of the struct so the cid-form 947 * struct (sched_ext_ops_cid) can omit them without affecting the 948 * shared field offsets. Use SCX_ENQ_IMMED instead. Sitting past 949 * SCX_OPI_END means has_op doesn't cover them, so SCX_HAS_OP() cannot 950 * be used; callers must test sch->ops.cpu_acquire / cpu_release 951 * directly. 952 */ 953 954 /** 955 * @cpu_acquire: A CPU is becoming available to the BPF scheduler 956 * @cpu: The CPU being acquired by the BPF scheduler. 957 * @args: Acquire arguments, see the struct definition. 958 * 959 * A CPU that was previously released from the BPF scheduler is now once 960 * again under its control. Deprecated; use SCX_ENQ_IMMED instead. 961 */ 962 void (*cpu_acquire)(s32 cpu, struct scx_cpu_acquire_args *args); 963 964 /** 965 * @cpu_release: A CPU is taken away from the BPF scheduler 966 * @cpu: The CPU being released by the BPF scheduler. 967 * @args: Release arguments, see the struct definition. 968 * 969 * The specified CPU is no longer under the control of the BPF 970 * scheduler. This could be because it was preempted by a higher 971 * priority sched_class, though there may be other reasons as well. The 972 * caller should consult @args->reason to determine the cause. 973 * Deprecated; use SCX_ENQ_IMMED instead. 974 */ 975 void (*cpu_release)(s32 cpu, struct scx_cpu_release_args *args); 976 }; 977 978 /** 979 * struct sched_ext_ops_cid - cid-form alternative to struct sched_ext_ops 980 * 981 * Mirrors struct sched_ext_ops with cpu/cpumask substituted with cid/cmask 982 * where applicable. Layout up to and including @priv matches sched_ext_ops 983 * byte-for-byte (verified by BUILD_BUG_ON checks at scx_init() time) so 984 * shared field offsets work for both struct types in bpf_scx_init_member() 985 * and bpf_scx_check_member(). The deprecated cpu_acquire/cpu_release 986 * callbacks at the tail of sched_ext_ops are omitted here entirely. 987 * 988 * Differences from sched_ext_ops: 989 * - select_cpu -> select_cid (returns cid) 990 * - dispatch -> dispatch (cpu arg is now cid) 991 * - update_idle -> update_idle (cpu arg is now cid) 992 * - set_cpumask -> set_cmask (cmask instead of cpumask) 993 * - cpu_online -> cid_online 994 * - cpu_offline -> cid_offline 995 * - dump_cpu -> dump_cid 996 * - cgroup_* -> cpuctl_* (they track the cgroup cpu controller) 997 * - cpu_acquire/cpu_release -> not present (deprecated in sched_ext_ops) 998 * 999 * BPF schedulers using this type cannot call cpu-form scx_bpf_* kfuncs; 1000 * use the cid-form variants instead. Enforced at BPF verifier time via 1001 * scx_kfunc_context_filter() branching on prog->aux->st_ops. 1002 * 1003 * See sched_ext_ops for callback documentation. 1004 */ 1005 struct sched_ext_ops_cid { 1006 s32 (*select_cid)(struct task_struct *p, s32 prev_cid, u64 wake_flags); 1007 void (*enqueue)(struct task_struct *p, u64 enq_flags); 1008 void (*dequeue)(struct task_struct *p, u64 deq_flags); 1009 void (*dispatch)(s32 cid, struct task_struct *prev); 1010 void (*tick)(struct task_struct *p); 1011 void (*runnable)(struct task_struct *p, u64 enq_flags); 1012 void (*running)(struct task_struct *p); 1013 void (*stopping)(struct task_struct *p, bool runnable); 1014 void (*quiescent)(struct task_struct *p, u64 deq_flags); 1015 bool (*yield)(struct task_struct *from, struct task_struct *to); 1016 bool (*core_sched_before)(struct task_struct *a, 1017 struct task_struct *b); 1018 void (*set_weight)(struct task_struct *p, u32 weight); 1019 void (*set_cmask)(struct task_struct *p, 1020 const struct scx_cmask *cmask); 1021 void (*update_idle)(s32 cid, bool idle); 1022 s32 (*init_task)(struct task_struct *p, 1023 struct scx_init_task_args *args); 1024 void (*exit_task)(struct task_struct *p, 1025 struct scx_exit_task_args *args); 1026 void (*enable)(struct task_struct *p); 1027 void (*disable)(struct task_struct *p); 1028 void (*dump)(struct scx_dump_ctx *ctx); 1029 void (*dump_cid)(struct scx_dump_ctx *ctx, s32 cid, bool idle); 1030 void (*dump_task)(struct scx_dump_ctx *ctx, struct task_struct *p); 1031 #ifdef CONFIG_EXT_GROUP_SCHED 1032 s32 (*cpuctl_init)(struct cgroup *cgrp, struct scx_cgroup_init_args *args); 1033 void (*cpuctl_exit)(struct cgroup *cgrp); 1034 s32 (*cpuctl_prep_move)(struct task_struct *p, struct cgroup *from, 1035 struct cgroup *to); 1036 void (*cpuctl_move)(struct task_struct *p, struct cgroup *from, struct cgroup *to); 1037 void (*cpuctl_cancel_move)(struct task_struct *p, struct cgroup *from, 1038 struct cgroup *to); 1039 void (*cpuctl_set_weight)(struct cgroup *cgrp, u32 weight); 1040 void (*cpuctl_set_bandwidth)(struct cgroup *cgrp, u64 period_us, u64 quota_us, 1041 u64 burst_us); 1042 void (*cpuctl_set_idle)(struct cgroup *cgrp, bool idle); 1043 #endif /* CONFIG_EXT_GROUP_SCHED */ 1044 s32 (*sub_attach)(struct scx_sub_attach_args *args); 1045 void (*sub_detach)(struct scx_sub_detach_args *args); 1046 void (*sub_caps_updated)(const struct scx_cmask *cmask, u64 caps); 1047 void (*sub_ecaps_updated)(s32 cid, u64 before, u64 after); 1048 void (*cid_online)(s32 cid); 1049 void (*cid_offline)(s32 cid); 1050 s32 (*init_cids)(void); 1051 s32 (*init)(void); 1052 void (*exit)(struct scx_exit_info *info); 1053 1054 /* Data fields - must match sched_ext_ops layout exactly */ 1055 u32 dispatch_max_batch; 1056 u64 flags; 1057 u32 timeout_ms; 1058 u32 exit_dump_len; 1059 u64 hotplug_seq; 1060 u32 cid_shard_size; 1061 u64 sub_cgroup_id; 1062 char name[SCX_OPS_NAME_LEN]; 1063 1064 /* internal use only, must be NULL */ 1065 void __rcu *priv; 1066 1067 /* layout end anchor for the BUILD_BUG_ON in scx_init(); keep last */ 1068 char __end[0]; 1069 }; 1070 1071 enum scx_opi { 1072 SCX_OPI_BEGIN = 0, 1073 SCX_OPI_NORMAL_BEGIN = 0, 1074 SCX_OPI_NORMAL_END = SCX_OP_IDX(cpu_online), 1075 SCX_OPI_CPU_HOTPLUG_BEGIN = SCX_OP_IDX(cpu_online), 1076 SCX_OPI_CPU_HOTPLUG_END = SCX_OP_IDX(init_cids), 1077 SCX_OPI_END = SCX_OP_IDX(init_cids), 1078 }; 1079 1080 /* 1081 * Collection of event counters. Event types are placed in descending order. 1082 */ 1083 struct scx_event_stats { 1084 /* 1085 * If ops.select_cpu() returns a CPU which can't be used by the task, 1086 * the core scheduler code silently picks a fallback CPU. 1087 */ 1088 s64 SCX_EV_SELECT_CPU_FALLBACK; 1089 1090 /* 1091 * When dispatching to a local DSQ, the CPU may have gone offline in 1092 * the meantime. In this case, the task is bounced to the global DSQ. 1093 */ 1094 s64 SCX_EV_DISPATCH_LOCAL_DSQ_OFFLINE; 1095 1096 /* 1097 * If SCX_OPS_ENQ_LAST is not set, the number of times that a task 1098 * continued to run because there were no other tasks on the CPU. 1099 */ 1100 s64 SCX_EV_DISPATCH_KEEP_LAST; 1101 1102 /* 1103 * If SCX_OPS_ENQ_EXITING is not set, the number of times that a task 1104 * is dispatched to a local DSQ when exiting. 1105 */ 1106 s64 SCX_EV_ENQ_SKIP_EXITING; 1107 1108 /* 1109 * If SCX_OPS_ENQ_MIGRATION_DISABLED is not set, the number of times a 1110 * migration disabled task skips ops.enqueue() and is dispatched to its 1111 * local DSQ. 1112 */ 1113 s64 SCX_EV_ENQ_SKIP_MIGRATION_DISABLED; 1114 1115 /* 1116 * The number of times a task, enqueued on a local DSQ with 1117 * SCX_ENQ_IMMED, was re-enqueued because the CPU was not available for 1118 * immediate execution. 1119 */ 1120 s64 SCX_EV_REENQ_IMMED; 1121 1122 /* 1123 * The number of times a reenqueue (%SCX_ENQ_REENQ) led to another 1124 * reenqueue without the task running in between. This count climbing 1125 * rapidly indicates that the BPF scheduler keeps re-deciding placements 1126 * it can't honor. A single task reenqueued more than 1127 * %SCX_REENQ_MAX_REPEAT times gets its owning scheduler ejected. 1128 */ 1129 s64 SCX_EV_REENQ_REPEAT; 1130 1131 /* 1132 * Total number of times a task's time slice was refilled with the 1133 * default value (SCX_SLICE_DFL). 1134 */ 1135 s64 SCX_EV_REFILL_SLICE_DFL; 1136 1137 /* 1138 * The number of times an out-of-band slice request exceeded the maximum 1139 * representable value and was clamped. 1140 */ 1141 s64 SCX_EV_SLICE_CLAMPED; 1142 1143 /* 1144 * The number of times a slice extension was denied because the 1145 * scheduler lacked baseline cpu access on the task's cpu. 1146 */ 1147 s64 SCX_EV_SLICE_DENIED; 1148 1149 /* 1150 * The total duration of bypass modes in nanoseconds. 1151 */ 1152 s64 SCX_EV_BYPASS_DURATION; 1153 1154 /* 1155 * The number of tasks dispatched in the bypassing mode. 1156 */ 1157 s64 SCX_EV_BYPASS_DISPATCH; 1158 1159 /* 1160 * The number of times the bypassing mode has been activated. 1161 */ 1162 s64 SCX_EV_BYPASS_ACTIVATE; 1163 1164 /* 1165 * The number of times the scheduler attempted to insert a task that it 1166 * doesn't own into a DSQ. Such attempts are ignored. 1167 * 1168 * As BPF schedulers are allowed to ignore dequeues, it's difficult to 1169 * tell whether such an attempt is from a scheduler malfunction or an 1170 * ignored dequeue around sub-sched enabling. If this count keeps going 1171 * up regardless of sub-sched enabling, it likely indicates a bug in the 1172 * scheduler. 1173 */ 1174 s64 SCX_EV_INSERT_NOT_OWNED; 1175 1176 /* 1177 * The number of times tasks from bypassing descendants are scheduled 1178 * from sub_bypass_dsq's. 1179 */ 1180 s64 SCX_EV_SUB_BYPASS_DISPATCH; 1181 1182 /* 1183 * The number of times a migration-disabled task lacking the cap for its 1184 * cid was allowed onto the local DSQ. It must run on its pinned CPU, so 1185 * it can't be rejected. The violation is counted here. 1186 */ 1187 s64 SCX_EV_SUB_FORCED_ADMIT; 1188 1189 /* 1190 * The number of times a preempting kick was refused because the 1191 * sub-sched lacked SCX_CAP_PREEMPT for a task outside its subtree. The 1192 * kick degrades to a plain reschedule. 1193 */ 1194 s64 SCX_EV_SUB_PREEMPT_DENIED; 1195 1196 /* 1197 * The number of times a kick was skipped because the sub-sched lacked 1198 * baseline access on the target cid. The preempt-part degradation of a 1199 * delivered kick is counted in SCX_EV_SUB_PREEMPT_DENIED instead. 1200 */ 1201 s64 SCX_EV_SUB_KICK_DENIED; 1202 1203 /* 1204 * The number of times a local DSQ reenq was dropped because the 1205 * sub-sched lacked baseline access on the target cid. 1206 */ 1207 s64 SCX_EV_SUB_REENQ_DENIED; 1208 1209 /* 1210 * The number of times scx_bpf_cidperf_set() was denied because the 1211 * sub-sched lacked SCX_CAP_PERF on the target cid. 1212 */ 1213 s64 SCX_EV_SUB_CIDPERF_DENIED; 1214 }; 1215 1216 #define SCX_EVENTS_LIST(SCX_EVENT) \ 1217 SCX_EVENT(SCX_EV_SELECT_CPU_FALLBACK); \ 1218 SCX_EVENT(SCX_EV_DISPATCH_LOCAL_DSQ_OFFLINE); \ 1219 SCX_EVENT(SCX_EV_DISPATCH_KEEP_LAST); \ 1220 SCX_EVENT(SCX_EV_ENQ_SKIP_EXITING); \ 1221 SCX_EVENT(SCX_EV_ENQ_SKIP_MIGRATION_DISABLED); \ 1222 SCX_EVENT(SCX_EV_REENQ_IMMED); \ 1223 SCX_EVENT(SCX_EV_REENQ_REPEAT); \ 1224 SCX_EVENT(SCX_EV_REFILL_SLICE_DFL); \ 1225 SCX_EVENT(SCX_EV_SLICE_CLAMPED); \ 1226 SCX_EVENT(SCX_EV_SLICE_DENIED); \ 1227 SCX_EVENT(SCX_EV_BYPASS_DURATION); \ 1228 SCX_EVENT(SCX_EV_BYPASS_DISPATCH); \ 1229 SCX_EVENT(SCX_EV_BYPASS_ACTIVATE); \ 1230 SCX_EVENT(SCX_EV_INSERT_NOT_OWNED); \ 1231 SCX_EVENT(SCX_EV_SUB_BYPASS_DISPATCH); \ 1232 SCX_EVENT(SCX_EV_SUB_FORCED_ADMIT); \ 1233 SCX_EVENT(SCX_EV_SUB_PREEMPT_DENIED); \ 1234 SCX_EVENT(SCX_EV_SUB_KICK_DENIED); \ 1235 SCX_EVENT(SCX_EV_SUB_REENQ_DENIED); \ 1236 SCX_EVENT(SCX_EV_SUB_CIDPERF_DENIED) 1237 1238 struct scx_sched; 1239 1240 enum scx_sched_pcpu_flags { 1241 SCX_SCHED_PCPU_BYPASSING = 1LLU << 0, 1242 }; 1243 1244 /* dispatch buf */ 1245 struct scx_dsp_buf_ent { 1246 struct task_struct *task; 1247 unsigned long qseq; 1248 u64 dsq_id; 1249 u64 enq_flags; 1250 }; 1251 1252 struct scx_dsp_ctx { 1253 struct rq *rq; 1254 u32 cursor; 1255 u32 nr_tasks; 1256 struct scx_dsp_buf_ent buf[]; 1257 }; 1258 1259 struct scx_deferred_reenq_local { 1260 struct list_head node; 1261 u64 flags; 1262 }; 1263 1264 struct scx_sched_pcpu { 1265 struct scx_sched *sch; 1266 u64 flags; /* protected by rq lock */ 1267 1268 /* 1269 * Kick state owned by this cpu for this sched. scx_kick_cpu() records 1270 * targets here and links @to_kick_node onto the cpu's 1271 * rq->scx.sched_pcpus_to_kick. The cpu's single kick irq_work walks 1272 * that list and kicks each sched's targets on its behalf. Per-sched so 1273 * a kick stays attributed to its scheduler. 1274 */ 1275 cpumask_var_t cpus_to_kick; 1276 cpumask_var_t cpus_to_kick_if_idle; 1277 cpumask_var_t cpus_to_preempt; 1278 cpumask_var_t cpus_to_wait; 1279 struct list_head to_kick_node; 1280 1281 #ifdef CONFIG_EXT_SUB_SCHED 1282 /* 1283 * pshard->caps[cap_bit] is the set of cids the sched holds that one 1284 * cap on. ecaps is its transpose: the set of SCX_CAP_* bits the sched 1285 * effectively holds on this cpu, with implied caps folded in, so that 1286 * the hot-path check is a single read. 1287 * 1288 * While pshard->caps[] under pshard->lock is the target configuration, 1289 * ecaps is the effective copy owned by the cpu. It is written under the 1290 * rq lock while processing rq->ecaps_to_sync. Can also be read with 1291 * READ_ONCE() outside rq lock. 1292 * 1293 * See queue_sync_ecaps() and scx_process_sync_ecaps(). 1294 */ 1295 u64 ecaps; 1296 struct llist_node ecaps_to_sync_node; 1297 /* owed a forced update_idle() re-notify on this cpu */ 1298 bool idle_renotify; 1299 /* effective caps as of the last sub_ecaps_updated() delivery */ 1300 u64 reported_ecaps; 1301 #endif 1302 1303 /* 1304 * The event counters are in a per-CPU variable to minimize the 1305 * accounting overhead. A system-wide view on the event counter is 1306 * constructed when requested by scx_bpf_events(). 1307 */ 1308 struct scx_event_stats event_stats; 1309 1310 struct scx_deferred_reenq_local deferred_reenq_local; 1311 struct scx_dispatch_q bypass_dsq; 1312 #ifdef CONFIG_EXT_SUB_SCHED 1313 u32 bypass_host_seq; 1314 #endif 1315 1316 /* must be the last entry - contains flex array */ 1317 struct scx_dsp_ctx dsp_ctx; 1318 }; 1319 1320 struct scx_sched_pnode { 1321 struct scx_dispatch_q global_dsq; 1322 }; 1323 1324 /* 1325 * Sub-sched capability delegation. 1326 * 1327 * Caps are per-cid permissions parents delegate to direct children via 1328 * scx_bpf_sub_grant() / scx_bpf_sub_revoke(). A child's cap set is always a 1329 * subset of its parent's. A sub-sched checks its caps locally, and cross-sched 1330 * communication is needed only when the delegation set itself changes. 1331 * 1332 * Caps are used to implement sub-sched scheduling on the enqueue path. Picking 1333 * a cid for a task at a leaf depends on which cids the leaf is allowed to use. 1334 * Resolving that programmatically on every enqueue would mean a cross-sched 1335 * round-trip call chain, possibly retrying if the request can't be granted 1336 * as-is. 1337 * 1338 * The dispatch path is different - it runs as top-down recursion via 1339 * scx_bpf_sub_dispatch(): a sched's dispatch op invokes a child's dispatch op 1340 * on the local rq, and the subtree dispatches in a single pass. 1341 * 1342 * Locking is per shard. cid space is split into shards, and each sub-sched has 1343 * its own pshard->lock for each shard. Operations are broken up on shard 1344 * boundaries. Different shards never contend. Shards are expected to be 1345 * topology-aligned and likely to serve as the locality unit when cids are 1346 * allocated to schedulers, so per-shard lock granularity scales naturally with 1347 * the allocation pattern. 1348 * 1349 * ENQ_IMMED insert an IMMED task onto the cid's local DSQ 1350 * - kick the cid's cpu (except SCX_KICK_PREEMPT) 1351 * 1352 * ENQ insert any task onto the cid's local DSQ (implies ENQ_IMMED) 1353 * 1354 * PREEMPT preempt any task running on the cid regardless of the owning 1355 * sched (implies ENQ). Preempting a task in the sched's own subtree 1356 * doesn't require any cap. 1357 * - SCX_ENQ_PREEMPT inserts 1358 * - SCX_KICK_PREEMPT kicks 1359 * 1360 * PERF control the cid's cpu power/perf management state, currently the 1361 * cpufreq target set through scx_bpf_cidperf_set(). Hardware 1362 * control is a separate axis from queue access: PERF neither 1363 * implies nor is implied by the caps above. 1364 * 1365 * Implied caps apply to the holder's own use of a cid, not to delegation. 1366 * scx_bpf_sub_grant() delegates literally-held caps, so a cap held only through 1367 * implication is usable but cannot be re-delegated to a child. When granting a 1368 * cap, it usually makes sense to delegate its implied caps explicitly alongside 1369 * it. 1370 */ 1371 enum scx_cap_flags { 1372 __SCX_CAP_ENQ_IMMED = 0, 1373 __SCX_CAP_ENQ = 1, 1374 __SCX_CAP_PREEMPT = 2, 1375 __SCX_CAP_PERF = 3, 1376 1377 __SCX_NR_CAPS, 1378 __SCX_CAP_ALL = BIT_U64(__SCX_NR_CAPS) - 1, 1379 1380 SCX_CAP_ENQ_IMMED = BIT_U64(__SCX_CAP_ENQ_IMMED), 1381 SCX_CAP_ENQ = BIT_U64(__SCX_CAP_ENQ), 1382 SCX_CAP_PREEMPT = BIT_U64(__SCX_CAP_PREEMPT), 1383 SCX_CAP_PERF = BIT_U64(__SCX_CAP_PERF), 1384 1385 /* alias for minimal cap to make any use of a cpu */ 1386 SCX_CAP_BASE = SCX_CAP_ENQ_IMMED, 1387 1388 /* caps whose loss strands queued tasks, see scx_process_sync_ecaps() */ 1389 SCX_CAPS_REENQ_ON_LOSS = SCX_CAP_ENQ_IMMED | SCX_CAP_ENQ, 1390 }; 1391 1392 #ifdef CONFIG_EXT_SUB_SCHED 1393 /* iterate set bits in a u64 cap mask */ 1394 #define scx_for_each_cap_bit(cap_bit, caps) \ 1395 for (u64 __caps = (caps); \ 1396 __caps && ((cap_bit) = __ffs64(__caps), true); \ 1397 __caps &= __caps - 1) 1398 1399 /* 1400 * Sub-cap update notifier. 1401 * 1402 * ops_cid.sub_caps_updated() notifies sub-scheds when their cap state changes 1403 * so they can refresh internal state without polling scx_bpf_sub_caps() per 1404 * enqueue. 1405 * 1406 * Three constraints shape the design: 1407 * 1408 * 1. Static memory. Deliveries use a fixed-size buffer, both for runtime 1409 * efficiency and so notifications can't be lost under memory pressure. 1410 * 1411 * 2. High-frequency updates. Grant/revoke can mutate caps in bursts, and the 1412 * notifier path must absorb that without amplifying it. 1413 * 1414 * 3. Recursive grant/revoke from the callback. A child receiving a 1415 * notification can call grant/revoke on its own children, which can 1416 * cascade recursively down its subtree. 1417 * 1418 * (1) and (2) lead to coalescing into a fixed payload. Each delivery carries a 1419 * single (cmask, caps) pair covering every change since the previous one. 1420 * Direction (set vs cleared) isn't encoded as it doesn't fit in the fixed-size 1421 * summary. The callback queries scx_bpf_sub_caps() for current state. Only one 1422 * delivery is in flight per shard. Further changes fold into the same buffer 1423 * and ship as the next callback, so a shard's callbacks fire in order. 1424 * 1425 * (3) leads to deferred delivery. Events accumulate during grant/revoke and are 1426 * delivered after the shard lock is released. 1427 */ 1428 struct scx_caps_updated { 1429 raw_spinlock_t lock; 1430 u64 caps; 1431 struct scx_cmask *cmask_arena_out; 1432 struct list_head node_in_flight; 1433 /* Kernel-side accumulator. Access as &cu->cmask. */ 1434 TRAILING_OVERLAP(struct scx_cmask, cmask, bits, 1435 u64 _bits[SCX_CMASK_NR_WORDS(SCX_CID_SHARD_MAX_CPUS)]; 1436 ); 1437 }; 1438 1439 struct scx_pshard { 1440 raw_spinlock_t lock; /* serializes caps */ 1441 struct scx_sched *sch; /* backpointer */ 1442 struct scx_caps_updated caps_updated; 1443 1444 /* 1445 * Per-cap cmask, inline via TRAILING_OVERLAP so cmask.bits[] overlaps 1446 * the trailing _bits[] storage. Access as &caps[i].cmask. See 1447 * scx_sched_pcpu->ecaps. 1448 */ 1449 TRAILING_OVERLAP(struct scx_cmask, cmask, bits, 1450 u64 _bits[SCX_CMASK_NR_WORDS(SCX_CID_SHARD_MAX_CPUS)]; 1451 ) caps[__SCX_NR_CAPS]; 1452 1453 /* 1454 * Shard geometry captured at alloc. cmask_arena_out's own header is 1455 * bpf-writable and the live shard range can change before the 1456 * rcu-deferred free, so re-init and size cmask_arena_out from these 1457 * trusted copies instead. 1458 */ 1459 u32 base; 1460 u32 nr_cids; 1461 }; 1462 #endif 1463 1464 struct scx_sched { 1465 /* 1466 * cpu-form and cid-form ops share field offsets up to .priv (verified 1467 * by BUILD_BUG_ON in scx_init()). The anonymous union lets the kernel 1468 * access either view of the same storage without function-pointer 1469 * casts: use .ops for cpu-form and shared fields, .ops_cid for the 1470 * cid-renamed callbacks (set_cmask, select_cid, cid_online, ...). 1471 */ 1472 union { 1473 struct sched_ext_ops ops; 1474 struct sched_ext_ops_cid ops_cid; 1475 }; 1476 bool is_cid_type; /* true if registered via bpf_sched_ext_ops_cid */ 1477 bool dead; /* set after ops.exit(), gates scx_prog_sched() */ 1478 1479 /* 1480 * Arena map auto-discovered from member progs at struct_ops attach. 1481 * cid-form schedulers must use exactly one arena across all member 1482 * progs. NULL on cpu-form. 1483 * 1484 * @arena_pool sub-allocates @arena_map. Each gen_pool chunk is added 1485 * at the kernel-side mapping address. @arena_kern_base is the start 1486 * of the arena's kern_vm range. See scx_arena_to_kaddr() and 1487 * scx_kaddr_to_arena(). 1488 */ 1489 struct bpf_map *arena_map; 1490 struct gen_pool *arena_pool; 1491 uintptr_t arena_kern_base; 1492 1493 /* 1494 * Per-CPU arena cmask used by scx_call_op_set_cpumask() to hand a cmask 1495 * to ops_cid.set_cmask(). The kernel writes through the stored kern_va 1496 * and hands BPF its arena pointer via scx_kaddr_to_arena(). 1497 */ 1498 struct scx_cmask * __percpu *set_cmask_scratch; 1499 1500 DECLARE_BITMAP(has_op, SCX_OPI_END); 1501 1502 /* 1503 * Dispatch queues. 1504 * 1505 * The global DSQ (%SCX_DSQ_GLOBAL) is split per-node for scalability. 1506 * This is to avoid live-locking in bypass mode where all tasks are 1507 * dispatched to %SCX_DSQ_GLOBAL and all CPUs consume from it. If 1508 * per-node split isn't sufficient, it can be further split. 1509 */ 1510 struct rhashtable dsq_hash; 1511 struct scx_sched_pnode **pnode; 1512 #ifdef CONFIG_EXT_SUB_SCHED 1513 struct scx_pshard **pshard; /* indexed by shard_idx */ 1514 #endif 1515 struct scx_sched_pcpu __percpu *pcpu; 1516 1517 u64 slice_dfl; 1518 u64 bypass_timestamp; 1519 s32 bypass_depth; 1520 1521 /* bypass dispatch path enable state, see scx_bypass_dsp_enabled() */ 1522 unsigned long bypass_dsp_claim; 1523 atomic_t bypass_dsp_enable_depth; 1524 1525 bool aborting; 1526 bool dump_disabled; /* protected by scx_dump_lock */ 1527 u32 dsp_max_batch; 1528 s32 level; 1529 1530 #ifdef CONFIG_EXT_SUB_SCHED 1531 /* 1532 * pshard[] size captured at enable for the async RCU free path - 1533 * scx_nr_cid_shards may be rewritten by a later enable's 1534 * scx_cid_publish_tables() before free runs. While sch is active, use 1535 * the global. 1536 */ 1537 u32 nr_pshards; 1538 #endif 1539 1540 /* 1541 * Updates to the following warned bitfields can race causing RMW issues 1542 * but it doesn't really matter. 1543 */ 1544 bool warned_zero_slice:1; 1545 bool warned_unassoc_progs:1; 1546 1547 struct list_head all; 1548 1549 /* unique instance id, monotonic and never reused */ 1550 u64 id; 1551 1552 #ifdef CONFIG_EXT_SUB_SCHED 1553 struct rhash_head hash_node; 1554 1555 struct list_head children; 1556 struct list_head sibling; 1557 struct cgroup *cgrp; 1558 char *cgrp_path; 1559 struct kset *sub_kset; 1560 1561 bool linked; /* on ->children, see scx_link_sched() */ 1562 bool sub_attached; 1563 #endif /* CONFIG_EXT_SUB_SCHED */ 1564 1565 /* 1566 * The maximum amount of time in jiffies that a task may be runnable 1567 * without being scheduled on a CPU. If this timeout is exceeded, it 1568 * will trigger scx_error(). 1569 */ 1570 unsigned long watchdog_timeout; 1571 1572 atomic_t exit_kind; 1573 struct scx_exit_info *exit_info; 1574 1575 struct kobject kobj; 1576 1577 struct kthread_worker *helper; 1578 struct irq_work disable_irq_work; 1579 struct kthread_work disable_work; 1580 struct irq_work propagate_exit_irq_work; /* see scx_claim_exit() */ 1581 struct timer_list bypass_lb_timer; 1582 cpumask_var_t bypass_lb_donee_cpumask; 1583 cpumask_var_t bypass_lb_resched_cpumask; 1584 cpumask_var_t stall_cpus; 1585 struct rcu_work rcu_work; 1586 1587 /* all ancestors including self */ 1588 struct scx_sched *ancestors[]; 1589 }; 1590 1591 /** 1592 * scx_arena_to_kaddr - Translate a BPF-arena pointer to its kernel address 1593 * @sch: scheduler whose arena hosts @bpf_ptr 1594 * @bpf_ptr: BPF-arena pointer, only the low 32 bits are used 1595 * 1596 * The (u32) cast normalizes any input into the arena's 4 GiB kern_vm range, 1597 * which combined with scratch-page fault recovery makes the returned pointer 1598 * safe to dereference up to GUARD_SZ / 2 past the intended object. Accesses 1599 * larger than GUARD_SZ / 2 must be explicitly bounds-checked. 1600 */ 1601 static inline void *scx_arena_to_kaddr(struct scx_sched *sch, const void *bpf_ptr) 1602 { 1603 return (void *)(sch->arena_kern_base + (u32)(uintptr_t)bpf_ptr); 1604 } 1605 1606 /** 1607 * scx_kaddr_to_arena - Translate a kernel arena address to its BPF form 1608 * @sch: scheduler whose arena hosts @kaddr 1609 * @kaddr: kernel-side arena address, supplied by trusted kernel code 1610 */ 1611 static inline void *scx_kaddr_to_arena(struct scx_sched *sch, const void *kaddr) 1612 { 1613 return (void *)((uintptr_t)kaddr - sch->arena_kern_base); 1614 } 1615 1616 enum scx_wake_flags { 1617 /* expose select WF_* flags as enums */ 1618 SCX_WAKE_FORK = WF_FORK, 1619 SCX_WAKE_TTWU = WF_TTWU, 1620 SCX_WAKE_SYNC = WF_SYNC, 1621 }; 1622 1623 enum scx_enq_flags { 1624 /* expose select ENQUEUE_* flags as enums */ 1625 SCX_ENQ_WAKEUP = ENQUEUE_WAKEUP, 1626 SCX_ENQ_HEAD = ENQUEUE_HEAD, 1627 SCX_ENQ_CPU_SELECTED = ENQUEUE_RQ_SELECTED, 1628 1629 /* high 32bits are SCX specific */ 1630 1631 /* 1632 * Set the following to trigger preemption when calling 1633 * scx_bpf_dsq_insert() with a local dsq as the target. The slice of the 1634 * current task is cleared to zero and the CPU is kicked into the 1635 * scheduling path. Implies %SCX_ENQ_HEAD. 1636 */ 1637 SCX_ENQ_PREEMPT = 1LLU << 32, 1638 1639 /* 1640 * Only allowed on local DSQs. Guarantees that the task either gets 1641 * on the CPU immediately and stays on it, or gets reenqueued back 1642 * to the BPF scheduler. It will never linger on a local DSQ or be 1643 * silently put back after preemption. 1644 * 1645 * The protection persists until the next fresh enqueue - it 1646 * survives SAVE/RESTORE cycles, slice extensions and preemption. 1647 * If the task can't stay on the CPU for any reason, it gets 1648 * reenqueued back to the BPF scheduler. 1649 * 1650 * Exiting and migration-disabled tasks bypass ops.enqueue() and 1651 * are placed directly on a local DSQ without IMMED protection 1652 * unless %SCX_OPS_ENQ_EXITING and %SCX_OPS_ENQ_MIGRATION_DISABLED 1653 * are set respectively. 1654 */ 1655 SCX_ENQ_IMMED = 1LLU << 33, 1656 1657 /* 1658 * The task being enqueued was previously enqueued on a DSQ, but was 1659 * removed and is being re-enqueued. See SCX_TASK_REENQ_* flags to find 1660 * out why a given task is being reenqueued. 1661 */ 1662 SCX_ENQ_REENQ = 1LLU << 40, 1663 1664 /* 1665 * The task being enqueued is the only task available for the cpu. By 1666 * default, ext core keeps executing such tasks but when 1667 * %SCX_OPS_ENQ_LAST is specified, they're ops.enqueue()'d with the 1668 * %SCX_ENQ_LAST flag set. 1669 * 1670 * The BPF scheduler is responsible for triggering a follow-up 1671 * scheduling event. Otherwise, Execution may stall. 1672 */ 1673 SCX_ENQ_LAST = 1LLU << 41, 1674 1675 /* high 8 bits are internal */ 1676 __SCX_ENQ_INTERNAL_MASK = 0xffLLU << 56, 1677 1678 SCX_ENQ_CLEAR_OPSS = 1LLU << 56, 1679 SCX_ENQ_DSQ_PRIQ = 1LLU << 57, 1680 SCX_ENQ_NESTED = 1LLU << 58, 1681 SCX_ENQ_GDSQ_FALLBACK = 1LLU << 59, /* fell back to global DSQ */ 1682 SCX_ENQ_IGNORE_CAPS = 1LLU << 60, /* admit to local DSQ ignoring caps */ 1683 }; 1684 1685 enum scx_deq_flags { 1686 /* expose select DEQUEUE_* flags as enums */ 1687 SCX_DEQ_SLEEP = DEQUEUE_SLEEP, 1688 1689 /* high 32bits are SCX specific */ 1690 1691 /* 1692 * The generic core-sched layer decided to execute the task even though 1693 * it hasn't been dispatched yet. Dequeue from the BPF side. 1694 */ 1695 SCX_DEQ_CORE_SCHED_EXEC = 1LLU << 32, 1696 1697 /* 1698 * The task is being dequeued due to a property change (e.g., 1699 * sched_setaffinity(), sched_setscheduler(), set_user_nice(), 1700 * etc.). 1701 */ 1702 SCX_DEQ_SCHED_CHANGE = 1LLU << 33, 1703 }; 1704 1705 enum scx_reenq_flags { 1706 /* low 16bits determine which tasks should be reenqueued */ 1707 SCX_REENQ_ANY = 1LLU << 0, /* all tasks */ 1708 1709 /* internal: kernel-issued on cap revoke, not accepted from BPF */ 1710 SCX_REENQ_CAP_REVOKE = 1LLU << 1, 1711 1712 __SCX_REENQ_FILTER_MASK = 0xffffLLU, 1713 1714 __SCX_REENQ_USER_MASK = SCX_REENQ_ANY, 1715 1716 /* bits 32-35 used by task_should_reenq() */ 1717 SCX_REENQ_TSR_RQ_OPEN = 1LLU << 32, 1718 SCX_REENQ_TSR_NOT_FIRST = 1LLU << 33, 1719 1720 __SCX_REENQ_TSR_MASK = 0xfLLU << 32, 1721 }; 1722 1723 enum scx_pick_idle_cpu_flags { 1724 SCX_PICK_IDLE_CORE = 1LLU << 0, /* pick a CPU whose SMT siblings are also idle */ 1725 SCX_PICK_IDLE_IN_NODE = 1LLU << 1, /* pick a CPU in the same target NUMA node */ 1726 }; 1727 1728 enum scx_kick_flags { 1729 /* 1730 * Kick the target CPU if idle. Guarantees that the target CPU goes 1731 * through at least one full scheduling cycle before going idle. If the 1732 * target CPU can be determined to be currently not idle and going to go 1733 * through a scheduling cycle before going idle, noop. 1734 */ 1735 SCX_KICK_IDLE = 1LLU << 0, 1736 1737 /* 1738 * Preempt the current task and execute the dispatch path. If the 1739 * current task of the target CPU is an SCX task, its ->scx.slice is 1740 * cleared to zero before the scheduling path is invoked so that the 1741 * task expires and the dispatch path is invoked. 1742 */ 1743 SCX_KICK_PREEMPT = 1LLU << 1, 1744 1745 /* 1746 * The scx_bpf_kick_cpu() call will return after the current SCX task of 1747 * the target CPU switches out. This can be used to implement e.g. core 1748 * scheduling. This has no effect if the current task on the target CPU 1749 * is not on SCX. 1750 */ 1751 SCX_KICK_WAIT = 1LLU << 2, 1752 }; 1753 1754 enum scx_tg_flags { 1755 SCX_TG_ONLINE = 1U << 0, 1756 SCX_TG_INITED = 1U << 1, 1757 SCX_TG_SUB_INIT = 1U << 2, /* see scx_cgroup_claim_subtree() */ 1758 }; 1759 1760 enum scx_enable_state { 1761 SCX_ENABLING, 1762 SCX_ENABLED, 1763 SCX_DISABLING, 1764 SCX_DISABLED, 1765 }; 1766 1767 static const char *scx_enable_state_str[] = { 1768 [SCX_ENABLING] = "enabling", 1769 [SCX_ENABLED] = "enabled", 1770 [SCX_DISABLING] = "disabling", 1771 [SCX_DISABLED] = "disabled", 1772 }; 1773 1774 /* 1775 * Task Ownership State Machine (sched_ext_entity->ops_state) 1776 * 1777 * The sched_ext core uses this state machine to track task ownership 1778 * between the SCX core and the BPF scheduler. This allows the BPF 1779 * scheduler to dispatch tasks without strict ordering requirements, while 1780 * the SCX core safely rejects invalid dispatches. 1781 * 1782 * State Transitions 1783 * 1784 * .------------> NONE (owned by SCX core) 1785 * | | ^ 1786 * | enqueue | | direct dispatch 1787 * | v | 1788 * | QUEUEING -------' 1789 * | | 1790 * | enqueue | 1791 * | completes | 1792 * | v 1793 * | QUEUED (owned by BPF scheduler) 1794 * | | 1795 * | dispatch | 1796 * | | 1797 * | v 1798 * | DISPATCHING 1799 * | | 1800 * | dispatch | 1801 * | completes | 1802 * `---------------' 1803 * 1804 * State Descriptions 1805 * 1806 * - %SCX_OPSS_NONE: 1807 * Task is owned by the SCX core. It's either on a run queue, running, 1808 * or being manipulated by the core scheduler. The BPF scheduler has no 1809 * claim on this task. 1810 * 1811 * - %SCX_OPSS_QUEUEING: 1812 * Transitional state while transferring a task from the SCX core to 1813 * the BPF scheduler. The task's rq lock is held during this state. 1814 * Since QUEUEING is both entered and exited under the rq lock, dequeue 1815 * can never observe this state (it would be a BUG). When finishing a 1816 * dispatch, if the task is still in %SCX_OPSS_QUEUEING the completion 1817 * path busy-waits for it to leave this state (via wait_ops_state()) 1818 * before retrying. 1819 * 1820 * - %SCX_OPSS_QUEUED: 1821 * Task is owned by the BPF scheduler. It's on a DSQ (dispatch queue) 1822 * and the BPF scheduler is responsible for dispatching it. A QSEQ 1823 * (queue sequence number) is embedded in this state to detect 1824 * dispatch/dequeue races: if a task is dequeued and re-enqueued, the 1825 * QSEQ changes and any in-flight dispatch operations targeting the old 1826 * QSEQ are safely ignored. 1827 * 1828 * - %SCX_OPSS_DISPATCHING: 1829 * Transitional state while transferring a task from the BPF scheduler 1830 * back to the SCX core. This state indicates the BPF scheduler has 1831 * selected the task for execution. When dequeue needs to take the task 1832 * off a DSQ and it is still in %SCX_OPSS_DISPATCHING, the dequeue path 1833 * busy-waits for it to leave this state (via wait_ops_state()) before 1834 * proceeding. Exits to %SCX_OPSS_NONE when dispatch completes. 1835 * 1836 * Memory Ordering 1837 * 1838 * Transitions out of %SCX_OPSS_QUEUEING and %SCX_OPSS_DISPATCHING into 1839 * %SCX_OPSS_NONE or %SCX_OPSS_QUEUED must use atomic_long_set_release() 1840 * and waiters must use atomic_long_read_acquire(). This ensures proper 1841 * synchronization between concurrent operations. 1842 * 1843 * Cross-CPU Task Migration 1844 * 1845 * When moving a task in the %SCX_OPSS_DISPATCHING state, we can't simply 1846 * grab the target CPU's rq lock because a concurrent dequeue might be 1847 * waiting on %SCX_OPSS_DISPATCHING while holding the source rq lock 1848 * (deadlock). 1849 * 1850 * The sched_ext core uses a "lock dancing" protocol coordinated by 1851 * p->scx.holding_cpu. When moving a task to a different rq: 1852 * 1853 * 1. Set p->scx.holding_cpu to the current CPU 1854 * 2. Set task state to %SCX_OPSS_NONE; dequeue waits while DISPATCHING 1855 * is set, so clearing DISPATCHING first prevents the circular wait 1856 * (safe to lock the rq we need) 1857 * 3. Unlock the current CPU's rq 1858 * 4. Lock src_rq (where the task currently lives) 1859 * 5. Verify p->scx.holding_cpu == current CPU, if not, dequeue won the 1860 * race (dequeue clears holding_cpu to -1 when it takes the task), in 1861 * this case migration is aborted 1862 * 6. If src_rq == dst_rq: clear holding_cpu and enqueue directly 1863 * into dst_rq's local DSQ (no lock swap needed) 1864 * 7. Otherwise, verify under src_rq lock that the task can be moved to dst_rq 1865 * (CPU affinity, migration_disabled, etc.). If not, clear holding_cpu, 1866 * leave the task on src_rq, and enqueue it on the fallback DSQ. 1867 * 8. Otherwise (i.e. if the task can be moved to dst_rq), call 1868 * move_remote_task_to_local_dsq(), which releases src_rq, locks dst_rq, 1869 * and performs the deactivate/activate migration cycle 1870 * (dst_rq is held on return) 1871 * 9. Unlock dst_rq and re-lock the current CPU's rq to restore 1872 * the lock state expected by the caller 1873 * 1874 * If any verification fails, abort the migration. 1875 * 1876 * This state tracking allows the BPF scheduler to try to dispatch any task 1877 * at any time regardless of its state. The SCX core can safely 1878 * reject/ignore invalid dispatches, simplifying the BPF scheduler 1879 * implementation. 1880 */ 1881 enum scx_ops_state { 1882 SCX_OPSS_NONE, /* owned by the SCX core */ 1883 SCX_OPSS_QUEUEING, /* in transit to the BPF scheduler */ 1884 SCX_OPSS_QUEUED, /* owned by the BPF scheduler */ 1885 SCX_OPSS_DISPATCHING, /* in transit back to the SCX core */ 1886 1887 /* 1888 * QSEQ brands each QUEUED instance so that, when dispatch races 1889 * dequeue/requeue, the dispatcher can tell whether it still has a claim 1890 * on the task being dispatched. 1891 * 1892 * As some 32bit archs can't do 64bit store_release/load_acquire, 1893 * p->scx.ops_state is atomic_long_t which leaves 30 bits for QSEQ on 1894 * 32bit machines. The dispatch race window QSEQ protects is very narrow 1895 * and runs with IRQ disabled. 30 bits should be sufficient. 1896 */ 1897 SCX_OPSS_QSEQ_SHIFT = 2, 1898 }; 1899 1900 /* Use macros to ensure that the type is unsigned long for the masks */ 1901 #define SCX_OPSS_STATE_MASK ((1LU << SCX_OPSS_QSEQ_SHIFT) - 1) 1902 #define SCX_OPSS_QSEQ_MASK (~SCX_OPSS_STATE_MASK) 1903 1904 /* 1905 * SCX task iterator. 1906 */ 1907 struct scx_task_iter { 1908 struct sched_ext_entity cursor; 1909 struct task_struct *locked_task; 1910 struct rq *rq; 1911 struct rq_flags rf; 1912 u32 cnt; 1913 bool list_locked; 1914 #ifdef CONFIG_EXT_SUB_SCHED 1915 struct cgroup *cgrp; 1916 struct cgroup_subsys_state *css_pos; 1917 struct css_task_iter css_iter; 1918 #endif 1919 }; 1920 1921 /* 1922 * scx_enable() is offloaded to a dedicated system-wide RT kthread to avoid 1923 * starvation. During the READY -> ENABLED task switching loop, the calling 1924 * thread's sched_class gets switched from fair to ext. As fair has higher 1925 * priority than ext, the calling thread can be indefinitely starved under 1926 * fair-class saturation, leading to a system hang. 1927 */ 1928 struct scx_enable_cmd { 1929 struct kthread_work work; 1930 union { 1931 struct sched_ext_ops *ops; 1932 struct sched_ext_ops_cid *ops_cid; 1933 }; 1934 bool is_cid_type; 1935 struct bpf_map *arena_map; /* arena ref to transfer to sch */ 1936 int ret; 1937 }; 1938 1939 /* string formatting from BPF */ 1940 struct scx_bstr_buf { 1941 u64 data[MAX_BPRINTF_VARARGS]; 1942 char line[SCX_EXIT_MSG_LEN]; 1943 }; 1944 1945 extern struct scx_sched __rcu *scx_root; 1946 DECLARE_PER_CPU(struct rq *, scx_locked_rq_state); 1947 1948 /* 1949 * True when the currently loaded scheduler hierarchy is cid-form. All scheds 1950 * in a hierarchy share one form, so this single key tells callsites which 1951 * view to use without per-sch dereferences. Use scx_is_cid_type() to test. 1952 */ 1953 DECLARE_STATIC_KEY_FALSE(__scx_is_cid_type); 1954 1955 int scx_kfunc_context_filter(const struct bpf_prog *prog, u32 kfunc_id); 1956 1957 bool scx_cpu_valid(struct scx_sched *sch, s32 cpu, const char *where); 1958 1959 __printf(5, 0) bool scx_vexit(struct scx_sched *sch, enum scx_exit_kind kind, 1960 s64 exit_code, s32 exit_cpu, const char *fmt, 1961 va_list args); 1962 __printf(5, 6) bool __scx_exit(struct scx_sched *sch, enum scx_exit_kind kind, 1963 s64 exit_code, s32 exit_cpu, const char *fmt, ...); 1964 1965 u32 scx_get_task_state(const struct task_struct *p); 1966 void scx_set_task_state(struct task_struct *p, u32 state); 1967 void scx_task_iter_start(struct scx_task_iter *iter, struct cgroup *cgrp); 1968 void scx_task_iter_unlock(struct scx_task_iter *iter); 1969 void scx_task_iter_stop(struct scx_task_iter *iter); 1970 struct task_struct *scx_task_iter_next_locked(struct scx_task_iter *iter); 1971 void scx_dispatch_dequeue(struct rq *rq, struct task_struct *p); 1972 void scx_do_enqueue_task(struct rq *rq, struct task_struct *p, u64 enq_flags, 1973 int sticky_cpu); 1974 bool scx_consume_dispatch_q(struct scx_sched *sch, struct rq *rq, 1975 struct scx_dispatch_q *dsq, u64 enq_flags); 1976 bool scx_consume_global_dsq(struct scx_sched *sch, struct rq *rq); 1977 bool scx_rq_online(struct rq *rq); 1978 void scx_flush_dispatch_buf(struct scx_sched *sch, struct rq *rq); 1979 void scx_kick_cpu(struct scx_sched *sch, s32 cpu, u64 flags); 1980 void schedule_dsq_reenq(struct scx_sched *sch, struct scx_dispatch_q *dsq, 1981 u64 reenq_flags, struct rq *locked_rq); 1982 int __scx_init_task(struct scx_sched *sch, struct task_struct *p, 1983 struct cgroup *cgrp, bool fork); 1984 void scx_enable_task(struct scx_sched *sch, struct task_struct *p); 1985 void __scx_disable_and_exit_task(struct scx_sched *sch, struct task_struct *p); 1986 void scx_sub_init_cancel_task(struct scx_sched *sch, struct task_struct *p); 1987 void scx_disable_and_exit_task(struct scx_sched *sch, struct task_struct *p); 1988 #if defined(CONFIG_EXT_GROUP_SCHED) || defined(CONFIG_EXT_SUB_SCHED) 1989 void scx_cgroup_lock(void); 1990 void scx_cgroup_unlock(void); 1991 #endif 1992 s32 scx_set_cmask_scratch_alloc(struct scx_sched *sch); 1993 void scx_disable_bypass_dsp(struct scx_sched *sch); 1994 void scx_bypass(struct scx_sched *sch, bool bypass); 1995 s32 scx_link_sched(struct scx_sched *sch); 1996 void scx_unlink_sched(struct scx_sched *sch); 1997 void scx_disable_dump(struct scx_sched *sch); 1998 void scx_log_sched_disable(struct scx_sched *sch); 1999 void scx_flush_disable_work(struct scx_sched *sch); 2000 struct scx_sched *scx_alloc_and_add_sched(struct scx_enable_cmd *cmd, 2001 struct cgroup *cgrp, 2002 struct scx_sched *parent); 2003 int scx_validate_ops(struct scx_sched *sch, const struct sched_ext_ops *ops); 2004 int scx_sched_sysfs_add(struct scx_sched *sch); 2005 bool scx_is_descendant(struct scx_sched *sch, struct scx_sched *ancestor); 2006 __printf(5, 0) bool scx_exit_bstr(struct scx_sched *sch, enum scx_exit_kind kind, 2007 s64 exit_code, struct scx_sched *fmt_blame, 2008 char *fmt, unsigned long long *data, u32 data__sz); 2009 2010 extern raw_spinlock_t scx_sched_lock; 2011 extern struct mutex scx_enable_mutex; 2012 extern struct percpu_rw_semaphore scx_fork_rwsem; 2013 extern bool scx_cgroup_enabled; 2014 #ifdef CONFIG_EXT_SUB_SCHED 2015 extern const struct rhashtable_params scx_sched_hash_params; 2016 extern struct rhashtable scx_sched_hash; 2017 extern struct scx_sched *scx_enabling_sub_sched; 2018 #endif 2019 2020 #define scx_exit(sch, kind, exit_code, fmt, args...) \ 2021 __scx_exit(sch, kind, exit_code, raw_smp_processor_id(), fmt, ##args) 2022 #define scx_error(sch, fmt, args...) \ 2023 scx_exit((sch), SCX_EXIT_ERROR, 0, fmt, ##args) 2024 2025 /** 2026 * scx_root_protected_live - Root sched for paths that only run while live 2027 * 2028 * scx_root is published before the scheduler goes live and cleared only after 2029 * it is fully drained, so a path that only executes while the scheduler is live 2030 * can never race an update. Return the root sched with a plain load, never 2031 * %NULL. 2032 */ 2033 static inline struct scx_sched *scx_root_protected_live(void) 2034 { 2035 return rcu_dereference_protected(scx_root, true); 2036 } 2037 2038 /** 2039 * scx_root_protected - Root sched for contexts that exclude its updates 2040 * 2041 * Both scx_root updates run under the locks checked below, so holding one 2042 * excludes them. Return the root sched with a plain load, %NULL if no scheduler 2043 * is loaded. 2044 */ 2045 static inline struct scx_sched *scx_root_protected(void) 2046 { 2047 return rcu_dereference_protected(scx_root, 2048 lockdep_is_cpus_held() || 2049 lockdep_is_held(&scx_enable_mutex)); 2050 } 2051 2052 static inline struct scx_dispatch_q *scx_bypass_dsq(struct scx_sched *sch, s32 cpu) 2053 { 2054 return &per_cpu_ptr(sch->pcpu, cpu)->bypass_dsq; 2055 } 2056 2057 /** 2058 * scx_bypass_dsp_enabled - Check if bypass dispatch path is enabled 2059 * @sch: scheduler to check 2060 * 2061 * When a descendant scheduler enters bypass mode, bypassed tasks are scheduled 2062 * by the nearest non-bypassing ancestor, or the root scheduler if all ancestors 2063 * are bypassing. In the former case, the ancestor is not itself bypassing but 2064 * its bypass DSQs will be populated with bypassed tasks from descendants. Thus, 2065 * the ancestor's bypass dispatch path must be active even though its own 2066 * bypass_depth remains zero. 2067 * 2068 * This function checks bypass_dsp_enable_depth which is managed separately from 2069 * bypass_depth to enable this decoupling. See enable_bypass_dsp() and 2070 * scx_disable_bypass_dsp(). 2071 */ 2072 static inline bool scx_bypass_dsp_enabled(struct scx_sched *sch) 2073 { 2074 return unlikely(atomic_read(&sch->bypass_dsp_enable_depth)); 2075 } 2076 2077 /** 2078 * scx_ops_sanitize_err - Sanitize a -errno value 2079 * @sch: scx_sched to error out on error 2080 * @ops_name: operation to blame on failure 2081 * @err: -errno value to sanitize 2082 * 2083 * Verify @err is a valid -errno. If not, trigger scx_error() and return 2084 * -%EPROTO. This is necessary because returning a rogue -errno up the chain can 2085 * cause misbehaviors. For an example, a large negative return from 2086 * ops.init_task() triggers an oops when passed up the call chain because the 2087 * value fails IS_ERR() test after being encoded with ERR_PTR() and then is 2088 * handled as a pointer. 2089 */ 2090 static inline int scx_ops_sanitize_err(struct scx_sched *sch, const char *ops_name, s32 err) 2091 { 2092 if (err < 0 && err >= -MAX_ERRNO) 2093 return err; 2094 2095 scx_error(sch, "ops.%s() returned an invalid errno %d", ops_name, err); 2096 return -EPROTO; 2097 } 2098 2099 static inline void scx_schedule_reenq_local(struct rq *rq, u64 reenq_flags) 2100 { 2101 struct scx_sched *root = rcu_dereference_sched(scx_root); 2102 2103 if (WARN_ON_ONCE(!root)) 2104 return; 2105 2106 schedule_dsq_reenq(root, &rq->scx.local_dsq, reenq_flags, rq); 2107 } 2108 2109 /* 2110 * Return the rq currently locked from an scx callback, or NULL if no rq is 2111 * locked. 2112 */ 2113 static inline struct rq *scx_locked_rq(void) 2114 { 2115 return __this_cpu_read(scx_locked_rq_state); 2116 } 2117 2118 static inline void update_locked_rq(struct rq *rq) 2119 { 2120 /* 2121 * Check whether @rq is actually locked. This can help expose bugs 2122 * or incorrect assumptions about the context in which a kfunc or 2123 * callback is executed. 2124 */ 2125 if (rq) 2126 lockdep_assert_rq_held(rq); 2127 __this_cpu_write(scx_locked_rq_state, rq); 2128 } 2129 2130 #define SCX_HAS_OP(sch, op) test_bit(SCX_OP_IDX(op), (sch)->has_op) 2131 2132 /* 2133 * SCX ops can recurse via scx_bpf_sub_dispatch() - the inner call must not 2134 * clobber the outer's scx_locked_rq_state. Save it on entry, restore on exit. 2135 * 2136 * @ops is the ops table to dispatch through: ops for the cpu form, ops_cid 2137 * for the cid form. 2138 */ 2139 #define __SCX_CALL_OP(sch, ops, op, locked_rq, args...) \ 2140 do { \ 2141 struct rq *__prev_locked_rq; \ 2142 \ 2143 if (locked_rq) { \ 2144 __prev_locked_rq = scx_locked_rq(); \ 2145 update_locked_rq(locked_rq); \ 2146 } \ 2147 (sch)->ops.op(args); \ 2148 if (locked_rq) \ 2149 update_locked_rq(__prev_locked_rq); \ 2150 } while (0) 2151 2152 #define SCX_CALL_OP(sch, op, locked_rq, args...) \ 2153 __SCX_CALL_OP(sch, ops, op, locked_rq, ##args) 2154 2155 #define SCX_CALL_OP_RET(sch, op, locked_rq, args...) \ 2156 ({ \ 2157 struct rq *__prev_locked_rq; \ 2158 __typeof__((sch)->ops.op(args)) __ret; \ 2159 \ 2160 if (locked_rq) { \ 2161 __prev_locked_rq = scx_locked_rq(); \ 2162 update_locked_rq(locked_rq); \ 2163 } \ 2164 __ret = (sch)->ops.op(args); \ 2165 if (locked_rq) \ 2166 update_locked_rq(__prev_locked_rq); \ 2167 __ret; \ 2168 }) 2169 2170 /* 2171 * SCX_CALL_OP_TASK*() invokes an SCX op that takes one or two task arguments 2172 * and records them in current->scx.kf_tasks[] for the duration of the call. A 2173 * kfunc invoked from inside such an op can then use 2174 * scx_kf_arg_task_ok() to verify that its task argument is one of 2175 * those subject tasks. 2176 * 2177 * Every SCX_CALL_OP_TASK*() call site invokes its op with @p's rq lock held - 2178 * either via the @locked_rq argument here, or (for ops.select_cpu()) via @p's 2179 * pi_lock held by try_to_wake_up() with rq tracking via scx_rq.in_select_cpu. 2180 * So if kf_tasks[] is set, @p's scheduler-protected fields are stable. 2181 * 2182 * kf_tasks[] can not stack, so task-based SCX ops must not nest. The 2183 * WARN_ON_ONCE() in each macro catches a re-entry of any of the three variants 2184 * while a previous one is still in progress. 2185 */ 2186 #define __SCX_CALL_OP_TASK(sch, ops, op, locked_rq, task, args...) \ 2187 do { \ 2188 WARN_ON_ONCE(current->scx.kf_tasks[0]); \ 2189 current->scx.kf_tasks[0] = task; \ 2190 __SCX_CALL_OP((sch), ops, op, locked_rq, task, ##args); \ 2191 current->scx.kf_tasks[0] = NULL; \ 2192 } while (0) 2193 2194 /* 2195 * A per-task op runs on @task's owner - WARN if @sch isn't it. Sites that must 2196 * target a different scheduler call __SCX_CALL_OP_TASK() directly. 2197 */ 2198 #define SCX_CALL_OP_TASK(sch, op, locked_rq, task, args...) \ 2199 do { \ 2200 WARN_ON_ONCE(scx_has_subs() && (sch) != scx_task_sched_rcu(task)); \ 2201 __SCX_CALL_OP_TASK((sch), ops, op, locked_rq, task, ##args); \ 2202 } while (0) 2203 2204 /* 2205 * Dispatch a task op through the cid-form ops_cid table. Only set_cmask() needs 2206 * this: it takes an arena cmask address instead of a cpumask, so it cannot be 2207 * invoked via its cpu-form set_cpumask() slot. 2208 */ 2209 #define SCX_CALL_CID_OP_TASK(sch, op, locked_rq, task, args...) \ 2210 __SCX_CALL_OP_TASK(sch, ops_cid, op, locked_rq, task, ##args) 2211 2212 #define SCX_CALL_OP_TASK_RET(sch, op, locked_rq, task, args...) \ 2213 ({ \ 2214 __typeof__((sch)->ops.op(task, ##args)) __ret; \ 2215 WARN_ON_ONCE(scx_has_subs() && (sch) != scx_task_sched_rcu(task)); \ 2216 WARN_ON_ONCE(current->scx.kf_tasks[0]); \ 2217 current->scx.kf_tasks[0] = task; \ 2218 __ret = SCX_CALL_OP_RET((sch), op, locked_rq, task, ##args); \ 2219 current->scx.kf_tasks[0] = NULL; \ 2220 __ret; \ 2221 }) 2222 2223 #define SCX_CALL_OP_2TASKS_RET(sch, op, locked_rq, task0, task1, args...) \ 2224 ({ \ 2225 __typeof__((sch)->ops.op(task0, task1, ##args)) __ret; \ 2226 WARN_ON_ONCE(current->scx.kf_tasks[0]); \ 2227 current->scx.kf_tasks[0] = task0; \ 2228 current->scx.kf_tasks[1] = task1; \ 2229 __ret = SCX_CALL_OP_RET((sch), op, locked_rq, task0, task1, ##args); \ 2230 current->scx.kf_tasks[0] = NULL; \ 2231 current->scx.kf_tasks[1] = NULL; \ 2232 __ret; \ 2233 }) 2234 2235 /* see SCX_CALL_OP_TASK() */ 2236 static __always_inline bool scx_kf_arg_task_ok(struct scx_sched *sch, 2237 struct task_struct *p) 2238 { 2239 if (unlikely((p != current->scx.kf_tasks[0] && 2240 p != current->scx.kf_tasks[1]))) { 2241 scx_error(sch, "called on a task not being operated on"); 2242 return false; 2243 } 2244 2245 return true; 2246 } 2247 2248 static inline bool scx_bypassing(struct scx_sched *sch, s32 cpu) 2249 { 2250 return unlikely(per_cpu_ptr(sch->pcpu, cpu)->flags & 2251 SCX_SCHED_PCPU_BYPASSING); 2252 } 2253 2254 #ifdef CONFIG_EXT_SUB_SCHED 2255 DECLARE_STATIC_KEY_FALSE(__scx_has_subs); 2256 2257 /** 2258 * scx_has_subs - Whether any sub-scheduler exists 2259 * 2260 * Gates the sub-sched portions of hot paths so that a root-only system doesn't 2261 * pay for them. See scx_sub_enable_workfn() and scx_sched_free_rcu_work(). 2262 */ 2263 static inline bool scx_has_subs(void) 2264 { 2265 return static_branch_unlikely(&__scx_has_subs); 2266 } 2267 2268 /** 2269 * scx_task_sched - Find scx_sched scheduling a task 2270 * @p: task of interest 2271 * 2272 * Return @p's scheduler instance. Must be called with @p's pi_lock or rq lock 2273 * held. 2274 */ 2275 static inline struct scx_sched *scx_task_sched(const struct task_struct *p) 2276 { 2277 return rcu_dereference_protected(p->scx.sched, 2278 lockdep_is_held(&p->pi_lock) || 2279 lockdep_is_held(__rq_lockp(task_rq(p)))); 2280 } 2281 2282 /** 2283 * scx_task_sched_rcu - Find scx_sched scheduling a task 2284 * @p: task of interest 2285 * 2286 * Return @p's scheduler instance. The returned scx_sched is RCU protected. 2287 */ 2288 static inline struct scx_sched *scx_task_sched_rcu(const struct task_struct *p) 2289 { 2290 return rcu_dereference_all(p->scx.sched); 2291 } 2292 2293 /** 2294 * scx_task_on_sched - Is a task on the specified sched? 2295 * @sch: sched to test against 2296 * @p: task of interest 2297 * 2298 * Returns %true if @p is on @sch, %false otherwise. 2299 */ 2300 static inline bool scx_task_on_sched(struct scx_sched *sch, 2301 const struct task_struct *p) 2302 { 2303 return rcu_access_pointer(p->scx.sched) == sch; 2304 } 2305 2306 /** 2307 * scx_prog_sched - Find scx_sched associated with a BPF prog 2308 * @aux: aux passed in from BPF to a kfunc 2309 * 2310 * To be called from kfuncs. Return the scheduler instance associated with the 2311 * BPF program given the implicit kfunc argument aux. The returned scx_sched is 2312 * RCU protected. 2313 */ 2314 static inline struct scx_sched *scx_prog_sched(const struct bpf_prog_aux *aux) 2315 { 2316 struct sched_ext_ops *ops; 2317 struct scx_sched *sch, *root; 2318 2319 ops = bpf_prog_get_assoc_struct_ops(aux); 2320 if (likely(ops)) { 2321 sch = rcu_dereference_all(ops->priv); 2322 if (sch && unlikely(READ_ONCE(sch->dead))) 2323 return NULL; 2324 return sch; 2325 } 2326 2327 root = rcu_dereference_all(scx_root); 2328 if (root) { 2329 if (unlikely(READ_ONCE(root->dead))) 2330 return NULL; 2331 /* 2332 * COMPAT-v6.19: Schedulers built before sub-sched support was 2333 * introduced may have unassociated non-struct_ops programs. 2334 */ 2335 if (!root->ops.sub_attach) 2336 return root; 2337 2338 if (!root->warned_unassoc_progs) { 2339 printk_deferred(KERN_WARNING "sched_ext: Unassociated program %s (id %d)\n", 2340 aux->name, aux->id); 2341 root->warned_unassoc_progs = true; 2342 } 2343 } 2344 2345 return NULL; 2346 } 2347 2348 /** 2349 * scx_parent - Find the parent sched 2350 * @sch: sched to find the parent of 2351 * 2352 * Returns the parent scheduler or %NULL if @sch is root. 2353 */ 2354 static inline struct scx_sched *scx_parent(struct scx_sched *sch) 2355 { 2356 if (sch->level) 2357 return sch->ancestors[sch->level - 1]; 2358 else 2359 return NULL; 2360 } 2361 #else /* CONFIG_EXT_SUB_SCHED */ 2362 static inline bool scx_has_subs(void) { return false; } 2363 2364 static inline struct scx_sched *scx_task_sched(const struct task_struct *p) 2365 { 2366 return rcu_dereference_protected(scx_root, 2367 lockdep_is_held(&p->pi_lock) || 2368 lockdep_is_held(__rq_lockp(task_rq(p)))); 2369 } 2370 2371 static inline struct scx_sched *scx_task_sched_rcu(const struct task_struct *p) 2372 { 2373 return rcu_dereference_all(scx_root); 2374 } 2375 2376 static inline bool scx_task_on_sched(struct scx_sched *sch, 2377 const struct task_struct *p) 2378 { 2379 return true; 2380 } 2381 2382 static inline struct scx_sched *scx_prog_sched(const struct bpf_prog_aux *aux) 2383 { 2384 struct scx_sched *root = rcu_dereference_all(scx_root); 2385 2386 if (root && unlikely(READ_ONCE(root->dead))) 2387 return NULL; 2388 return root; 2389 } 2390 2391 static inline struct scx_sched *scx_parent(struct scx_sched *sch) { return NULL; } 2392 #endif /* CONFIG_EXT_SUB_SCHED */ 2393 2394 #endif /* _KERNEL_SCHED_EXT_INTERNAL_H */ 2395