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