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