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