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 #define SCX_OP_IDX(op) (offsetof(struct sched_ext_ops, op) / sizeof(void (*)(void))) 9 10 enum scx_consts { 11 SCX_DSP_DFL_MAX_BATCH = 32, 12 SCX_DSP_MAX_LOOPS = 32, 13 SCX_WATCHDOG_MAX_TIMEOUT = 30 * HZ, 14 15 SCX_EXIT_BT_LEN = 64, 16 SCX_EXIT_MSG_LEN = 1024, 17 SCX_EXIT_DUMP_DFL_LEN = 32768, 18 19 SCX_CPUPERF_ONE = SCHED_CAPACITY_SCALE, 20 21 /* 22 * Iterating all tasks may take a while. Periodically drop 23 * scx_tasks_lock to avoid causing e.g. CSD and RCU stalls. 24 */ 25 SCX_TASK_ITER_BATCH = 32, 26 27 SCX_BYPASS_HOST_NTH = 2, 28 29 SCX_BYPASS_LB_DFL_INTV_US = 500 * USEC_PER_MSEC, 30 SCX_BYPASS_LB_DONOR_PCT = 125, 31 SCX_BYPASS_LB_MIN_DELTA_DIV = 4, 32 SCX_BYPASS_LB_BATCH = 256, 33 34 SCX_REENQ_LOCAL_MAX_REPEAT = 256, 35 36 SCX_SUB_MAX_DEPTH = 4, 37 }; 38 39 enum scx_exit_kind { 40 SCX_EXIT_NONE, 41 SCX_EXIT_DONE, 42 43 SCX_EXIT_UNREG = 64, /* user-space initiated unregistration */ 44 SCX_EXIT_UNREG_BPF, /* BPF-initiated unregistration */ 45 SCX_EXIT_UNREG_KERN, /* kernel-initiated unregistration */ 46 SCX_EXIT_SYSRQ, /* requested by 'S' sysrq */ 47 SCX_EXIT_PARENT, /* parent exiting */ 48 49 SCX_EXIT_ERROR = 1024, /* runtime error, error msg contains details */ 50 SCX_EXIT_ERROR_BPF, /* ERROR but triggered through scx_bpf_error() */ 51 SCX_EXIT_ERROR_STALL, /* watchdog detected stalled runnable tasks */ 52 }; 53 54 /* 55 * An exit code can be specified when exiting with scx_bpf_exit() or scx_exit(), 56 * corresponding to exit_kind UNREG_BPF and UNREG_KERN respectively. The codes 57 * are 64bit of the format: 58 * 59 * Bits: [63 .. 48 47 .. 32 31 .. 0] 60 * [ SYS ACT ] [ SYS RSN ] [ USR ] 61 * 62 * SYS ACT: System-defined exit actions 63 * SYS RSN: System-defined exit reasons 64 * USR : User-defined exit codes and reasons 65 * 66 * Using the above, users may communicate intention and context by ORing system 67 * actions and/or system reasons with a user-defined exit code. 68 */ 69 enum scx_exit_code { 70 /* Reasons */ 71 SCX_ECODE_RSN_HOTPLUG = 1LLU << 32, 72 SCX_ECODE_RSN_CGROUP_OFFLINE = 2LLU << 32, 73 74 /* Actions */ 75 SCX_ECODE_ACT_RESTART = 1LLU << 48, 76 }; 77 78 enum scx_exit_flags { 79 /* 80 * ops.exit() may be called even if the loading failed before ops.init() 81 * finishes successfully. This is because ops.exit() allows rich exit 82 * info communication. The following flag indicates whether ops.init() 83 * finished successfully. 84 */ 85 SCX_EFLAG_INITIALIZED = 1LLU << 0, 86 }; 87 88 /* 89 * scx_exit_info is passed to ops.exit() to describe why the BPF scheduler is 90 * being disabled. 91 */ 92 struct scx_exit_info { 93 /* %SCX_EXIT_* - broad category of the exit reason */ 94 enum scx_exit_kind kind; 95 96 /* exit code if gracefully exiting */ 97 s64 exit_code; 98 99 /* %SCX_EFLAG_* */ 100 u64 flags; 101 102 /* textual representation of the above */ 103 const char *reason; 104 105 /* backtrace if exiting due to an error */ 106 unsigned long *bt; 107 u32 bt_len; 108 109 /* informational message */ 110 char *msg; 111 112 /* debug dump */ 113 char *dump; 114 }; 115 116 /* sched_ext_ops.flags */ 117 enum scx_ops_flags { 118 /* 119 * Keep built-in idle tracking even if ops.update_idle() is implemented. 120 */ 121 SCX_OPS_KEEP_BUILTIN_IDLE = 1LLU << 0, 122 123 /* 124 * By default, if there are no other task to run on the CPU, ext core 125 * keeps running the current task even after its slice expires. If this 126 * flag is specified, such tasks are passed to ops.enqueue() with 127 * %SCX_ENQ_LAST. See the comment above %SCX_ENQ_LAST for more info. 128 */ 129 SCX_OPS_ENQ_LAST = 1LLU << 1, 130 131 /* 132 * An exiting task may schedule after PF_EXITING is set. In such cases, 133 * bpf_task_from_pid() may not be able to find the task and if the BPF 134 * scheduler depends on pid lookup for dispatching, the task will be 135 * lost leading to various issues including RCU grace period stalls. 136 * 137 * To mask this problem, by default, unhashed tasks are automatically 138 * dispatched to the local DSQ on enqueue. If the BPF scheduler doesn't 139 * depend on pid lookups and wants to handle these tasks directly, the 140 * following flag can be used. 141 */ 142 SCX_OPS_ENQ_EXITING = 1LLU << 2, 143 144 /* 145 * If set, only tasks with policy set to SCHED_EXT are attached to 146 * sched_ext. If clear, SCHED_NORMAL tasks are also included. 147 */ 148 SCX_OPS_SWITCH_PARTIAL = 1LLU << 3, 149 150 /* 151 * A migration disabled task can only execute on its current CPU. By 152 * default, such tasks are automatically put on the CPU's local DSQ with 153 * the default slice on enqueue. If this ops flag is set, they also go 154 * through ops.enqueue(). 155 * 156 * A migration disabled task never invokes ops.select_cpu() as it can 157 * only select the current CPU. Also, p->cpus_ptr will only contain its 158 * current CPU while p->nr_cpus_allowed keeps tracking p->user_cpus_ptr 159 * and thus may disagree with cpumask_weight(p->cpus_ptr). 160 */ 161 SCX_OPS_ENQ_MIGRATION_DISABLED = 1LLU << 4, 162 163 /* 164 * Queued wakeup (ttwu_queue) is a wakeup optimization that invokes 165 * ops.enqueue() on the ops.select_cpu() selected or the wakee's 166 * previous CPU via IPI (inter-processor interrupt) to reduce cacheline 167 * transfers. When this optimization is enabled, ops.select_cpu() is 168 * skipped in some cases (when racing against the wakee switching out). 169 * As the BPF scheduler may depend on ops.select_cpu() being invoked 170 * during wakeups, queued wakeup is disabled by default. 171 * 172 * If this ops flag is set, queued wakeup optimization is enabled and 173 * the BPF scheduler must be able to handle ops.enqueue() invoked on the 174 * wakee's CPU without preceding ops.select_cpu() even for tasks which 175 * may be executed on multiple CPUs. 176 */ 177 SCX_OPS_ALLOW_QUEUED_WAKEUP = 1LLU << 5, 178 179 /* 180 * If set, enable per-node idle cpumasks. If clear, use a single global 181 * flat idle cpumask. 182 */ 183 SCX_OPS_BUILTIN_IDLE_PER_NODE = 1LLU << 6, 184 185 /* 186 * If set, %SCX_ENQ_IMMED is assumed to be set on all local DSQ 187 * enqueues. 188 */ 189 SCX_OPS_ALWAYS_ENQ_IMMED = 1LLU << 7, 190 191 SCX_OPS_ALL_FLAGS = SCX_OPS_KEEP_BUILTIN_IDLE | 192 SCX_OPS_ENQ_LAST | 193 SCX_OPS_ENQ_EXITING | 194 SCX_OPS_ENQ_MIGRATION_DISABLED | 195 SCX_OPS_ALLOW_QUEUED_WAKEUP | 196 SCX_OPS_SWITCH_PARTIAL | 197 SCX_OPS_BUILTIN_IDLE_PER_NODE | 198 SCX_OPS_ALWAYS_ENQ_IMMED, 199 200 /* high 8 bits are internal, don't include in SCX_OPS_ALL_FLAGS */ 201 __SCX_OPS_INTERNAL_MASK = 0xffLLU << 56, 202 203 SCX_OPS_HAS_CPU_PREEMPT = 1LLU << 56, 204 }; 205 206 /* argument container for ops.init_task() */ 207 struct scx_init_task_args { 208 /* 209 * Set if ops.init_task() is being invoked on the fork path, as opposed 210 * to the scheduler transition path. 211 */ 212 bool fork; 213 #ifdef CONFIG_EXT_GROUP_SCHED 214 /* the cgroup the task is joining */ 215 struct cgroup *cgroup; 216 #endif 217 }; 218 219 /* argument container for ops.exit_task() */ 220 struct scx_exit_task_args { 221 /* Whether the task exited before running on sched_ext. */ 222 bool cancelled; 223 }; 224 225 /* argument container for ops.cgroup_init() */ 226 struct scx_cgroup_init_args { 227 /* the weight of the cgroup [1..10000] */ 228 u32 weight; 229 230 /* bandwidth control parameters from cpu.max and cpu.max.burst */ 231 u64 bw_period_us; 232 u64 bw_quota_us; 233 u64 bw_burst_us; 234 }; 235 236 enum scx_cpu_preempt_reason { 237 /* next task is being scheduled by &sched_class_rt */ 238 SCX_CPU_PREEMPT_RT, 239 /* next task is being scheduled by &sched_class_dl */ 240 SCX_CPU_PREEMPT_DL, 241 /* next task is being scheduled by &sched_class_stop */ 242 SCX_CPU_PREEMPT_STOP, 243 /* unknown reason for SCX being preempted */ 244 SCX_CPU_PREEMPT_UNKNOWN, 245 }; 246 247 /* 248 * Argument container for ops.cpu_acquire(). Currently empty, but may be 249 * expanded in the future. 250 */ 251 struct scx_cpu_acquire_args {}; 252 253 /* argument container for ops.cpu_release() */ 254 struct scx_cpu_release_args { 255 /* the reason the CPU was preempted */ 256 enum scx_cpu_preempt_reason reason; 257 258 /* the task that's going to be scheduled on the CPU */ 259 struct task_struct *task; 260 }; 261 262 /* informational context provided to dump operations */ 263 struct scx_dump_ctx { 264 enum scx_exit_kind kind; 265 s64 exit_code; 266 const char *reason; 267 u64 at_ns; 268 u64 at_jiffies; 269 }; 270 271 /* argument container for ops.sub_attach() */ 272 struct scx_sub_attach_args { 273 struct sched_ext_ops *ops; 274 char *cgroup_path; 275 }; 276 277 /* argument container for ops.sub_detach() */ 278 struct scx_sub_detach_args { 279 struct sched_ext_ops *ops; 280 char *cgroup_path; 281 }; 282 283 /** 284 * struct sched_ext_ops - Operation table for BPF scheduler implementation 285 * 286 * A BPF scheduler can implement an arbitrary scheduling policy by 287 * implementing and loading operations in this table. Note that a userland 288 * scheduling policy can also be implemented using the BPF scheduler 289 * as a shim layer. 290 */ 291 struct sched_ext_ops { 292 /** 293 * @select_cpu: Pick the target CPU for a task which is being woken up 294 * @p: task being woken up 295 * @prev_cpu: the cpu @p was on before sleeping 296 * @wake_flags: SCX_WAKE_* 297 * 298 * Decision made here isn't final. @p may be moved to any CPU while it 299 * is getting dispatched for execution later. However, as @p is not on 300 * the rq at this point, getting the eventual execution CPU right here 301 * saves a small bit of overhead down the line. 302 * 303 * If an idle CPU is returned, the CPU is kicked and will try to 304 * dispatch. While an explicit custom mechanism can be added, 305 * select_cpu() serves as the default way to wake up idle CPUs. 306 * 307 * @p may be inserted into a DSQ directly by calling 308 * scx_bpf_dsq_insert(). If so, the ops.enqueue() will be skipped. 309 * Directly inserting into %SCX_DSQ_LOCAL will put @p in the local DSQ 310 * of the CPU returned by this operation. 311 * 312 * Note that select_cpu() is never called for tasks that can only run 313 * on a single CPU or tasks with migration disabled, as they don't have 314 * the option to select a different CPU. See select_task_rq() for 315 * details. 316 */ 317 s32 (*select_cpu)(struct task_struct *p, s32 prev_cpu, u64 wake_flags); 318 319 /** 320 * @enqueue: Enqueue a task on the BPF scheduler 321 * @p: task being enqueued 322 * @enq_flags: %SCX_ENQ_* 323 * 324 * @p is ready to run. Insert directly into a DSQ by calling 325 * scx_bpf_dsq_insert() or enqueue on the BPF scheduler. If not directly 326 * inserted, the bpf scheduler owns @p and if it fails to dispatch @p, 327 * the task will stall. 328 * 329 * If @p was inserted into a DSQ from ops.select_cpu(), this callback is 330 * skipped. 331 */ 332 void (*enqueue)(struct task_struct *p, u64 enq_flags); 333 334 /** 335 * @dequeue: Remove a task from the BPF scheduler 336 * @p: task being dequeued 337 * @deq_flags: %SCX_DEQ_* 338 * 339 * Remove @p from the BPF scheduler. This is usually called to isolate 340 * the task while updating its scheduling properties (e.g. priority). 341 * 342 * The ext core keeps track of whether the BPF side owns a given task or 343 * not and can gracefully ignore spurious dispatches from BPF side, 344 * which makes it safe to not implement this method. However, depending 345 * on the scheduling logic, this can lead to confusing behaviors - e.g. 346 * scheduling position not being updated across a priority change. 347 */ 348 void (*dequeue)(struct task_struct *p, u64 deq_flags); 349 350 /** 351 * @dispatch: Dispatch tasks from the BPF scheduler and/or user DSQs 352 * @cpu: CPU to dispatch tasks for 353 * @prev: previous task being switched out 354 * 355 * Called when a CPU's local dsq is empty. The operation should dispatch 356 * one or more tasks from the BPF scheduler into the DSQs using 357 * scx_bpf_dsq_insert() and/or move from user DSQs into the local DSQ 358 * using scx_bpf_dsq_move_to_local(). 359 * 360 * The maximum number of times scx_bpf_dsq_insert() can be called 361 * without an intervening scx_bpf_dsq_move_to_local() is specified by 362 * ops.dispatch_max_batch. See the comments on top of the two functions 363 * for more details. 364 * 365 * When not %NULL, @prev is an SCX task with its slice depleted. If 366 * @prev is still runnable as indicated by set %SCX_TASK_QUEUED in 367 * @prev->scx.flags, it is not enqueued yet and will be enqueued after 368 * ops.dispatch() returns. To keep executing @prev, return without 369 * dispatching or moving any tasks. Also see %SCX_OPS_ENQ_LAST. 370 */ 371 void (*dispatch)(s32 cpu, struct task_struct *prev); 372 373 /** 374 * @tick: Periodic tick 375 * @p: task running currently 376 * 377 * This operation is called every 1/HZ seconds on CPUs which are 378 * executing an SCX task. Setting @p->scx.slice to 0 will trigger an 379 * immediate dispatch cycle on the CPU. 380 */ 381 void (*tick)(struct task_struct *p); 382 383 /** 384 * @runnable: A task is becoming runnable on its associated CPU 385 * @p: task becoming runnable 386 * @enq_flags: %SCX_ENQ_* 387 * 388 * This and the following three functions can be used to track a task's 389 * execution state transitions. A task becomes ->runnable() on a CPU, 390 * and then goes through one or more ->running() and ->stopping() pairs 391 * as it runs on the CPU, and eventually becomes ->quiescent() when it's 392 * done running on the CPU. 393 * 394 * @p is becoming runnable on the CPU because it's 395 * 396 * - waking up (%SCX_ENQ_WAKEUP) 397 * - being moved from another CPU 398 * - being restored after temporarily taken off the queue for an 399 * attribute change. 400 * 401 * This and ->enqueue() are related but not coupled. This operation 402 * notifies @p's state transition and may not be followed by ->enqueue() 403 * e.g. when @p is being dispatched to a remote CPU, or when @p is 404 * being enqueued on a CPU experiencing a hotplug event. Likewise, a 405 * task may be ->enqueue()'d without being preceded by this operation 406 * e.g. after exhausting its slice. 407 */ 408 void (*runnable)(struct task_struct *p, u64 enq_flags); 409 410 /** 411 * @running: A task is starting to run on its associated CPU 412 * @p: task starting to run 413 * 414 * Note that this callback may be called from a CPU other than the 415 * one the task is going to run on. This can happen when a task 416 * property is changed (i.e., affinity), since scx_next_task_scx(), 417 * which triggers this callback, may run on a CPU different from 418 * the task's assigned CPU. 419 * 420 * Therefore, always use scx_bpf_task_cpu(@p) to determine the 421 * target CPU the task is going to use. 422 * 423 * See ->runnable() for explanation on the task state notifiers. 424 */ 425 void (*running)(struct task_struct *p); 426 427 /** 428 * @stopping: A task is stopping execution 429 * @p: task stopping to run 430 * @runnable: is task @p still runnable? 431 * 432 * Note that this callback may be called from a CPU other than the 433 * one the task was running on. This can happen when a task 434 * property is changed (i.e., affinity), since dequeue_task_scx(), 435 * which triggers this callback, may run on a CPU different from 436 * the task's assigned CPU. 437 * 438 * Therefore, always use scx_bpf_task_cpu(@p) to retrieve the CPU 439 * the task was running on. 440 * 441 * See ->runnable() for explanation on the task state notifiers. If 442 * !@runnable, ->quiescent() will be invoked after this operation 443 * returns. 444 */ 445 void (*stopping)(struct task_struct *p, bool runnable); 446 447 /** 448 * @quiescent: A task is becoming not runnable on its associated CPU 449 * @p: task becoming not runnable 450 * @deq_flags: %SCX_DEQ_* 451 * 452 * See ->runnable() for explanation on the task state notifiers. 453 * 454 * @p is becoming quiescent on the CPU because it's 455 * 456 * - sleeping (%SCX_DEQ_SLEEP) 457 * - being moved to another CPU 458 * - being temporarily taken off the queue for an attribute change 459 * (%SCX_DEQ_SAVE) 460 * 461 * This and ->dequeue() are related but not coupled. This operation 462 * notifies @p's state transition and may not be preceded by ->dequeue() 463 * e.g. when @p is being dispatched to a remote CPU. 464 */ 465 void (*quiescent)(struct task_struct *p, u64 deq_flags); 466 467 /** 468 * @yield: Yield CPU 469 * @from: yielding task 470 * @to: optional yield target task 471 * 472 * If @to is NULL, @from is yielding the CPU to other runnable tasks. 473 * The BPF scheduler should ensure that other available tasks are 474 * dispatched before the yielding task. Return value is ignored in this 475 * case. 476 * 477 * If @to is not-NULL, @from wants to yield the CPU to @to. If the bpf 478 * scheduler can implement the request, return %true; otherwise, %false. 479 */ 480 bool (*yield)(struct task_struct *from, struct task_struct *to); 481 482 /** 483 * @core_sched_before: Task ordering for core-sched 484 * @a: task A 485 * @b: task B 486 * 487 * Used by core-sched to determine the ordering between two tasks. See 488 * Documentation/admin-guide/hw-vuln/core-scheduling.rst for details on 489 * core-sched. 490 * 491 * Both @a and @b are runnable and may or may not currently be queued on 492 * the BPF scheduler. Should return %true if @a should run before @b. 493 * %false if there's no required ordering or @b should run before @a. 494 * 495 * If not specified, the default is ordering them according to when they 496 * became runnable. 497 */ 498 bool (*core_sched_before)(struct task_struct *a, struct task_struct *b); 499 500 /** 501 * @set_weight: Set task weight 502 * @p: task to set weight for 503 * @weight: new weight [1..10000] 504 * 505 * Update @p's weight to @weight. 506 */ 507 void (*set_weight)(struct task_struct *p, u32 weight); 508 509 /** 510 * @set_cpumask: Set CPU affinity 511 * @p: task to set CPU affinity for 512 * @cpumask: cpumask of cpus that @p can run on 513 * 514 * Update @p's CPU affinity to @cpumask. 515 */ 516 void (*set_cpumask)(struct task_struct *p, 517 const struct cpumask *cpumask); 518 519 /** 520 * @update_idle: Update the idle state of a CPU 521 * @cpu: CPU to update the idle state for 522 * @idle: whether entering or exiting the idle state 523 * 524 * This operation is called when @rq's CPU goes or leaves the idle 525 * state. By default, implementing this operation disables the built-in 526 * idle CPU tracking and the following helpers become unavailable: 527 * 528 * - scx_bpf_select_cpu_dfl() 529 * - scx_bpf_select_cpu_and() 530 * - scx_bpf_test_and_clear_cpu_idle() 531 * - scx_bpf_pick_idle_cpu() 532 * 533 * The user also must implement ops.select_cpu() as the default 534 * implementation relies on scx_bpf_select_cpu_dfl(). 535 * 536 * Specify the %SCX_OPS_KEEP_BUILTIN_IDLE flag to keep the built-in idle 537 * tracking. 538 */ 539 void (*update_idle)(s32 cpu, bool idle); 540 541 /** 542 * @cpu_acquire: A CPU is becoming available to the BPF scheduler 543 * @cpu: The CPU being acquired by the BPF scheduler. 544 * @args: Acquire arguments, see the struct definition. 545 * 546 * A CPU that was previously released from the BPF scheduler is now once 547 * again under its control. 548 */ 549 void (*cpu_acquire)(s32 cpu, struct scx_cpu_acquire_args *args); 550 551 /** 552 * @cpu_release: A CPU is taken away from the BPF scheduler 553 * @cpu: The CPU being released by the BPF scheduler. 554 * @args: Release arguments, see the struct definition. 555 * 556 * The specified CPU is no longer under the control of the BPF 557 * scheduler. This could be because it was preempted by a higher 558 * priority sched_class, though there may be other reasons as well. The 559 * caller should consult @args->reason to determine the cause. 560 */ 561 void (*cpu_release)(s32 cpu, struct scx_cpu_release_args *args); 562 563 /** 564 * @init_task: Initialize a task to run in a BPF scheduler 565 * @p: task to initialize for BPF scheduling 566 * @args: init arguments, see the struct definition 567 * 568 * Either we're loading a BPF scheduler or a new task is being forked. 569 * Initialize @p for BPF scheduling. This operation may block and can 570 * be used for allocations, and is called exactly once for a task. 571 * 572 * Return 0 for success, -errno for failure. An error return while 573 * loading will abort loading of the BPF scheduler. During a fork, it 574 * will abort that specific fork. 575 */ 576 s32 (*init_task)(struct task_struct *p, struct scx_init_task_args *args); 577 578 /** 579 * @exit_task: Exit a previously-running task from the system 580 * @p: task to exit 581 * @args: exit arguments, see the struct definition 582 * 583 * @p is exiting or the BPF scheduler is being unloaded. Perform any 584 * necessary cleanup for @p. 585 */ 586 void (*exit_task)(struct task_struct *p, struct scx_exit_task_args *args); 587 588 /** 589 * @enable: Enable BPF scheduling for a task 590 * @p: task to enable BPF scheduling for 591 * 592 * Enable @p for BPF scheduling. enable() is called on @p any time it 593 * enters SCX, and is always paired with a matching disable(). 594 */ 595 void (*enable)(struct task_struct *p); 596 597 /** 598 * @disable: Disable BPF scheduling for a task 599 * @p: task to disable BPF scheduling for 600 * 601 * @p is exiting, leaving SCX or the BPF scheduler is being unloaded. 602 * Disable BPF scheduling for @p. A disable() call is always matched 603 * with a prior enable() call. 604 */ 605 void (*disable)(struct task_struct *p); 606 607 /** 608 * @dump: Dump BPF scheduler state on error 609 * @ctx: debug dump context 610 * 611 * Use scx_bpf_dump() to generate BPF scheduler specific debug dump. 612 */ 613 void (*dump)(struct scx_dump_ctx *ctx); 614 615 /** 616 * @dump_cpu: Dump BPF scheduler state for a CPU on error 617 * @ctx: debug dump context 618 * @cpu: CPU to generate debug dump for 619 * @idle: @cpu is currently idle without any runnable tasks 620 * 621 * Use scx_bpf_dump() to generate BPF scheduler specific debug dump for 622 * @cpu. If @idle is %true and this operation doesn't produce any 623 * output, @cpu is skipped for dump. 624 */ 625 void (*dump_cpu)(struct scx_dump_ctx *ctx, s32 cpu, bool idle); 626 627 /** 628 * @dump_task: Dump BPF scheduler state for a runnable task on error 629 * @ctx: debug dump context 630 * @p: runnable task to generate debug dump for 631 * 632 * Use scx_bpf_dump() to generate BPF scheduler specific debug dump for 633 * @p. 634 */ 635 void (*dump_task)(struct scx_dump_ctx *ctx, struct task_struct *p); 636 637 #ifdef CONFIG_EXT_GROUP_SCHED 638 /** 639 * @cgroup_init: Initialize a cgroup 640 * @cgrp: cgroup being initialized 641 * @args: init arguments, see the struct definition 642 * 643 * Either the BPF scheduler is being loaded or @cgrp created, initialize 644 * @cgrp for sched_ext. This operation may block. 645 * 646 * Return 0 for success, -errno for failure. An error return while 647 * loading will abort loading of the BPF scheduler. During cgroup 648 * creation, it will abort the specific cgroup creation. 649 */ 650 s32 (*cgroup_init)(struct cgroup *cgrp, 651 struct scx_cgroup_init_args *args); 652 653 /** 654 * @cgroup_exit: Exit a cgroup 655 * @cgrp: cgroup being exited 656 * 657 * Either the BPF scheduler is being unloaded or @cgrp destroyed, exit 658 * @cgrp for sched_ext. This operation my block. 659 */ 660 void (*cgroup_exit)(struct cgroup *cgrp); 661 662 /** 663 * @cgroup_prep_move: Prepare a task to be moved to a different cgroup 664 * @p: task being moved 665 * @from: cgroup @p is being moved from 666 * @to: cgroup @p is being moved to 667 * 668 * Prepare @p for move from cgroup @from to @to. This operation may 669 * block and can be used for allocations. 670 * 671 * Return 0 for success, -errno for failure. An error return aborts the 672 * migration. 673 */ 674 s32 (*cgroup_prep_move)(struct task_struct *p, 675 struct cgroup *from, struct cgroup *to); 676 677 /** 678 * @cgroup_move: Commit cgroup move 679 * @p: task being moved 680 * @from: cgroup @p is being moved from 681 * @to: cgroup @p is being moved to 682 * 683 * Commit the move. @p is dequeued during this operation. 684 */ 685 void (*cgroup_move)(struct task_struct *p, 686 struct cgroup *from, struct cgroup *to); 687 688 /** 689 * @cgroup_cancel_move: Cancel cgroup move 690 * @p: task whose cgroup move is being canceled 691 * @from: cgroup @p was being moved from 692 * @to: cgroup @p was being moved to 693 * 694 * @p was cgroup_prep_move()'d but failed before reaching cgroup_move(). 695 * Undo the preparation. 696 */ 697 void (*cgroup_cancel_move)(struct task_struct *p, 698 struct cgroup *from, struct cgroup *to); 699 700 /** 701 * @cgroup_set_weight: A cgroup's weight is being changed 702 * @cgrp: cgroup whose weight is being updated 703 * @weight: new weight [1..10000] 704 * 705 * Update @cgrp's weight to @weight. 706 */ 707 void (*cgroup_set_weight)(struct cgroup *cgrp, u32 weight); 708 709 /** 710 * @cgroup_set_bandwidth: A cgroup's bandwidth is being changed 711 * @cgrp: cgroup whose bandwidth is being updated 712 * @period_us: bandwidth control period 713 * @quota_us: bandwidth control quota 714 * @burst_us: bandwidth control burst 715 * 716 * Update @cgrp's bandwidth control parameters. This is from the cpu.max 717 * cgroup interface. 718 * 719 * @quota_us / @period_us determines the CPU bandwidth @cgrp is entitled 720 * to. For example, if @period_us is 1_000_000 and @quota_us is 721 * 2_500_000. @cgrp is entitled to 2.5 CPUs. @burst_us can be 722 * interpreted in the same fashion and specifies how much @cgrp can 723 * burst temporarily. The specific control mechanism and thus the 724 * interpretation of @period_us and burstiness is up to the BPF 725 * scheduler. 726 */ 727 void (*cgroup_set_bandwidth)(struct cgroup *cgrp, 728 u64 period_us, u64 quota_us, u64 burst_us); 729 730 /** 731 * @cgroup_set_idle: A cgroup's idle state is being changed 732 * @cgrp: cgroup whose idle state is being updated 733 * @idle: whether the cgroup is entering or exiting idle state 734 * 735 * Update @cgrp's idle state to @idle. This callback is invoked when 736 * a cgroup transitions between idle and non-idle states, allowing the 737 * BPF scheduler to adjust its behavior accordingly. 738 */ 739 void (*cgroup_set_idle)(struct cgroup *cgrp, bool idle); 740 741 #endif /* CONFIG_EXT_GROUP_SCHED */ 742 743 /** 744 * @sub_attach: Attach a sub-scheduler 745 * @args: argument container, see the struct definition 746 * 747 * Return 0 to accept the sub-scheduler. -errno to reject. 748 */ 749 s32 (*sub_attach)(struct scx_sub_attach_args *args); 750 751 /** 752 * @sub_detach: Detach a sub-scheduler 753 * @args: argument container, see the struct definition 754 */ 755 void (*sub_detach)(struct scx_sub_detach_args *args); 756 757 /* 758 * All online ops must come before ops.cpu_online(). 759 */ 760 761 /** 762 * @cpu_online: A CPU became online 763 * @cpu: CPU which just came up 764 * 765 * @cpu just came online. @cpu will not call ops.enqueue() or 766 * ops.dispatch(), nor run tasks associated with other CPUs beforehand. 767 */ 768 void (*cpu_online)(s32 cpu); 769 770 /** 771 * @cpu_offline: A CPU is going offline 772 * @cpu: CPU which is going offline 773 * 774 * @cpu is going offline. @cpu will not call ops.enqueue() or 775 * ops.dispatch(), nor run tasks associated with other CPUs afterwards. 776 */ 777 void (*cpu_offline)(s32 cpu); 778 779 /* 780 * All CPU hotplug ops must come before ops.init(). 781 */ 782 783 /** 784 * @init: Initialize the BPF scheduler 785 */ 786 s32 (*init)(void); 787 788 /** 789 * @exit: Clean up after the BPF scheduler 790 * @info: Exit info 791 * 792 * ops.exit() is also called on ops.init() failure, which is a bit 793 * unusual. This is to allow rich reporting through @info on how 794 * ops.init() failed. 795 */ 796 void (*exit)(struct scx_exit_info *info); 797 798 /* 799 * Data fields must comes after all ops fields. 800 */ 801 802 /** 803 * @dispatch_max_batch: Max nr of tasks that dispatch() can dispatch 804 */ 805 u32 dispatch_max_batch; 806 807 /** 808 * @flags: %SCX_OPS_* flags 809 */ 810 u64 flags; 811 812 /** 813 * @timeout_ms: The maximum amount of time, in milliseconds, that a 814 * runnable task should be able to wait before being scheduled. The 815 * maximum timeout may not exceed the default timeout of 30 seconds. 816 * 817 * Defaults to the maximum allowed timeout value of 30 seconds. 818 */ 819 u32 timeout_ms; 820 821 /** 822 * @exit_dump_len: scx_exit_info.dump buffer length. If 0, the default 823 * value of 32768 is used. 824 */ 825 u32 exit_dump_len; 826 827 /** 828 * @hotplug_seq: A sequence number that may be set by the scheduler to 829 * detect when a hotplug event has occurred during the loading process. 830 * If 0, no detection occurs. Otherwise, the scheduler will fail to 831 * load if the sequence number does not match @scx_hotplug_seq on the 832 * enable path. 833 */ 834 u64 hotplug_seq; 835 836 /** 837 * @cgroup_id: When >1, attach the scheduler as a sub-scheduler on the 838 * specified cgroup. 839 */ 840 u64 sub_cgroup_id; 841 842 /** 843 * @name: BPF scheduler's name 844 * 845 * Must be a non-zero valid BPF object name including only isalnum(), 846 * '_' and '.' chars. Shows up in kernel.sched_ext_ops sysctl while the 847 * BPF scheduler is enabled. 848 */ 849 char name[SCX_OPS_NAME_LEN]; 850 851 /* internal use only, must be NULL */ 852 void __rcu *priv; 853 }; 854 855 enum scx_opi { 856 SCX_OPI_BEGIN = 0, 857 SCX_OPI_NORMAL_BEGIN = 0, 858 SCX_OPI_NORMAL_END = SCX_OP_IDX(cpu_online), 859 SCX_OPI_CPU_HOTPLUG_BEGIN = SCX_OP_IDX(cpu_online), 860 SCX_OPI_CPU_HOTPLUG_END = SCX_OP_IDX(init), 861 SCX_OPI_END = SCX_OP_IDX(init), 862 }; 863 864 /* 865 * Collection of event counters. Event types are placed in descending order. 866 */ 867 struct scx_event_stats { 868 /* 869 * If ops.select_cpu() returns a CPU which can't be used by the task, 870 * the core scheduler code silently picks a fallback CPU. 871 */ 872 s64 SCX_EV_SELECT_CPU_FALLBACK; 873 874 /* 875 * When dispatching to a local DSQ, the CPU may have gone offline in 876 * the meantime. In this case, the task is bounced to the global DSQ. 877 */ 878 s64 SCX_EV_DISPATCH_LOCAL_DSQ_OFFLINE; 879 880 /* 881 * If SCX_OPS_ENQ_LAST is not set, the number of times that a task 882 * continued to run because there were no other tasks on the CPU. 883 */ 884 s64 SCX_EV_DISPATCH_KEEP_LAST; 885 886 /* 887 * If SCX_OPS_ENQ_EXITING is not set, the number of times that a task 888 * is dispatched to a local DSQ when exiting. 889 */ 890 s64 SCX_EV_ENQ_SKIP_EXITING; 891 892 /* 893 * If SCX_OPS_ENQ_MIGRATION_DISABLED is not set, the number of times a 894 * migration disabled task skips ops.enqueue() and is dispatched to its 895 * local DSQ. 896 */ 897 s64 SCX_EV_ENQ_SKIP_MIGRATION_DISABLED; 898 899 /* 900 * The number of times a task, enqueued on a local DSQ with 901 * SCX_ENQ_IMMED, was re-enqueued because the CPU was not available for 902 * immediate execution. 903 */ 904 s64 SCX_EV_REENQ_IMMED; 905 906 /* 907 * The number of times a reenq of local DSQ caused another reenq of 908 * local DSQ. This can happen when %SCX_ENQ_IMMED races against a higher 909 * priority class task even if the BPF scheduler always satisfies the 910 * prerequisites for %SCX_ENQ_IMMED at the time of enqueue. However, 911 * that scenario is very unlikely and this count going up regularly 912 * indicates that the BPF scheduler is handling %SCX_ENQ_REENQ 913 * incorrectly causing recursive reenqueues. 914 */ 915 s64 SCX_EV_REENQ_LOCAL_REPEAT; 916 917 /* 918 * Total number of times a task's time slice was refilled with the 919 * default value (SCX_SLICE_DFL). 920 */ 921 s64 SCX_EV_REFILL_SLICE_DFL; 922 923 /* 924 * The total duration of bypass modes in nanoseconds. 925 */ 926 s64 SCX_EV_BYPASS_DURATION; 927 928 /* 929 * The number of tasks dispatched in the bypassing mode. 930 */ 931 s64 SCX_EV_BYPASS_DISPATCH; 932 933 /* 934 * The number of times the bypassing mode has been activated. 935 */ 936 s64 SCX_EV_BYPASS_ACTIVATE; 937 938 /* 939 * The number of times the scheduler attempted to insert a task that it 940 * doesn't own into a DSQ. Such attempts are ignored. 941 * 942 * As BPF schedulers are allowed to ignore dequeues, it's difficult to 943 * tell whether such an attempt is from a scheduler malfunction or an 944 * ignored dequeue around sub-sched enabling. If this count keeps going 945 * up regardless of sub-sched enabling, it likely indicates a bug in the 946 * scheduler. 947 */ 948 s64 SCX_EV_INSERT_NOT_OWNED; 949 950 /* 951 * The number of times tasks from bypassing descendants are scheduled 952 * from sub_bypass_dsq's. 953 */ 954 s64 SCX_EV_SUB_BYPASS_DISPATCH; 955 }; 956 957 struct scx_sched; 958 959 enum scx_sched_pcpu_flags { 960 SCX_SCHED_PCPU_BYPASSING = 1LLU << 0, 961 }; 962 963 /* dispatch buf */ 964 struct scx_dsp_buf_ent { 965 struct task_struct *task; 966 unsigned long qseq; 967 u64 dsq_id; 968 u64 enq_flags; 969 }; 970 971 struct scx_dsp_ctx { 972 struct rq *rq; 973 u32 cursor; 974 u32 nr_tasks; 975 struct scx_dsp_buf_ent buf[]; 976 }; 977 978 struct scx_deferred_reenq_local { 979 struct list_head node; 980 u64 flags; 981 u64 seq; 982 u32 cnt; 983 }; 984 985 struct scx_sched_pcpu { 986 struct scx_sched *sch; 987 u64 flags; /* protected by rq lock */ 988 989 /* 990 * The event counters are in a per-CPU variable to minimize the 991 * accounting overhead. A system-wide view on the event counter is 992 * constructed when requested by scx_bpf_events(). 993 */ 994 struct scx_event_stats event_stats; 995 996 struct scx_deferred_reenq_local deferred_reenq_local; 997 struct scx_dispatch_q bypass_dsq; 998 #ifdef CONFIG_EXT_SUB_SCHED 999 u32 bypass_host_seq; 1000 #endif 1001 1002 /* must be the last entry - contains flex array */ 1003 struct scx_dsp_ctx dsp_ctx; 1004 }; 1005 1006 struct scx_sched_pnode { 1007 struct scx_dispatch_q global_dsq; 1008 }; 1009 1010 struct scx_sched { 1011 struct sched_ext_ops ops; 1012 DECLARE_BITMAP(has_op, SCX_OPI_END); 1013 1014 /* 1015 * Dispatch queues. 1016 * 1017 * The global DSQ (%SCX_DSQ_GLOBAL) is split per-node for scalability. 1018 * This is to avoid live-locking in bypass mode where all tasks are 1019 * dispatched to %SCX_DSQ_GLOBAL and all CPUs consume from it. If 1020 * per-node split isn't sufficient, it can be further split. 1021 */ 1022 struct rhashtable dsq_hash; 1023 struct scx_sched_pnode **pnode; 1024 struct scx_sched_pcpu __percpu *pcpu; 1025 1026 u64 slice_dfl; 1027 u64 bypass_timestamp; 1028 s32 bypass_depth; 1029 1030 /* bypass dispatch path enable state, see bypass_dsp_enabled() */ 1031 unsigned long bypass_dsp_claim; 1032 atomic_t bypass_dsp_enable_depth; 1033 1034 bool aborting; 1035 bool dump_disabled; /* protected by scx_dump_lock */ 1036 u32 dsp_max_batch; 1037 s32 level; 1038 1039 /* 1040 * Updates to the following warned bitfields can race causing RMW issues 1041 * but it doesn't really matter. 1042 */ 1043 bool warned_zero_slice:1; 1044 bool warned_deprecated_rq:1; 1045 bool warned_unassoc_progs:1; 1046 1047 struct list_head all; 1048 1049 #ifdef CONFIG_EXT_SUB_SCHED 1050 struct rhash_head hash_node; 1051 1052 struct list_head children; 1053 struct list_head sibling; 1054 struct cgroup *cgrp; 1055 char *cgrp_path; 1056 struct kset *sub_kset; 1057 1058 bool sub_attached; 1059 #endif /* CONFIG_EXT_SUB_SCHED */ 1060 1061 /* 1062 * The maximum amount of time in jiffies that a task may be runnable 1063 * without being scheduled on a CPU. If this timeout is exceeded, it 1064 * will trigger scx_error(). 1065 */ 1066 unsigned long watchdog_timeout; 1067 1068 atomic_t exit_kind; 1069 struct scx_exit_info *exit_info; 1070 1071 struct kobject kobj; 1072 1073 struct kthread_worker *helper; 1074 struct irq_work disable_irq_work; 1075 struct kthread_work disable_work; 1076 struct timer_list bypass_lb_timer; 1077 struct rcu_work rcu_work; 1078 1079 /* all ancestors including self */ 1080 struct scx_sched *ancestors[]; 1081 }; 1082 1083 enum scx_wake_flags { 1084 /* expose select WF_* flags as enums */ 1085 SCX_WAKE_FORK = WF_FORK, 1086 SCX_WAKE_TTWU = WF_TTWU, 1087 SCX_WAKE_SYNC = WF_SYNC, 1088 }; 1089 1090 enum scx_enq_flags { 1091 /* expose select ENQUEUE_* flags as enums */ 1092 SCX_ENQ_WAKEUP = ENQUEUE_WAKEUP, 1093 SCX_ENQ_HEAD = ENQUEUE_HEAD, 1094 SCX_ENQ_CPU_SELECTED = ENQUEUE_RQ_SELECTED, 1095 1096 /* high 32bits are SCX specific */ 1097 1098 /* 1099 * Set the following to trigger preemption when calling 1100 * scx_bpf_dsq_insert() with a local dsq as the target. The slice of the 1101 * current task is cleared to zero and the CPU is kicked into the 1102 * scheduling path. Implies %SCX_ENQ_HEAD. 1103 */ 1104 SCX_ENQ_PREEMPT = 1LLU << 32, 1105 1106 /* 1107 * Only allowed on local DSQs. Guarantees that the task either gets 1108 * on the CPU immediately and stays on it, or gets reenqueued back 1109 * to the BPF scheduler. It will never linger on a local DSQ or be 1110 * silently put back after preemption. 1111 * 1112 * The protection persists until the next fresh enqueue - it 1113 * survives SAVE/RESTORE cycles, slice extensions and preemption. 1114 * If the task can't stay on the CPU for any reason, it gets 1115 * reenqueued back to the BPF scheduler. 1116 * 1117 * Exiting and migration-disabled tasks bypass ops.enqueue() and 1118 * are placed directly on a local DSQ without IMMED protection 1119 * unless %SCX_OPS_ENQ_EXITING and %SCX_OPS_ENQ_MIGRATION_DISABLED 1120 * are set respectively. 1121 */ 1122 SCX_ENQ_IMMED = 1LLU << 33, 1123 1124 /* 1125 * The task being enqueued was previously enqueued on a DSQ, but was 1126 * removed and is being re-enqueued. See SCX_TASK_REENQ_* flags to find 1127 * out why a given task is being reenqueued. 1128 */ 1129 SCX_ENQ_REENQ = 1LLU << 40, 1130 1131 /* 1132 * The task being enqueued is the only task available for the cpu. By 1133 * default, ext core keeps executing such tasks but when 1134 * %SCX_OPS_ENQ_LAST is specified, they're ops.enqueue()'d with the 1135 * %SCX_ENQ_LAST flag set. 1136 * 1137 * The BPF scheduler is responsible for triggering a follow-up 1138 * scheduling event. Otherwise, Execution may stall. 1139 */ 1140 SCX_ENQ_LAST = 1LLU << 41, 1141 1142 /* high 8 bits are internal */ 1143 __SCX_ENQ_INTERNAL_MASK = 0xffLLU << 56, 1144 1145 SCX_ENQ_CLEAR_OPSS = 1LLU << 56, 1146 SCX_ENQ_DSQ_PRIQ = 1LLU << 57, 1147 SCX_ENQ_NESTED = 1LLU << 58, 1148 SCX_ENQ_GDSQ_FALLBACK = 1LLU << 59, /* fell back to global DSQ */ 1149 }; 1150 1151 enum scx_deq_flags { 1152 /* expose select DEQUEUE_* flags as enums */ 1153 SCX_DEQ_SLEEP = DEQUEUE_SLEEP, 1154 1155 /* high 32bits are SCX specific */ 1156 1157 /* 1158 * The generic core-sched layer decided to execute the task even though 1159 * it hasn't been dispatched yet. Dequeue from the BPF side. 1160 */ 1161 SCX_DEQ_CORE_SCHED_EXEC = 1LLU << 32, 1162 1163 /* 1164 * The task is being dequeued due to a property change (e.g., 1165 * sched_setaffinity(), sched_setscheduler(), set_user_nice(), 1166 * etc.). 1167 */ 1168 SCX_DEQ_SCHED_CHANGE = 1LLU << 33, 1169 }; 1170 1171 enum scx_reenq_flags { 1172 /* low 16bits determine which tasks should be reenqueued */ 1173 SCX_REENQ_ANY = 1LLU << 0, /* all tasks */ 1174 1175 __SCX_REENQ_FILTER_MASK = 0xffffLLU, 1176 1177 __SCX_REENQ_USER_MASK = SCX_REENQ_ANY, 1178 1179 /* bits 32-35 used by task_should_reenq() */ 1180 SCX_REENQ_TSR_RQ_OPEN = 1LLU << 32, 1181 SCX_REENQ_TSR_NOT_FIRST = 1LLU << 33, 1182 1183 __SCX_REENQ_TSR_MASK = 0xfLLU << 32, 1184 }; 1185 1186 enum scx_pick_idle_cpu_flags { 1187 SCX_PICK_IDLE_CORE = 1LLU << 0, /* pick a CPU whose SMT siblings are also idle */ 1188 SCX_PICK_IDLE_IN_NODE = 1LLU << 1, /* pick a CPU in the same target NUMA node */ 1189 }; 1190 1191 enum scx_kick_flags { 1192 /* 1193 * Kick the target CPU if idle. Guarantees that the target CPU goes 1194 * through at least one full scheduling cycle before going idle. If the 1195 * target CPU can be determined to be currently not idle and going to go 1196 * through a scheduling cycle before going idle, noop. 1197 */ 1198 SCX_KICK_IDLE = 1LLU << 0, 1199 1200 /* 1201 * Preempt the current task and execute the dispatch path. If the 1202 * current task of the target CPU is an SCX task, its ->scx.slice is 1203 * cleared to zero before the scheduling path is invoked so that the 1204 * task expires and the dispatch path is invoked. 1205 */ 1206 SCX_KICK_PREEMPT = 1LLU << 1, 1207 1208 /* 1209 * The scx_bpf_kick_cpu() call will return after the current SCX task of 1210 * the target CPU switches out. This can be used to implement e.g. core 1211 * scheduling. This has no effect if the current task on the target CPU 1212 * is not on SCX. 1213 */ 1214 SCX_KICK_WAIT = 1LLU << 2, 1215 }; 1216 1217 enum scx_tg_flags { 1218 SCX_TG_ONLINE = 1U << 0, 1219 SCX_TG_INITED = 1U << 1, 1220 }; 1221 1222 enum scx_enable_state { 1223 SCX_ENABLING, 1224 SCX_ENABLED, 1225 SCX_DISABLING, 1226 SCX_DISABLED, 1227 }; 1228 1229 static const char *scx_enable_state_str[] = { 1230 [SCX_ENABLING] = "enabling", 1231 [SCX_ENABLED] = "enabled", 1232 [SCX_DISABLING] = "disabling", 1233 [SCX_DISABLED] = "disabled", 1234 }; 1235 1236 /* 1237 * Task Ownership State Machine (sched_ext_entity->ops_state) 1238 * 1239 * The sched_ext core uses this state machine to track task ownership 1240 * between the SCX core and the BPF scheduler. This allows the BPF 1241 * scheduler to dispatch tasks without strict ordering requirements, while 1242 * the SCX core safely rejects invalid dispatches. 1243 * 1244 * State Transitions 1245 * 1246 * .------------> NONE (owned by SCX core) 1247 * | | ^ 1248 * | enqueue | | direct dispatch 1249 * | v | 1250 * | QUEUEING -------' 1251 * | | 1252 * | enqueue | 1253 * | completes | 1254 * | v 1255 * | QUEUED (owned by BPF scheduler) 1256 * | | 1257 * | dispatch | 1258 * | | 1259 * | v 1260 * | DISPATCHING 1261 * | | 1262 * | dispatch | 1263 * | completes | 1264 * `---------------' 1265 * 1266 * State Descriptions 1267 * 1268 * - %SCX_OPSS_NONE: 1269 * Task is owned by the SCX core. It's either on a run queue, running, 1270 * or being manipulated by the core scheduler. The BPF scheduler has no 1271 * claim on this task. 1272 * 1273 * - %SCX_OPSS_QUEUEING: 1274 * Transitional state while transferring a task from the SCX core to 1275 * the BPF scheduler. The task's rq lock is held during this state. 1276 * Since QUEUEING is both entered and exited under the rq lock, dequeue 1277 * can never observe this state (it would be a BUG). When finishing a 1278 * dispatch, if the task is still in %SCX_OPSS_QUEUEING the completion 1279 * path busy-waits for it to leave this state (via wait_ops_state()) 1280 * before retrying. 1281 * 1282 * - %SCX_OPSS_QUEUED: 1283 * Task is owned by the BPF scheduler. It's on a DSQ (dispatch queue) 1284 * and the BPF scheduler is responsible for dispatching it. A QSEQ 1285 * (queue sequence number) is embedded in this state to detect 1286 * dispatch/dequeue races: if a task is dequeued and re-enqueued, the 1287 * QSEQ changes and any in-flight dispatch operations targeting the old 1288 * QSEQ are safely ignored. 1289 * 1290 * - %SCX_OPSS_DISPATCHING: 1291 * Transitional state while transferring a task from the BPF scheduler 1292 * back to the SCX core. This state indicates the BPF scheduler has 1293 * selected the task for execution. When dequeue needs to take the task 1294 * off a DSQ and it is still in %SCX_OPSS_DISPATCHING, the dequeue path 1295 * busy-waits for it to leave this state (via wait_ops_state()) before 1296 * proceeding. Exits to %SCX_OPSS_NONE when dispatch completes. 1297 * 1298 * Memory Ordering 1299 * 1300 * Transitions out of %SCX_OPSS_QUEUEING and %SCX_OPSS_DISPATCHING into 1301 * %SCX_OPSS_NONE or %SCX_OPSS_QUEUED must use atomic_long_set_release() 1302 * and waiters must use atomic_long_read_acquire(). This ensures proper 1303 * synchronization between concurrent operations. 1304 * 1305 * Cross-CPU Task Migration 1306 * 1307 * When moving a task in the %SCX_OPSS_DISPATCHING state, we can't simply 1308 * grab the target CPU's rq lock because a concurrent dequeue might be 1309 * waiting on %SCX_OPSS_DISPATCHING while holding the source rq lock 1310 * (deadlock). 1311 * 1312 * The sched_ext core uses a "lock dancing" protocol coordinated by 1313 * p->scx.holding_cpu. When moving a task to a different rq: 1314 * 1315 * 1. Verify task can be moved (CPU affinity, migration_disabled, etc.) 1316 * 2. Set p->scx.holding_cpu to the current CPU 1317 * 3. Set task state to %SCX_OPSS_NONE; dequeue waits while DISPATCHING 1318 * is set, so clearing DISPATCHING first prevents the circular wait 1319 * (safe to lock the rq we need) 1320 * 4. Unlock the current CPU's rq 1321 * 5. Lock src_rq (where the task currently lives) 1322 * 6. Verify p->scx.holding_cpu == current CPU, if not, dequeue won the 1323 * race (dequeue clears holding_cpu to -1 when it takes the task), in 1324 * this case migration is aborted 1325 * 7. If src_rq == dst_rq: clear holding_cpu and enqueue directly 1326 * into dst_rq's local DSQ (no lock swap needed) 1327 * 8. Otherwise: call move_remote_task_to_local_dsq(), which releases 1328 * src_rq, locks dst_rq, and performs the deactivate/activate 1329 * migration cycle (dst_rq is held on return) 1330 * 9. Unlock dst_rq and re-lock the current CPU's rq to restore 1331 * the lock state expected by the caller 1332 * 1333 * If any verification fails, abort the migration. 1334 * 1335 * This state tracking allows the BPF scheduler to try to dispatch any task 1336 * at any time regardless of its state. The SCX core can safely 1337 * reject/ignore invalid dispatches, simplifying the BPF scheduler 1338 * implementation. 1339 */ 1340 enum scx_ops_state { 1341 SCX_OPSS_NONE, /* owned by the SCX core */ 1342 SCX_OPSS_QUEUEING, /* in transit to the BPF scheduler */ 1343 SCX_OPSS_QUEUED, /* owned by the BPF scheduler */ 1344 SCX_OPSS_DISPATCHING, /* in transit back to the SCX core */ 1345 1346 /* 1347 * QSEQ brands each QUEUED instance so that, when dispatch races 1348 * dequeue/requeue, the dispatcher can tell whether it still has a claim 1349 * on the task being dispatched. 1350 * 1351 * As some 32bit archs can't do 64bit store_release/load_acquire, 1352 * p->scx.ops_state is atomic_long_t which leaves 30 bits for QSEQ on 1353 * 32bit machines. The dispatch race window QSEQ protects is very narrow 1354 * and runs with IRQ disabled. 30 bits should be sufficient. 1355 */ 1356 SCX_OPSS_QSEQ_SHIFT = 2, 1357 }; 1358 1359 /* Use macros to ensure that the type is unsigned long for the masks */ 1360 #define SCX_OPSS_STATE_MASK ((1LU << SCX_OPSS_QSEQ_SHIFT) - 1) 1361 #define SCX_OPSS_QSEQ_MASK (~SCX_OPSS_STATE_MASK) 1362 1363 extern struct scx_sched __rcu *scx_root; 1364 DECLARE_PER_CPU(struct rq *, scx_locked_rq_state); 1365 1366 /* 1367 * Return the rq currently locked from an scx callback, or NULL if no rq is 1368 * locked. 1369 */ 1370 static inline struct rq *scx_locked_rq(void) 1371 { 1372 return __this_cpu_read(scx_locked_rq_state); 1373 } 1374 1375 static inline bool scx_kf_allowed_if_unlocked(void) 1376 { 1377 return !current->scx.kf_mask; 1378 } 1379 1380 static inline bool scx_bypassing(struct scx_sched *sch, s32 cpu) 1381 { 1382 return unlikely(per_cpu_ptr(sch->pcpu, cpu)->flags & 1383 SCX_SCHED_PCPU_BYPASSING); 1384 } 1385 1386 #ifdef CONFIG_EXT_SUB_SCHED 1387 /** 1388 * scx_task_sched - Find scx_sched scheduling a task 1389 * @p: task of interest 1390 * 1391 * Return @p's scheduler instance. Must be called with @p's pi_lock or rq lock 1392 * held. 1393 */ 1394 static inline struct scx_sched *scx_task_sched(const struct task_struct *p) 1395 { 1396 return rcu_dereference_protected(p->scx.sched, 1397 lockdep_is_held(&p->pi_lock) || 1398 lockdep_is_held(__rq_lockp(task_rq(p)))); 1399 } 1400 1401 /** 1402 * scx_task_sched_rcu - Find scx_sched scheduling a task 1403 * @p: task of interest 1404 * 1405 * Return @p's scheduler instance. The returned scx_sched is RCU protected. 1406 */ 1407 static inline struct scx_sched *scx_task_sched_rcu(const struct task_struct *p) 1408 { 1409 return rcu_dereference_all(p->scx.sched); 1410 } 1411 1412 /** 1413 * scx_task_on_sched - Is a task on the specified sched? 1414 * @sch: sched to test against 1415 * @p: task of interest 1416 * 1417 * Returns %true if @p is on @sch, %false otherwise. 1418 */ 1419 static inline bool scx_task_on_sched(struct scx_sched *sch, 1420 const struct task_struct *p) 1421 { 1422 return rcu_access_pointer(p->scx.sched) == sch; 1423 } 1424 1425 /** 1426 * scx_prog_sched - Find scx_sched associated with a BPF prog 1427 * @aux: aux passed in from BPF to a kfunc 1428 * 1429 * To be called from kfuncs. Return the scheduler instance associated with the 1430 * BPF program given the implicit kfunc argument aux. The returned scx_sched is 1431 * RCU protected. 1432 */ 1433 static inline struct scx_sched *scx_prog_sched(const struct bpf_prog_aux *aux) 1434 { 1435 struct sched_ext_ops *ops; 1436 struct scx_sched *root; 1437 1438 ops = bpf_prog_get_assoc_struct_ops(aux); 1439 if (likely(ops)) 1440 return rcu_dereference_all(ops->priv); 1441 1442 root = rcu_dereference_all(scx_root); 1443 if (root) { 1444 /* 1445 * COMPAT-v6.19: Schedulers built before sub-sched support was 1446 * introduced may have unassociated non-struct_ops programs. 1447 */ 1448 if (!root->ops.sub_attach) 1449 return root; 1450 1451 if (!root->warned_unassoc_progs) { 1452 printk_deferred(KERN_WARNING "sched_ext: Unassociated program %s (id %d)\n", 1453 aux->name, aux->id); 1454 root->warned_unassoc_progs = true; 1455 } 1456 } 1457 1458 return NULL; 1459 } 1460 #else /* CONFIG_EXT_SUB_SCHED */ 1461 static inline struct scx_sched *scx_task_sched(const struct task_struct *p) 1462 { 1463 return rcu_dereference_protected(scx_root, 1464 lockdep_is_held(&p->pi_lock) || 1465 lockdep_is_held(__rq_lockp(task_rq(p)))); 1466 } 1467 1468 static inline struct scx_sched *scx_task_sched_rcu(const struct task_struct *p) 1469 { 1470 return rcu_dereference_all(scx_root); 1471 } 1472 1473 static inline bool scx_task_on_sched(struct scx_sched *sch, 1474 const struct task_struct *p) 1475 { 1476 return true; 1477 } 1478 1479 static struct scx_sched *scx_prog_sched(const struct bpf_prog_aux *aux) 1480 { 1481 return rcu_dereference_all(scx_root); 1482 } 1483 #endif /* CONFIG_EXT_SUB_SCHED */ 1484