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