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 #include <linux/bitmap.h> 10 #include <linux/btf_ids.h> 11 #include <linux/rhashtable.h> 12 #include <linux/sched/clock.h> 13 #include <linux/sched/isolation.h> 14 #include <linux/suspend.h> 15 #include <linux/sysrq.h> 16 17 #include "../pelt.h" 18 #include "internal.h" 19 #include "cid.h" 20 #include "arena.h" 21 #include "idle.h" 22 #include "sub.h" 23 #include "inlines.h" 24 25 DEFINE_RAW_SPINLOCK(scx_sched_lock); 26 27 /* 28 * Block a retained proxy donor, telling put_prev_task_scx() that the donor is 29 * about to be dequeued and must not be reenqueued. 30 */ 31 static void scx_block_proxy_donor(struct rq *rq, struct task_struct *p) 32 { 33 rq->scx.flags |= SCX_RQ_PROXY_BLOCKING; 34 sched_proxy_block_task(rq, p); 35 rq->scx.flags &= ~SCX_RQ_PROXY_BLOCKING; 36 } 37 38 bool __scx_allow_proxy_exec(const struct task_struct *p) 39 { 40 struct scx_sched *sch; 41 42 if (p->sched_class != &ext_sched_class) 43 return true; 44 45 sch = scx_task_sched(p); 46 return !sch || (sch->ops.flags & SCX_OPS_ENQ_BLOCKED); 47 } 48 49 /* 50 * End retained proxy execution before changing @p's BPF scheduler ownership. 51 * Called with @p's pi and rq locks held immediately before 52 * sched_change_begin(). The caller must pass DEQUEUE_NOCLOCK so the rq clock 53 * is updated only once. 54 */ 55 void scx_prepare_task_sched_change(struct task_struct *p) 56 { 57 lockdep_assert_held(&p->pi_lock); 58 lockdep_assert_rq_held(task_rq(p)); 59 60 update_rq_clock(task_rq(p)); 61 scx_block_proxy_donor(task_rq(p), p); 62 } 63 64 /* 65 * NOTE: sched_ext is in the process of growing multiple scheduler support and 66 * scx_root usage is in a transitional state. Naked dereferences are safe if the 67 * caller is one of the tasks attached to SCX and explicit RCU dereference is 68 * necessary otherwise. Naked scx_root dereferences trigger sparse warnings but 69 * are used as temporary markers to indicate that the dereferences need to be 70 * updated to point to the associated scheduler instances rather than scx_root. 71 */ 72 struct scx_sched __rcu *scx_root; 73 74 /* 75 * All scheds, writers must hold both scx_enable_mutex and scx_sched_lock. 76 * Readers can hold either or rcu_read_lock(). 77 */ 78 LIST_HEAD(scx_sched_all); 79 80 #ifdef CONFIG_EXT_SUB_SCHED 81 static __always_inline int scx_sched_cmpfn(struct rhashtable_compare_arg *arg, 82 const void *ptr) 83 { 84 const struct scx_sched *sch = ptr; 85 86 BUILD_BUG_ON(sizeof_field(struct scx_sched, ops.sub_cgroup_id) != sizeof(u64)); 87 88 return sch->ops.sub_cgroup_id != *(const u64 *)arg->key; 89 } 90 91 const struct rhashtable_params scx_sched_hash_params = { 92 .key_len = sizeof_field(struct scx_sched, ops.sub_cgroup_id), 93 .key_offset = offsetof(struct scx_sched, ops.sub_cgroup_id), 94 .head_offset = offsetof(struct scx_sched, hash_node), 95 .obj_cmpfn = scx_sched_cmpfn, 96 .insecure_elasticity = true, /* inserted under scx_sched_lock */ 97 }; 98 99 struct rhashtable scx_sched_hash; 100 #endif 101 102 /* see SCX_OPS_TID_TO_TASK */ 103 static __always_inline int scx_tid_cmpfn(struct rhashtable_compare_arg *arg, const void *ptr) 104 { 105 const struct sched_ext_entity *scx = ptr; 106 107 BUILD_BUG_ON(sizeof_field(struct sched_ext_entity, tid) != sizeof(u64)); 108 109 return scx->tid != *(const u64 *)arg->key; 110 } 111 112 static const struct rhashtable_params scx_tid_hash_params = { 113 .key_len = sizeof_field(struct sched_ext_entity, tid), 114 .key_offset = offsetof(struct sched_ext_entity, tid), 115 .head_offset = offsetof(struct sched_ext_entity, tid_hash_node), 116 .obj_cmpfn = scx_tid_cmpfn, 117 .insecure_elasticity = true, /* inserted/removed under scx_tasks_lock */ 118 }; 119 static struct rhashtable scx_tid_hash; 120 121 /* 122 * During exit, a task may schedule after losing its PIDs. When disabling the 123 * BPF scheduler, we need to be able to iterate tasks in every state to 124 * guarantee system safety. Maintain a dedicated task list which contains every 125 * task between its fork and eventual free. 126 */ 127 static DEFINE_RAW_SPINLOCK(scx_tasks_lock); 128 static LIST_HEAD(scx_tasks); 129 130 /* ops enable/disable */ 131 DEFINE_MUTEX(scx_enable_mutex); 132 DEFINE_STATIC_KEY_FALSE(__scx_enabled); 133 DEFINE_PERCPU_RWSEM(scx_fork_rwsem); 134 static atomic_t scx_enable_state_var = ATOMIC_INIT(SCX_DISABLED); 135 static DEFINE_RAW_SPINLOCK(scx_bypass_lock); 136 static bool scx_init_task_enabled; 137 static bool scx_switching_all; 138 DEFINE_STATIC_KEY_FALSE(__scx_switched_all); 139 static DEFINE_STATIC_KEY_FALSE(__scx_tid_to_task_enabled); 140 141 /* 142 * Gates cgroup ops delivery. Set at the end of the cgroup init phase of root 143 * enable and cleared before root disable starts tearing down tasks, both under 144 * scx_cgroup_lock(). Holding cgroup_lock() and seeing %true guarantees no race 145 * against root tearing down tasks. 146 */ 147 bool scx_cgroup_enabled; 148 149 /* 150 * True once SCX_OPS_TID_TO_TASK has been negotiated with the root scheduler 151 * and the tid->task table is live. Wraps the static key so callers don't 152 * take the address, and hints "likely enabled" for the common case where 153 * the feature is in use. 154 */ 155 static inline bool scx_tid_to_task_enabled(void) 156 { 157 return static_branch_likely(&__scx_tid_to_task_enabled); 158 } 159 160 static atomic_long_t scx_nr_rejected = ATOMIC_LONG_INIT(0); 161 static atomic_long_t scx_hotplug_seq = ATOMIC_LONG_INIT(0); 162 163 /* Global cursor for the per-CPU tid allocator. Starts at 1; tid 0 is reserved. */ 164 static atomic64_t scx_tid_cursor = ATOMIC64_INIT(1); 165 166 /* is @dsq synchronized by the containing rq lock instead of dsq->lock? */ 167 static bool dsq_is_rq_owned(struct scx_dispatch_q *dsq) 168 { 169 switch (dsq->id) { 170 case SCX_DSQ_LOCAL: 171 case SCX_DSQ_REJECT: 172 case SCX_DSQ_RESCUE: 173 return true; 174 default: 175 return false; 176 } 177 } 178 179 /* Cursor for unique scx_sched instance ids. id 0 is reserved. */ 180 static atomic64_t scx_sched_id_cursor = ATOMIC64_INIT(0); 181 182 #ifdef CONFIG_EXT_SUB_SCHED 183 /* 184 * The sub sched being enabled. Used by scx_disable_and_exit_task() to exit 185 * tasks for the sub-sched being enabled. Use a global variable instead of a 186 * per-task field as all enables are serialized. 187 */ 188 struct scx_sched *scx_enabling_sub_sched; 189 #else 190 #define scx_enabling_sub_sched (struct scx_sched *)NULL 191 #endif /* CONFIG_EXT_SUB_SCHED */ 192 193 /* 194 * A monotonically increasing sequence number that is incremented every time a 195 * scheduler is enabled. This can be used to check if any custom sched_ext 196 * scheduler has ever been used in the system. 197 */ 198 static atomic_long_t scx_enable_seq = ATOMIC_LONG_INIT(0); 199 200 /* 201 * Watchdog interval. All scx_sched's share a single watchdog timer and the 202 * interval is half of the shortest sch->watchdog_timeout. 203 */ 204 static unsigned long scx_watchdog_interval; 205 206 /* 207 * The last time the delayed work was run. This delayed work relies on 208 * ksoftirqd being able to run to service timer interrupts, so it's possible 209 * that this work itself could get wedged. To account for this, we check that 210 * it's not stalled in the timer tick, and trigger an error if it is. 211 */ 212 static unsigned long scx_watchdog_timestamp = INITIAL_JIFFIES; 213 214 static struct delayed_work scx_watchdog_work; 215 216 /* 217 * For %SCX_KICK_WAIT: Each CPU has a pointer to an array of kick_sync sequence 218 * numbers. The arrays are allocated with kvzalloc() as size can exceed percpu 219 * allocator limits on large machines. O(nr_cpu_ids^2) allocation, allocated 220 * lazily when enabling and freed when disabling to avoid waste when sched_ext 221 * isn't active. 222 */ 223 struct scx_kick_syncs { 224 struct rcu_head rcu; 225 unsigned long syncs[]; 226 }; 227 228 static DEFINE_PER_CPU(struct scx_kick_syncs __rcu *, scx_kick_syncs); 229 230 /* 231 * Per-CPU buffered allocator state for p->scx.tid. Each CPU pulls a chunk of 232 * SCX_TID_CHUNK ids from scx_tid_cursor and hands them out locally without 233 * further synchronization. See scx_alloc_tid(). 234 */ 235 struct scx_tid_alloc { 236 u64 next; 237 u64 end; 238 }; 239 static DEFINE_PER_CPU(struct scx_tid_alloc, scx_tid_alloc); 240 241 /* 242 * Direct dispatch marker. 243 * 244 * Non-NULL values are used for direct dispatch from enqueue path. A valid 245 * pointer points to the task currently being enqueued. An ERR_PTR value is used 246 * to indicate that direct dispatch has already happened. 247 */ 248 static DEFINE_PER_CPU(struct task_struct *, direct_dispatch_task); 249 250 static __always_inline int dsq_cmpfn(struct rhashtable_compare_arg *arg, const void *ptr) 251 { 252 const struct scx_dispatch_q *dsq = ptr; 253 254 BUILD_BUG_ON(sizeof_field(struct scx_dispatch_q, id) != sizeof(u64)); 255 256 return dsq->id != *(const u64 *)arg->key; 257 } 258 259 static const struct rhashtable_params dsq_hash_params = { 260 .key_len = sizeof_field(struct scx_dispatch_q, id), 261 .key_offset = offsetof(struct scx_dispatch_q, id), 262 .head_offset = offsetof(struct scx_dispatch_q, hash_node), 263 .obj_cmpfn = dsq_cmpfn, 264 }; 265 266 static LLIST_HEAD(dsqs_to_free); 267 268 /* ops debug dump */ 269 static DEFINE_RAW_SPINLOCK(scx_dump_lock); 270 271 struct scx_dump_data { 272 s32 cpu; 273 bool first; 274 s32 cursor; 275 struct seq_buf *s; 276 const char *prefix; 277 struct scx_bstr_buf buf; 278 }; 279 280 static struct scx_dump_data scx_dump_data = { 281 .cpu = -1, 282 }; 283 284 /* /sys/kernel/sched_ext interface */ 285 static struct kset *scx_kset; 286 287 /* 288 * Parameters that can be adjusted through /sys/module/sched_ext/parameters. 289 * There usually is no reason to modify these as normal scheduler operation 290 * shouldn't be affected by them. The knobs are primarily for debugging. 291 */ 292 static unsigned int scx_slice_bypass_us = SCX_SLICE_BYPASS / NSEC_PER_USEC; 293 static unsigned int scx_bypass_lb_intv_us = SCX_BYPASS_LB_DFL_INTV_US; 294 295 static int set_slice_us(const char *val, const struct kernel_param *kp) 296 { 297 return param_set_uint_minmax(val, kp, 100, 100 * USEC_PER_MSEC); 298 } 299 300 static const struct kernel_param_ops slice_us_param_ops = { 301 .set = set_slice_us, 302 .get = param_get_uint, 303 }; 304 305 static int set_bypass_lb_intv_us(const char *val, const struct kernel_param *kp) 306 { 307 return param_set_uint_minmax(val, kp, 0, 10 * USEC_PER_SEC); 308 } 309 310 static const struct kernel_param_ops bypass_lb_intv_us_param_ops = { 311 .set = set_bypass_lb_intv_us, 312 .get = param_get_uint, 313 }; 314 315 #undef MODULE_PARAM_PREFIX 316 #define MODULE_PARAM_PREFIX "sched_ext." 317 318 module_param_cb(slice_bypass_us, &slice_us_param_ops, &scx_slice_bypass_us, 0600); 319 MODULE_PARM_DESC(slice_bypass_us, "bypass slice in microseconds, applied on [un]load (100us to 100ms)"); 320 module_param_cb(bypass_lb_intv_us, &bypass_lb_intv_us_param_ops, &scx_bypass_lb_intv_us, 0600); 321 MODULE_PARM_DESC(bypass_lb_intv_us, "bypass load balance interval in microseconds (0 (disable) to 10s)"); 322 323 #undef MODULE_PARAM_PREFIX 324 325 #define CREATE_TRACE_POINTS 326 #include <trace/events/sched_ext.h> 327 328 static void run_deferred(struct rq *rq); 329 static bool task_dead_and_done(struct task_struct *p); 330 static void scx_disable(struct scx_sched *sch, enum scx_exit_kind kind); 331 332 __printf(5, 6) bool __scx_exit(struct scx_sched *sch, 333 enum scx_exit_kind kind, s64 exit_code, 334 s32 exit_cpu, const char *fmt, ...) 335 { 336 va_list args; 337 bool ret; 338 339 va_start(args, fmt); 340 ret = scx_vexit(sch, kind, exit_code, exit_cpu, fmt, args); 341 va_end(args); 342 343 return ret; 344 } 345 346 static long jiffies_delta_msecs(unsigned long at, unsigned long now) 347 { 348 if (time_after(at, now)) 349 return jiffies_to_msecs(at - now); 350 else 351 return -(long)jiffies_to_msecs(now - at); 352 } 353 354 static bool u32_before(u32 a, u32 b) 355 { 356 return (s32)(a - b) < 0; 357 } 358 359 /** 360 * scx_is_descendant - Test whether sched is a descendant 361 * @sch: sched to test 362 * @ancestor: ancestor sched to test against 363 * 364 * Test whether @sch is a descendant of @ancestor. 365 */ 366 bool scx_is_descendant(struct scx_sched *sch, struct scx_sched *ancestor) 367 { 368 if (sch->level < ancestor->level) 369 return false; 370 return sch->ancestors[ancestor->level] == ancestor; 371 } 372 373 static struct scx_dispatch_q *find_global_dsq(struct scx_sched *sch, s32 cpu) 374 { 375 return &sch->pnode[cpu_to_node(cpu)]->global_dsq; 376 } 377 378 static struct scx_dispatch_q *find_user_dsq(struct scx_sched *sch, u64 dsq_id) 379 { 380 return rhashtable_lookup(&sch->dsq_hash, &dsq_id, dsq_hash_params); 381 } 382 383 static const struct sched_class *scx_setscheduler_class(struct task_struct *p) 384 { 385 if (p->sched_class == &stop_sched_class) 386 return &stop_sched_class; 387 388 return __setscheduler_class(p->policy, p->prio); 389 } 390 391 static struct scx_dispatch_q *bypass_enq_target_dsq(struct scx_sched *sch, s32 cpu) 392 { 393 /* 394 * If @sch is a sub-sched which is bypassing, its tasks should go into 395 * the bypass DSQs of the nearest ancestor which is not bypassing. The 396 * not-bypassing ancestor is responsible for scheduling all tasks from 397 * bypassing sub-trees. If all ancestors including root are bypassing, 398 * all tasks should go to the root's bypass DSQs. 399 * 400 * Whenever a sched starts bypassing, all runnable tasks in its subtree 401 * are re-enqueued after scx_bypassing() is turned on, guaranteeing that 402 * all tasks are transferred to the right DSQs. 403 */ 404 return scx_bypass_dsq(scx_exec_sched(sch, cpu), cpu); 405 } 406 407 /** 408 * rq_is_open - Is the rq available for immediate execution of an SCX task? 409 * @rq: rq to test 410 * @enq_flags: optional %SCX_ENQ_* of the task being enqueued 411 * 412 * Returns %true if @rq is currently open for executing an SCX task. After a 413 * %false return, @rq is guaranteed to invoke SCX dispatch path at least once 414 * before going to idle and not inserting a task into @rq's local DSQ after a 415 * %false return doesn't cause @rq to stall. 416 */ 417 static bool rq_is_open(struct rq *rq, u64 enq_flags) 418 { 419 lockdep_assert_rq_held(rq); 420 421 /* 422 * A higher-priority class task is either running or in the process of 423 * waking up on @rq. 424 */ 425 if (sched_class_above(rq->next_class, &ext_sched_class)) 426 return false; 427 428 /* 429 * @rq is either in transition to or in idle and there is no 430 * higher-priority class task waking up on it. 431 */ 432 if (sched_class_above(&ext_sched_class, rq->next_class)) 433 return true; 434 435 /* 436 * @rq is either picking, in transition to, or running an SCX task. 437 */ 438 439 /* 440 * If we're in the dispatch path holding rq lock, $donor may or may not 441 * be ready depending on whether the on-going dispatch decides to extend 442 * $donor's slice. We say yes here and resolve it at the end of dispatch. 443 * See dispatch_one(). 444 */ 445 if (rq->scx.flags & SCX_RQ_IN_DISPATCH) 446 return true; 447 448 /* 449 * The preemption flags clear $donor's slice if on SCX and kick dispatch, 450 * so allow it to avoid spuriously triggering reenq on a combined 451 * PREEMPT|IMMED insertion. 452 */ 453 if (enq_flags & (SCX_ENQ_PREEMPT | SCX_ENQ_PREEMPT_LAZY)) { 454 struct task_struct *donor = rq->donor; 455 456 /* 457 * A protected slice refuses the preemption and the cpu stays 458 * occupied. See rq_owned_post_enq(). 459 */ 460 return donor->sched_class != &ext_sched_class || 461 likely(!(donor->scx.flags & SCX_TASK_PROTECTED)); 462 } 463 464 /* 465 * @rq is either in transition to or running an SCX task and can't go 466 * idle without another SCX dispatch cycle. 467 */ 468 return false; 469 } 470 471 /* 472 * Track the rq currently locked. 473 * 474 * This allows kfuncs to safely operate on rq from any scx ops callback, 475 * knowing which rq is already locked. 476 */ 477 DEFINE_PER_CPU(struct rq *, scx_locked_rq_state); 478 479 /* 480 * Under core scheduling, a pick that releases the rq lock invalidates the 481 * core-wide selection it is part of. Count the releases so that the core-sched 482 * pick can tell whether one happened across dispatch. 483 */ 484 static void scx_rq_lock_drop(struct rq *rq) 485 { 486 lockdep_assert_rq_held(rq); 487 #ifdef CONFIG_SCHED_CORE 488 if (sched_core_enabled(rq)) 489 rq->scx.lock_drop_seq++; 490 #endif 491 } 492 493 static void switch_rq_lock(struct rq *from, struct rq *to) 494 { 495 bool tracked = scx_locked_rq() == from; 496 497 if (tracked) 498 update_locked_rq(NULL); 499 scx_rq_lock_drop(from); 500 raw_spin_rq_unlock(from); 501 raw_spin_rq_lock(to); 502 if (tracked) 503 update_locked_rq(to); 504 } 505 506 /* 507 * Flipped on enable per sch->is_cid_type. Declared in internal.h so 508 * subsystem inlines can read it. 509 */ 510 DEFINE_STATIC_KEY_FALSE(__scx_is_cid_type); 511 512 /** 513 * scx_fill_cmask_scratch - Build this cpu's arena cmask from @cpumask 514 * @sch: scx_sched whose scratch to fill 515 * @cpumask: cpus to translate into cids 516 * 517 * The scratch lives in BPF-writable arena memory and its header can't be 518 * trusted, so it is rewritten from kernel geometry rather than read. Caller 519 * must hold an rq lock so this cpu is the sole kernel writer for as long as the 520 * returned address is in use. 521 */ 522 static struct scx_cmask *scx_fill_cmask_scratch(struct scx_sched *sch, 523 const struct cpumask *cpumask) 524 { 525 struct scx_cmask *kern_va = *this_cpu_ptr(sch->set_cmask_scratch); 526 struct scx_cmask_ref ref; 527 528 scx_cmask_ref_init_kern(sch, kern_va, 0, num_possible_cpus(), &ref); 529 scx_cmask_ref_from_cpumask(&ref, cpumask); 530 return kern_va; 531 } 532 533 /** 534 * scx_call_op_set_cpumask - Invoke the set_cpumask or set_cmask op for @task 535 * @sch: scx_sched being invoked 536 * @rq: rq to update as the currently-locked rq, or NULL 537 * @task: task whose affinity is changing 538 * @cpumask: new cpumask 539 * 540 * For cid-form schedulers, translate @cpumask to a cmask in the per-cpu scratch 541 * and dispatch through the ops_cid union view. Caller must hold @rq's rq lock. 542 */ 543 static inline void scx_call_op_set_cpumask(struct scx_sched *sch, struct rq *rq, 544 struct task_struct *task, 545 const struct cpumask *cpumask) 546 { 547 if (scx_is_cid_type()) 548 SCX_CALL_CID_OP_TASK(sch, set_cmask, rq, task, 549 scx_fill_cmask_scratch(sch, cpumask)); 550 else 551 SCX_CALL_OP_TASK(sch, set_cpumask, rq, task, cpumask); 552 } 553 554 enum scx_dsq_iter_flags { 555 /* iterate in the reverse dispatch order */ 556 SCX_DSQ_ITER_REV = 1U << 16, 557 558 __SCX_DSQ_ITER_HAS_REENQ = 1U << 29, 559 __SCX_DSQ_ITER_HAS_SLICE = 1U << 30, 560 __SCX_DSQ_ITER_HAS_VTIME = 1U << 31, 561 562 __SCX_DSQ_ITER_USER_FLAGS = SCX_DSQ_ITER_REV, 563 __SCX_DSQ_ITER_ALL_FLAGS = __SCX_DSQ_ITER_USER_FLAGS | 564 __SCX_DSQ_ITER_HAS_REENQ | 565 __SCX_DSQ_ITER_HAS_SLICE | 566 __SCX_DSQ_ITER_HAS_VTIME, 567 }; 568 569 /** 570 * nldsq_next_task - Iterate to the next task in a non-local DSQ 571 * @dsq: non-local dsq being iterated 572 * @cur: current position, %NULL to start iteration 573 * @rev: walk backwards 574 * 575 * Returns %NULL when iteration is finished. 576 */ 577 static struct task_struct *nldsq_next_task(struct scx_dispatch_q *dsq, 578 struct task_struct *cur, bool rev) 579 { 580 struct list_head *list_node; 581 struct scx_dsq_list_node *dsq_lnode; 582 583 lockdep_assert_held(&dsq->lock); 584 585 if (cur) 586 list_node = &cur->scx.dsq_list.node; 587 else 588 list_node = &dsq->list; 589 590 /* find the next task, need to skip BPF iteration cursors */ 591 do { 592 if (rev) 593 list_node = list_node->prev; 594 else 595 list_node = list_node->next; 596 597 if (list_node == &dsq->list) 598 return NULL; 599 600 dsq_lnode = container_of(list_node, struct scx_dsq_list_node, 601 node); 602 } while (dsq_lnode->flags & SCX_DSQ_LNODE_ITER_CURSOR); 603 604 return container_of(dsq_lnode, struct task_struct, scx.dsq_list); 605 } 606 607 #define nldsq_for_each_task(p, dsq) \ 608 for ((p) = nldsq_next_task((dsq), NULL, false); (p); \ 609 (p) = nldsq_next_task((dsq), (p), false)) 610 611 /** 612 * nldsq_cursor_next_task - Iterate to the next task given a cursor in a non-local DSQ 613 * @cursor: scx_dsq_list_node initialized with INIT_DSQ_LIST_CURSOR() 614 * @dsq: non-local dsq being iterated 615 * 616 * Find the next task in a cursor based iteration. The caller must have 617 * initialized @cursor using INIT_DSQ_LIST_CURSOR() and can release the DSQ lock 618 * between the iteration steps. 619 * 620 * Only tasks which were queued before @cursor was initialized are visible. This 621 * bounds the iteration and guarantees that vtime never jumps in the other 622 * direction while iterating. 623 */ 624 static struct task_struct *nldsq_cursor_next_task(struct scx_dsq_list_node *cursor, 625 struct scx_dispatch_q *dsq) 626 { 627 bool rev = cursor->flags & SCX_DSQ_ITER_REV; 628 struct task_struct *p; 629 630 lockdep_assert_held(&dsq->lock); 631 BUG_ON(!(cursor->flags & SCX_DSQ_LNODE_ITER_CURSOR)); 632 633 if (list_empty(&cursor->node)) 634 p = NULL; 635 else 636 p = container_of(cursor, struct task_struct, scx.dsq_list); 637 638 /* skip cursors and tasks that were queued after @cursor init */ 639 do { 640 p = nldsq_next_task(dsq, p, rev); 641 } while (p && unlikely(u32_before(cursor->priv, p->scx.dsq_seq))); 642 643 if (p) { 644 if (rev) 645 list_move_tail(&cursor->node, &p->scx.dsq_list.node); 646 else 647 list_move(&cursor->node, &p->scx.dsq_list.node); 648 } else { 649 list_del_init(&cursor->node); 650 } 651 652 return p; 653 } 654 655 /** 656 * nldsq_cursor_lost_task - Test whether someone else took the task since iteration 657 * @cursor: scx_dsq_list_node initialized with INIT_DSQ_LIST_CURSOR() 658 * @rq: rq @p was on 659 * @dsq: dsq @p was on 660 * @p: target task 661 * 662 * @p is a task returned by nldsq_cursor_next_task(). The locks may have been 663 * dropped and re-acquired inbetween. Verify that no one else took or is in the 664 * process of taking @p from @dsq. 665 * 666 * On %false return, the caller can assume full ownership of @p. 667 */ 668 static bool nldsq_cursor_lost_task(struct scx_dsq_list_node *cursor, 669 struct rq *rq, struct scx_dispatch_q *dsq, 670 struct task_struct *p) 671 { 672 lockdep_assert_rq_held(rq); 673 lockdep_assert_held(&dsq->lock); 674 675 /* 676 * @p could have already left $src_dsq, got re-enqueud, or be in the 677 * process of being consumed by someone else. 678 */ 679 if (unlikely(p->scx.dsq != dsq || 680 u32_before(cursor->priv, p->scx.dsq_seq) || 681 p->scx.holding_cpu >= 0)) 682 return true; 683 684 /* if @p has stayed on @dsq, its rq couldn't have changed */ 685 if (WARN_ON_ONCE(rq != task_rq(p))) 686 return true; 687 688 return false; 689 } 690 691 /* 692 * BPF DSQ iterator. Tasks in a non-local DSQ can be iterated in [reverse] 693 * dispatch order. BPF-visible iterator is opaque and larger to allow future 694 * changes without breaking backward compatibility. Can be used with 695 * bpf_for_each(). See bpf_iter_scx_dsq_*(). 696 */ 697 struct bpf_iter_scx_dsq_kern { 698 struct scx_dsq_list_node cursor; 699 struct scx_dispatch_q *dsq; 700 u64 slice; 701 u64 vtime; 702 } __attribute__((aligned(8))); 703 704 struct bpf_iter_scx_dsq { 705 u64 __opaque[6]; 706 } __attribute__((aligned(8))); 707 708 709 u32 scx_get_task_state(const struct task_struct *p) 710 { 711 return p->scx.flags & SCX_TASK_STATE_MASK; 712 } 713 714 void scx_set_task_state(struct task_struct *p, u32 state) 715 { 716 u32 prev_state = scx_get_task_state(p); 717 bool warn = false; 718 719 switch (state) { 720 case SCX_TASK_NONE: 721 warn = prev_state == SCX_TASK_DEAD; 722 break; 723 case SCX_TASK_INIT_BEGIN: 724 warn = prev_state != SCX_TASK_NONE; 725 break; 726 case SCX_TASK_INIT: 727 warn = prev_state != SCX_TASK_INIT_BEGIN; 728 p->scx.flags |= SCX_TASK_RESET_RUNNABLE_AT; 729 break; 730 case SCX_TASK_READY: 731 warn = !(prev_state == SCX_TASK_INIT || 732 prev_state == SCX_TASK_ENABLED); 733 break; 734 case SCX_TASK_ENABLED: 735 warn = prev_state != SCX_TASK_READY; 736 break; 737 case SCX_TASK_DEAD: 738 warn = !(prev_state == SCX_TASK_NONE || 739 prev_state == SCX_TASK_INIT_BEGIN); 740 break; 741 default: 742 WARN_ONCE(1, "sched_ext: Invalid task state %d -> %d for %s[%d]", 743 prev_state, state, p->comm, p->pid); 744 return; 745 } 746 747 WARN_ONCE(warn, "sched_ext: Invalid task state transition 0x%x -> 0x%x for %s[%d]", 748 prev_state, state, p->comm, p->pid); 749 750 p->scx.flags &= ~SCX_TASK_STATE_MASK; 751 p->scx.flags |= state; 752 } 753 754 /** 755 * scx_task_iter_start - Lock scx_tasks_lock and start a task iteration 756 * @iter: iterator to init 757 * @cgrp: Optional root of cgroup subhierarchy to iterate 758 * 759 * Initialize @iter. Once initialized, @iter must eventually be stopped with 760 * scx_task_iter_stop(). 761 * 762 * If @cgrp is %NULL, scx_tasks is used for iteration and this function returns 763 * with scx_tasks_lock held and @iter->cursor inserted into scx_tasks. 764 * 765 * If @cgrp is not %NULL, @cgrp and its descendants' tasks are walked using 766 * @iter->css_iter. The caller must be holding cgroup_lock() to prevent cgroup 767 * task migrations. 768 * 769 * The two modes of iterations are largely independent and it's likely that 770 * scx_tasks can be removed in favor of always using cgroup iteration if 771 * CONFIG_SCHED_CLASS_EXT depends on CONFIG_CGROUPS. 772 * 773 * scx_tasks_lock and the rq lock may be released using scx_task_iter_unlock() 774 * between this and the first next() call or between any two next() calls. If 775 * the locks are released between two next() calls, the caller is responsible 776 * for ensuring that the task being iterated remains accessible either through 777 * RCU read lock or obtaining a reference count. 778 * 779 * All tasks which existed when the iteration started are guaranteed to be 780 * visited as long as they are not dead. 781 */ 782 void scx_task_iter_start(struct scx_task_iter *iter, struct cgroup *cgrp) 783 { 784 memset(iter, 0, sizeof(*iter)); 785 786 #ifdef CONFIG_EXT_SUB_SCHED 787 if (cgrp) { 788 lockdep_assert_held(&cgroup_mutex); 789 iter->cgrp = cgrp; 790 iter->css_pos = css_next_descendant_pre(NULL, &iter->cgrp->self); 791 css_task_iter_start(iter->css_pos, CSS_TASK_ITER_WITH_DEAD, 792 &iter->css_iter); 793 return; 794 } 795 #endif 796 raw_spin_lock_irq(&scx_tasks_lock); 797 798 iter->cursor = (struct sched_ext_entity){ .flags = SCX_TASK_CURSOR }; 799 list_add(&iter->cursor.tasks_node, &scx_tasks); 800 iter->list_locked = true; 801 } 802 803 static void __scx_task_iter_rq_unlock(struct scx_task_iter *iter) 804 { 805 if (iter->locked_task) { 806 __balance_callbacks(iter->rq, &iter->rf); 807 task_rq_unlock(iter->rq, iter->locked_task, &iter->rf); 808 iter->locked_task = NULL; 809 } 810 } 811 812 /** 813 * scx_task_iter_unlock - Unlock rq and scx_tasks_lock held by a task iterator 814 * @iter: iterator to unlock 815 * 816 * If @iter is in the middle of a locked iteration, it may be locking the rq of 817 * the task currently being visited in addition to scx_tasks_lock. Unlock both. 818 * This function can be safely called anytime during an iteration. The next 819 * iterator operation will automatically restore the necessary locking. 820 */ 821 void scx_task_iter_unlock(struct scx_task_iter *iter) 822 { 823 __scx_task_iter_rq_unlock(iter); 824 if (iter->list_locked) { 825 iter->list_locked = false; 826 raw_spin_unlock_irq(&scx_tasks_lock); 827 } 828 } 829 830 static void __scx_task_iter_maybe_relock(struct scx_task_iter *iter) 831 { 832 if (!iter->list_locked) { 833 raw_spin_lock_irq(&scx_tasks_lock); 834 iter->list_locked = true; 835 } 836 } 837 838 /** 839 * scx_task_iter_relock - Re-acquire scx_tasks_lock and, optionally, @p's rq 840 * @iter: iterator to relock 841 * @p: task whose rq to lock, or %NULL for scx_tasks_lock only 842 * 843 * Counterpart to scx_task_iter_unlock(). Locking @p's rq is optional. Once 844 * re-acquired, both locks are managed by the iterator from here on. 845 */ 846 static void scx_task_iter_relock(struct scx_task_iter *iter, 847 struct task_struct *p) 848 { 849 __scx_task_iter_maybe_relock(iter); 850 if (p) { 851 iter->rq = task_rq_lock(p, &iter->rf); 852 iter->locked_task = p; 853 } 854 } 855 856 /** 857 * scx_task_iter_stop - Stop a task iteration and unlock scx_tasks_lock 858 * @iter: iterator to exit 859 * 860 * Exit a previously initialized @iter. Must be called with scx_tasks_lock held 861 * which is released on return. If the iterator holds a task's rq lock, that rq 862 * lock is also released. See scx_task_iter_start() for details. 863 */ 864 void scx_task_iter_stop(struct scx_task_iter *iter) 865 { 866 #ifdef CONFIG_EXT_SUB_SCHED 867 if (iter->cgrp) { 868 if (iter->css_pos) 869 css_task_iter_end(&iter->css_iter); 870 __scx_task_iter_rq_unlock(iter); 871 return; 872 } 873 #endif 874 __scx_task_iter_maybe_relock(iter); 875 list_del_init(&iter->cursor.tasks_node); 876 scx_task_iter_unlock(iter); 877 } 878 879 /** 880 * scx_task_iter_next - Next task 881 * @iter: iterator to walk 882 * 883 * Visit the next task. See scx_task_iter_start() for details. Locks are dropped 884 * and re-acquired every %SCX_TASK_ITER_BATCH iterations to avoid causing stalls 885 * by holding scx_tasks_lock for too long. 886 */ 887 static struct task_struct *scx_task_iter_next(struct scx_task_iter *iter) 888 { 889 struct list_head *cursor = &iter->cursor.tasks_node; 890 struct sched_ext_entity *pos; 891 892 if (!(++iter->cnt % SCX_TASK_ITER_BATCH)) { 893 scx_task_iter_unlock(iter); 894 cond_resched(); 895 } 896 897 #ifdef CONFIG_EXT_SUB_SCHED 898 if (iter->cgrp) { 899 while (iter->css_pos) { 900 struct task_struct *p; 901 902 p = css_task_iter_next(&iter->css_iter); 903 if (p) 904 return p; 905 906 css_task_iter_end(&iter->css_iter); 907 iter->css_pos = css_next_descendant_pre(iter->css_pos, 908 &iter->cgrp->self); 909 if (iter->css_pos) 910 css_task_iter_start(iter->css_pos, CSS_TASK_ITER_WITH_DEAD, 911 &iter->css_iter); 912 } 913 return NULL; 914 } 915 #endif 916 __scx_task_iter_maybe_relock(iter); 917 918 list_for_each_entry(pos, cursor, tasks_node) { 919 if (&pos->tasks_node == &scx_tasks) 920 return NULL; 921 if (!(pos->flags & SCX_TASK_CURSOR)) { 922 list_move(cursor, &pos->tasks_node); 923 return container_of(pos, struct task_struct, scx); 924 } 925 } 926 927 /* can't happen, should always terminate at scx_tasks above */ 928 BUG(); 929 } 930 931 /** 932 * scx_task_iter_next_locked - Next non-idle task with its rq locked 933 * @iter: iterator to walk 934 * 935 * Visit the non-idle task with its rq lock held. Allows callers to specify 936 * whether they would like to filter out dead tasks. See scx_task_iter_start() 937 * for details. 938 */ 939 struct task_struct *scx_task_iter_next_locked(struct scx_task_iter *iter) 940 { 941 struct task_struct *p; 942 943 __scx_task_iter_rq_unlock(iter); 944 945 while ((p = scx_task_iter_next(iter))) { 946 /* 947 * scx_task_iter is used to prepare and move tasks into SCX 948 * while loading the BPF scheduler and vice-versa while 949 * unloading. The init_tasks ("swappers") should be excluded 950 * from the iteration because: 951 * 952 * - It's unsafe to use __setscheduler_class() on an init_task 953 * to determine the sched_class to use as it won't preserve 954 * its idle_sched_class. 955 * 956 * - ops.init/exit_task() can easily be confused if called with 957 * init_tasks as they, e.g., share PID 0. 958 * 959 * As init_tasks are never scheduled through SCX, they can be 960 * skipped safely. Note that is_idle_task() which tests %PF_IDLE 961 * doesn't work here: 962 * 963 * - %PF_IDLE may not be set for an init_task whose CPU hasn't 964 * yet been onlined. 965 * 966 * - %PF_IDLE can be set on tasks that are not init_tasks. See 967 * play_idle_precise() used by CONFIG_IDLE_INJECT. 968 * 969 * Test for idle_sched_class as only init_tasks are on it. 970 */ 971 if (p->sched_class == &idle_sched_class) 972 continue; 973 974 iter->rq = task_rq_lock(p, &iter->rf); 975 iter->locked_task = p; 976 977 /* 978 * cgroup_task_dead() removes the dead tasks from cset->tasks 979 * after sched_ext_dead() and cgroup iteration may see tasks 980 * which already finished sched_ext_dead(). %SCX_TASK_DEAD is 981 * set by sched_ext_dead() under @p's rq lock. Test it to 982 * avoid visiting tasks which are already dead from SCX POV. 983 */ 984 if (scx_get_task_state(p) == SCX_TASK_DEAD) { 985 __scx_task_iter_rq_unlock(iter); 986 continue; 987 } 988 989 return p; 990 } 991 return NULL; 992 } 993 994 /** 995 * scx_dump_event - Dump an event 'kind' in 'events' to 's' 996 * @s: output seq_buf 997 * @events: event stats 998 * @kind: a kind of event to dump 999 */ 1000 #define scx_dump_event(s, events, kind) do { \ 1001 scx_dump_line(&(s), "%40s: %16lld", #kind, (events)->kind); \ 1002 } while (0) 1003 1004 1005 static void scx_read_events(struct scx_sched *sch, 1006 struct scx_event_stats *events); 1007 1008 static enum scx_enable_state scx_enable_state(void) 1009 { 1010 return atomic_read(&scx_enable_state_var); 1011 } 1012 1013 static enum scx_enable_state scx_set_enable_state(enum scx_enable_state to) 1014 { 1015 return atomic_xchg(&scx_enable_state_var, to); 1016 } 1017 1018 static bool scx_tryset_enable_state(enum scx_enable_state to, 1019 enum scx_enable_state from) 1020 { 1021 int from_v = from; 1022 1023 return atomic_try_cmpxchg(&scx_enable_state_var, &from_v, to); 1024 } 1025 1026 /** 1027 * wait_ops_state - Busy-wait the specified ops state to end 1028 * @p: target task 1029 * @opss: state to wait the end of 1030 * 1031 * Busy-wait for @p to transition out of @opss. This can only be used when the 1032 * state part of @opss is %SCX_QUEUEING or %SCX_DISPATCHING. This function also 1033 * has load_acquire semantics to ensure that the caller can see the updates made 1034 * in the enqueueing and dispatching paths. 1035 */ 1036 static void wait_ops_state(struct task_struct *p, unsigned long opss) 1037 { 1038 do { 1039 cpu_relax(); 1040 } while (atomic_long_read_acquire(&p->scx.ops_state) == opss); 1041 } 1042 1043 static inline bool __cpu_valid(s32 cpu) 1044 { 1045 return likely(cpu >= 0 && cpu < nr_cpu_ids && cpu_possible(cpu)); 1046 } 1047 1048 /** 1049 * scx_cpu_valid - Verify a cpu number, to be used on ops input args 1050 * @sch: scx_sched to abort on error 1051 * @cpu: cpu number which came from a BPF ops 1052 * @where: extra information reported on error 1053 * 1054 * @cpu is a cpu number which came from the BPF scheduler and can be any value. 1055 * Verify that it is in range and one of the possible cpus. If invalid, trigger 1056 * an ops error. 1057 */ 1058 bool scx_cpu_valid(struct scx_sched *sch, s32 cpu, const char *where) 1059 { 1060 if (__cpu_valid(cpu)) { 1061 return true; 1062 } else { 1063 scx_error(sch, "invalid CPU %d%s%s", cpu, where ? " " : "", where ?: ""); 1064 return false; 1065 } 1066 } 1067 1068 static void deferred_bal_cb_workfn(struct rq *rq) 1069 { 1070 run_deferred(rq); 1071 } 1072 1073 static void deferred_irq_workfn(struct irq_work *irq_work) 1074 { 1075 struct rq *rq = container_of(irq_work, struct rq, scx.deferred_irq_work); 1076 1077 raw_spin_rq_lock(rq); 1078 run_deferred(rq); 1079 scx_rq_lock_drop(rq); 1080 raw_spin_rq_unlock(rq); 1081 } 1082 1083 /** 1084 * schedule_deferred - Schedule execution of deferred actions on an rq 1085 * @rq: target rq 1086 * 1087 * Schedule execution of deferred actions on @rq. Deferred actions are executed 1088 * with @rq locked but unpinned, and thus can unlock @rq to e.g. migrate tasks 1089 * to other rqs. 1090 */ 1091 static void schedule_deferred(struct rq *rq) 1092 { 1093 /* 1094 * This is the fallback when schedule_deferred_locked() can't use 1095 * the cheaper balance callback or wakeup hook paths (the target 1096 * CPU is not in dispatch or wakeup). Currently, this is primarily 1097 * hit by reenqueue operations targeting a remote CPU. 1098 * 1099 * Queue on the target CPU. The deferred work can run from any CPU 1100 * correctly - the _locked() path already processes remote rqs from 1101 * the calling CPU - but targeting the owning CPU allows IPI delivery 1102 * without waiting for the calling CPU to re-enable IRQs and is 1103 * cheaper as the reenqueue runs locally. 1104 */ 1105 irq_work_queue_on(&rq->scx.deferred_irq_work, cpu_of(rq)); 1106 } 1107 1108 /** 1109 * schedule_deferred_locked - Schedule execution of deferred actions on an rq 1110 * @rq: target rq 1111 * 1112 * Schedule execution of deferred actions on @rq. Equivalent to 1113 * schedule_deferred() but requires @rq to be locked and can be more efficient. 1114 */ 1115 static void schedule_deferred_locked(struct rq *rq) 1116 { 1117 lockdep_assert_rq_held(rq); 1118 1119 /* 1120 * If in the middle of waking up a task, task_woken_scx() will be called 1121 * afterwards which will then run the deferred actions, no need to 1122 * schedule anything. 1123 */ 1124 if (rq->scx.flags & SCX_RQ_IN_WAKEUP) 1125 return; 1126 1127 /* Don't do anything if there already is a deferred operation. */ 1128 if (rq->scx.flags & SCX_RQ_BAL_CB_PENDING) 1129 return; 1130 1131 /* 1132 * If in dispatch, the balance callbacks will be called before rq lock 1133 * is released. Schedule one. 1134 * 1135 * 1136 * We can't directly insert the callback into the 1137 * rq's list: The call can drop its lock and make the pending balance 1138 * callback visible to unrelated code paths that call rq_pin_lock(). 1139 * 1140 * Just let dispatch_one() know that it must do it itself. 1141 */ 1142 if (rq->scx.flags & SCX_RQ_IN_DISPATCH) { 1143 rq->scx.flags |= SCX_RQ_BAL_CB_PENDING; 1144 return; 1145 } 1146 1147 /* 1148 * No scheduler hooks available. Use the generic irq_work path. The 1149 * above WAKEUP and DISPATCH paths should cover most of the cases and 1150 * the time to IRQ re-enable shouldn't be long. 1151 */ 1152 schedule_deferred(rq); 1153 } 1154 1155 #ifdef CONFIG_NO_HZ_FULL 1156 static void scx_proxy_tick_bal_cb(struct rq *rq) 1157 { 1158 sched_update_tick_dependency(rq); 1159 } 1160 1161 static void scx_proxy_update_tick(struct rq *rq, struct task_struct *next) 1162 { 1163 bool proxy = next != rq->donor; 1164 bool was_proxy = rq->scx.flags & SCX_RQ_PROXY_TICK; 1165 1166 if (likely(proxy == was_proxy)) 1167 return; 1168 1169 if (proxy) { 1170 /* Keep proxy execution tick-driven for now. */ 1171 rq->scx.flags |= SCX_RQ_PROXY_TICK; 1172 tick_nohz_dep_set_cpu(cpu_of(rq), TICK_DEP_BIT_SCHED); 1173 } else { 1174 rq->scx.flags &= ~SCX_RQ_PROXY_TICK; 1175 /* 1176 * The selected donor is already visible, but rq->curr still 1177 * identifies the outgoing execution context. Reevaluate after 1178 * context_switch() updates rq->curr so sched_can_stop_tick() sees 1179 * the complete selection. 1180 */ 1181 queue_balance_callback(rq, &rq->scx.proxy_tick_bal_cb, 1182 scx_proxy_tick_bal_cb); 1183 } 1184 } 1185 #endif 1186 1187 /* 1188 * Complete sched_ext bookkeeping after proxy resolution and retry tasks which 1189 * couldn't be reenqueued by an earlier reject DSQ drain. 1190 */ 1191 void scx_proxy_reenqueue_retry(struct rq *rq, struct task_struct *next) 1192 { 1193 lockdep_assert_rq_held(rq); 1194 1195 #ifdef CONFIG_NO_HZ_FULL 1196 if (scx_enabled() && tick_nohz_full_cpu(cpu_of(rq))) 1197 scx_proxy_update_tick(rq, next); 1198 #endif 1199 1200 /* 1201 * A higher priority class may wake up while @rq is transiently idle 1202 * for proxy resolution. wakeup_preempt_scx() isn't invoked in that 1203 * case, so reenqueue IMMED donors parked on the local DSQ here. 1204 */ 1205 if (rq->scx.nr_immed && sched_class_above(rq->next_class, &ext_sched_class)) 1206 scx_schedule_reenq_local(rq, 0); 1207 1208 if (rq->scx.flags & SCX_RQ_PROXY_RETRY) { 1209 rq->scx.flags &= ~SCX_RQ_PROXY_RETRY; 1210 schedule_deferred_locked(rq); 1211 } 1212 } 1213 1214 void schedule_dsq_reenq(struct scx_sched *sch, struct scx_dispatch_q *dsq, 1215 u64 reenq_flags, struct rq *locked_rq) 1216 { 1217 struct rq *rq; 1218 1219 /* 1220 * Allowing reenqueues doesn't make sense while bypassing. This also 1221 * blocks from new reenqueues to be scheduled on dead scheds. 1222 */ 1223 if (unlikely(READ_ONCE(sch->bypass_depth))) 1224 return; 1225 1226 if (dsq->id == SCX_DSQ_LOCAL) { 1227 rq = container_of(dsq, struct rq, scx.local_dsq); 1228 1229 /* 1230 * An inactive cpu's local DSQ holds only tasks that are bound 1231 * to it or are being moved off, so a reenq of it is pointless. 1232 * Once balance push is installed, queue_balance_callback() also 1233 * drops the callback that would run a reenq requested from 1234 * dispatch, and irq_work_queue_on() can't reach an offline cpu. 1235 * The reenq's node would then stay on this rq's list after 1236 * @sch's pcpu is freed. 1237 */ 1238 if (unlikely(!cpu_active(cpu_of(rq)))) 1239 return; 1240 1241 /* 1242 * A sub-sched lacking baseline access on the target cid has no 1243 * business triggering IPIs. The lockless test is fine: slipping 1244 * through right after a revoke is harmless and a wrong denial 1245 * can't happen - if the caller has seen its ownership, so does 1246 * this test. 1247 */ 1248 if (unlikely(scx_missing_caps(sch, cpu_of(rq), SCX_CAP_BASE))) { 1249 __scx_add_event(sch, SCX_EV_SUB_REENQ_DENIED, 1); 1250 return; 1251 } 1252 1253 struct scx_sched_pcpu *sch_pcpu = per_cpu_ptr(sch->pcpu, cpu_of(rq)); 1254 struct scx_deferred_reenq_local *drl = &sch_pcpu->deferred_reenq_local; 1255 1256 /* 1257 * Pairs with smp_mb() in process_deferred_reenq_locals() and 1258 * guarantees that there is a reenq_local() afterwards. 1259 */ 1260 smp_mb(); 1261 1262 if (list_empty(&drl->node) || 1263 (READ_ONCE(drl->flags) & reenq_flags) != reenq_flags) { 1264 1265 guard(raw_spinlock_irqsave)(&rq->scx.deferred_reenq_lock); 1266 1267 if (list_empty(&drl->node)) 1268 list_move_tail(&drl->node, &rq->scx.deferred_reenq_locals); 1269 WRITE_ONCE(drl->flags, drl->flags | reenq_flags); 1270 } 1271 } else if (!(dsq->id & SCX_DSQ_FLAG_BUILTIN)) { 1272 rq = this_rq(); 1273 1274 struct scx_dsq_pcpu *dsq_pcpu = per_cpu_ptr(dsq->pcpu_user, cpu_of(rq)); 1275 struct scx_deferred_reenq_user *dru = &dsq_pcpu->deferred_reenq_user; 1276 1277 /* 1278 * Pairs with smp_mb() in process_deferred_reenq_users() and 1279 * guarantees that there is a reenq_user() afterwards. 1280 */ 1281 smp_mb(); 1282 1283 if (list_empty(&dru->node) || 1284 (READ_ONCE(dru->flags) & reenq_flags) != reenq_flags) { 1285 1286 guard(raw_spinlock_irqsave)(&rq->scx.deferred_reenq_lock); 1287 1288 /* @dsq is being destroyed, see free_dsq_irq_workfn() */ 1289 if (unlikely(READ_ONCE(dsq->id) == SCX_DSQ_INVALID)) 1290 return; 1291 1292 if (list_empty(&dru->node)) 1293 list_move_tail(&dru->node, &rq->scx.deferred_reenq_users); 1294 WRITE_ONCE(dru->flags, dru->flags | reenq_flags); 1295 } 1296 } else { 1297 /* destroyed since the caller resolved it, nothing to reenq */ 1298 if (READ_ONCE(dsq->id) != SCX_DSQ_INVALID) 1299 scx_error(sch, "DSQ 0x%llx not allowed for reenq", dsq->id); 1300 return; 1301 } 1302 1303 if (rq == locked_rq) 1304 schedule_deferred_locked(rq); 1305 else 1306 schedule_deferred(rq); 1307 } 1308 1309 /* 1310 * p->scx.slice_oob packs an out-of-band slice request into one atomic64. A zero 1311 * word means no request. Otherwise the fields are: 1312 * 1313 * 63 SCX_SLICE_OOB_PENDING, set on every request 1314 * 62-43 lower bits of issuing scheduler's id 1315 * 42-0 requested slice duration in nsecs 1316 * 1317 * A duration of SCX_SLICE_OOB_DUR_MASK means SCX_SLICE_INF. A finite dur 1318 * saturates at SCX_SLICE_OOB_DUR_MASK - 1. The id is used to detect and ignore 1319 * a request that outlived a task ownership change. 1320 * 1321 * Only the low 20 bits of sch->id are packed, which is enough to make 1322 * collisions practically impossible. A theoretical collision just lets a stale 1323 * request through once. 1324 */ 1325 enum scx_slice_oob_consts { 1326 SCX_SLICE_OOB_DUR_BITS = 43, 1327 SCX_SLICE_OOB_ID_BITS = 64 - SCX_SLICE_OOB_DUR_BITS - 1, 1328 1329 SCX_SLICE_OOB_DUR_MASK = (1LLU << SCX_SLICE_OOB_DUR_BITS) - 1, 1330 SCX_SLICE_OOB_ID_SHIFT = SCX_SLICE_OOB_DUR_BITS, 1331 SCX_SLICE_OOB_ID_MASK = (1LLU << SCX_SLICE_OOB_ID_BITS) - 1, 1332 SCX_SLICE_OOB_PENDING = 1LLU << 63, 1333 }; 1334 1335 /* 1336 * Slice and dsq_vtime write rules 1337 * 1338 * While @p is running, sleeping or queued on an rq-owned DSQ, both fields are 1339 * protected by the rq lock. While running, the rq lock is required because 1340 * update_curr_scx() RMWs the slice and the cap check for slice extension is 1341 * only reliable under the rq lock. 1342 * 1343 * While @p is queued on a user DSQ or on the BPF side, the kernel neither 1344 * consumes nor decides on the fields. Synchronizing the writers is the BPF 1345 * scheduler's responsibility. An rq-locked scx_bpf_task_set_slice() write and a 1346 * concurrent DSQ insertion commit can race each other and whichever lands last 1347 * wins. 1348 * 1349 * A DSQ insert kfunc doesn't update the fields directly. The verdict carries 1350 * the values and apply_slice_vtime() commits them at the insertion. 1351 * 1352 * scx_bpf_task_set_slice() may be called from any context and writes directly 1353 * only if @p's rq lock is already held, otherwise it bounces through 1354 * p->scx.slice_oob, applied under @p's rq lock at the next slice consideration. 1355 * 1356 * While %SCX_TASK_PROTECTED is set, every scheduler-reachable slice update is 1357 * refused. See set_task_slice_keep_oob(). 1358 * 1359 * dsq_vtime orders the next PRIQ insertion and has no running-side consumer, so 1360 * scx_bpf_task_set_dsq_vtime() writes it directly. Fork-time init and direct 1361 * BPF stores from non-cid-form schedulers are outside these rules. 1362 */ 1363 1364 /* clear a pending slice request */ 1365 static void clear_task_slice_oob(struct task_struct *p) 1366 { 1367 if (unlikely(atomic64_read(&p->scx.slice_oob))) 1368 atomic64_set(&p->scx.slice_oob, 0); 1369 } 1370 1371 /** 1372 * dsq_insert_head - FIFO head insertion honoring %SCX_TASK_PROTECTED 1373 * @dsq: DSQ to insert into 1374 * @p: task being inserted 1375 * 1376 * A HEAD insert should land behind any leading protected tasks. Return %true 1377 * indicates whether @p became the first entry. 1378 */ 1379 static bool dsq_insert_head(struct scx_dispatch_q *dsq, struct task_struct *p) 1380 { 1381 struct list_head *pos = &dsq->list; 1382 struct scx_dsq_list_node *node; 1383 1384 /* 1385 * Only rq-owned DSQs can hold protected tasks and the associated rq 1386 * lock keeps their flags stable. 1387 */ 1388 if (!dsq_is_rq_owned(dsq)) { 1389 list_add(&p->scx.dsq_list.node, &dsq->list); 1390 return true; 1391 } 1392 1393 list_for_each_entry(node, &dsq->list, node) { 1394 struct task_struct *q; 1395 1396 if (WARN_ON_ONCE(node->flags & SCX_DSQ_LNODE_ITER_CURSOR)) 1397 continue; 1398 1399 q = container_of(node, struct task_struct, scx.dsq_list); 1400 if (!(q->scx.flags & SCX_TASK_PROTECTED)) 1401 break; 1402 1403 pos = &node->node; 1404 } 1405 1406 list_add(&p->scx.dsq_list.node, pos); 1407 1408 return pos == &dsq->list; 1409 } 1410 1411 /** 1412 * set_task_slice_keep_oob - Set @p's slice, leaving any pending oob request 1413 * @p: task of interest 1414 * @slice: slice to set 1415 * 1416 * While %SCX_TASK_PROTECTED is set, BPF schedulers may not modify the slice. 1417 * Refuse and return %false. 1418 */ 1419 static bool set_task_slice_keep_oob(struct task_struct *p, u64 slice) 1420 { 1421 lockdep_assert_rq_held(task_rq(p)); 1422 1423 if (unlikely(p->scx.flags & SCX_TASK_PROTECTED)) 1424 return false; 1425 1426 p->scx.slice = slice; 1427 return true; 1428 } 1429 1430 /* set @p's slice, superseding any pending out-of-band request */ 1431 bool scx_set_task_slice(struct task_struct *p, u64 slice) 1432 { 1433 if (!set_task_slice_keep_oob(p, slice)) 1434 return false; 1435 clear_task_slice_oob(p); 1436 return true; 1437 } 1438 1439 /** 1440 * scx_task_slice_ended - @p's slice is consumed or given up 1441 * @rq: rq @p is on 1442 * @p: task of interest 1443 * 1444 * End what rides on the slice - the protection, and the rescue if @p is being 1445 * rescued. 1446 * 1447 * A dequeue normally ends the slice too. The exception is a save/restore pair 1448 * on the running task. Attribute changes like renice cycle the task through 1449 * dequeue and enqueue while it keeps executing, so the slice continues. A 1450 * queued task instead loses its DSQ position on any dequeue and the slice ends 1451 * with it. 1452 */ 1453 void scx_task_slice_ended(struct rq *rq, struct task_struct *p) 1454 { 1455 lockdep_assert_rq_held(rq); 1456 1457 p->scx.flags &= ~SCX_TASK_PROTECTED; 1458 if (unlikely(p == scx_rescuee(rq))) 1459 scx_rescue_end(rq); 1460 } 1461 1462 /* request @p's slice to be set to @slice, see the write rules above */ 1463 static void set_task_slice_oob(struct scx_sched *sch, struct task_struct *p, u64 slice) 1464 { 1465 u64 dur; 1466 1467 if (slice == SCX_SLICE_INF) { 1468 dur = SCX_SLICE_OOB_DUR_MASK; 1469 } else if (unlikely(slice >= SCX_SLICE_OOB_DUR_MASK)) { 1470 dur = SCX_SLICE_OOB_DUR_MASK - 1; 1471 scx_add_event(sch, SCX_EV_SLICE_CLAMPED, 1); 1472 } else { 1473 dur = slice; 1474 } 1475 1476 atomic64_set(&p->scx.slice_oob, SCX_SLICE_OOB_PENDING | 1477 ((sch->id & SCX_SLICE_OOB_ID_MASK) << SCX_SLICE_OOB_ID_SHIFT) | dur); 1478 } 1479 1480 /* 1481 * Apply a pending out-of-band slice request under @rq's lock. A request whose 1482 * packed id no longer matches @p's current owner is dropped. An extension needs 1483 * baseline cpu access on @p's cid, shortening is always allowed, and a 1484 * protected slice refuses both. %SCX_EV_SLICE_DENIED counts the denials. See 1485 * the write rules above. 1486 */ 1487 static void apply_task_slice_oob(struct rq *rq, struct task_struct *p) 1488 { 1489 u64 oob, dur, slice; 1490 1491 lockdep_assert_rq_held(rq); 1492 1493 if (likely(!atomic64_read(&p->scx.slice_oob))) 1494 return; 1495 1496 oob = atomic64_xchg(&p->scx.slice_oob, 0); 1497 if (unlikely(!oob)) 1498 return; 1499 1500 /* the issuing scheduler no longer owns @p, drop the request */ 1501 if (unlikely(((oob >> SCX_SLICE_OOB_ID_SHIFT) & SCX_SLICE_OOB_ID_MASK) != 1502 (scx_task_sched(p)->id & SCX_SLICE_OOB_ID_MASK))) 1503 return; 1504 1505 dur = oob & SCX_SLICE_OOB_DUR_MASK; 1506 slice = dur == SCX_SLICE_OOB_DUR_MASK ? SCX_SLICE_INF : dur; 1507 1508 if (slice > p->scx.slice && 1509 unlikely(scx_missing_caps(scx_task_sched(p), cpu_of(rq), SCX_CAP_BASE))) { 1510 __scx_add_event(scx_task_sched(p), SCX_EV_SLICE_DENIED, 1); 1511 return; 1512 } 1513 1514 if (unlikely(!set_task_slice_keep_oob(p, slice))) 1515 __scx_add_event(scx_task_sched(p), SCX_EV_SLICE_DENIED, 1); 1516 } 1517 1518 /* 1519 * A dsq insert kfunc doesn't write slice or dsq_vtime. The verdict carries them 1520 * and they are committed here, at the insertion. A zero @slice keeps the 1521 * current value, floored at 1 so the task isn't treated as expired. 1522 */ 1523 static void apply_slice_vtime(struct task_struct *p, u64 slice, u64 vtime, u64 enq_flags) 1524 { 1525 if (slice) { 1526 p->scx.slice = slice; 1527 /* 1528 * An explicit slice supersedes a pending oob request. A carried 1529 * default refill is not an explicit request and must keep it. 1530 */ 1531 if (!(enq_flags & SCX_ENQ_SLICE_DFL)) 1532 clear_task_slice_oob(p); 1533 } else if (!p->scx.slice) { 1534 p->scx.slice = 1; 1535 } 1536 1537 if (enq_flags & SCX_ENQ_DSQ_PRIQ) 1538 p->scx.dsq_vtime = vtime; 1539 } 1540 1541 static void update_curr_scx(struct rq *rq) 1542 { 1543 struct task_struct *donor; 1544 s64 delta_exec; 1545 1546 /* 1547 * update_curr_scx() is selected through rq->donor->sched_class, not 1548 * rq->curr->sched_class, so @donor is always an EXT task here. If an EXT 1549 * owner executes for a FAIR donor, FAIR's update_curr() runs instead. 1550 */ 1551 donor = rq->donor; 1552 1553 /* apply even on 0 delta_exec, callers may still act on the slice */ 1554 apply_task_slice_oob(rq, donor); 1555 1556 delta_exec = update_curr_common(rq); 1557 if (unlikely(delta_exec <= 0)) 1558 return; 1559 1560 if (donor->scx.slice != SCX_SLICE_INF) 1561 donor->scx.slice -= min_t(u64, donor->scx.slice, delta_exec); 1562 1563 if (unlikely(donor == scx_rescuee(rq))) 1564 scx_rescue_charge(rq, delta_exec); 1565 1566 dl_server_update(&rq->ext_server, delta_exec); 1567 } 1568 1569 static bool scx_dsq_priq_less(struct rb_node *node_a, 1570 const struct rb_node *node_b) 1571 { 1572 const struct task_struct *a = 1573 container_of(node_a, struct task_struct, scx.dsq_priq); 1574 const struct task_struct *b = 1575 container_of(node_b, struct task_struct, scx.dsq_priq); 1576 1577 return time_before64(a->scx.dsq_vtime, b->scx.dsq_vtime); 1578 } 1579 1580 static void dsq_inc_nr(struct scx_dispatch_q *dsq, struct task_struct *p, u64 enq_flags) 1581 { 1582 /* scx_bpf_dsq_nr_queued() reads ->nr without locking, use WRITE_ONCE() */ 1583 WRITE_ONCE(dsq->nr, dsq->nr + 1); 1584 1585 /* 1586 * Once @p reaches a local DSQ, it can only leave it by being dispatched 1587 * to the CPU or dequeued. In both cases, the only way @p can go back to 1588 * the BPF sched is through enqueueing. If being inserted into a local 1589 * DSQ with IMMED, persist the state until the next enqueueing event in 1590 * scx_do_enqueue_task() so that we can maintain IMMED protection 1591 * through e.g. SAVE/RESTORE cycles and slice extensions. 1592 */ 1593 if (enq_flags & SCX_ENQ_IMMED) { 1594 if (unlikely(dsq->id != SCX_DSQ_LOCAL)) { 1595 WARN_ON_ONCE(!(enq_flags & SCX_ENQ_GDSQ_FALLBACK)); 1596 return; 1597 } 1598 p->scx.flags |= SCX_TASK_IMMED; 1599 } 1600 1601 if (p->scx.flags & SCX_TASK_IMMED) { 1602 struct rq *rq = container_of(dsq, struct rq, scx.local_dsq); 1603 1604 if (WARN_ON_ONCE(dsq->id != SCX_DSQ_LOCAL)) 1605 return; 1606 1607 rq->scx.nr_immed++; 1608 1609 /* 1610 * If @rq already had other tasks or the current task is not 1611 * done yet, @p can't go on the CPU immediately. Re-enqueue. 1612 */ 1613 if (unlikely(dsq->nr > 1 || !rq_is_open(rq, enq_flags))) 1614 scx_schedule_reenq_local(rq, 0); 1615 } 1616 } 1617 1618 static void dsq_dec_nr(struct scx_dispatch_q *dsq, struct task_struct *p) 1619 { 1620 /* see dsq_inc_nr() */ 1621 WRITE_ONCE(dsq->nr, dsq->nr - 1); 1622 1623 if (p->scx.flags & SCX_TASK_IMMED) { 1624 struct rq *rq = container_of(dsq, struct rq, scx.local_dsq); 1625 1626 if (WARN_ON_ONCE(dsq->id != SCX_DSQ_LOCAL) || 1627 WARN_ON_ONCE(rq->scx.nr_immed <= 0)) 1628 return; 1629 1630 rq->scx.nr_immed--; 1631 } 1632 } 1633 1634 static void refill_task_slice_dfl(struct scx_sched *sch, struct task_struct *p) 1635 { 1636 /* 1637 * A default refill is not an explicit request, so it must not drop a 1638 * pending out-of-band one, which is applied when @p next runs. 1639 */ 1640 set_task_slice_keep_oob(p, READ_ONCE(sch->slice_dfl)); 1641 __scx_add_event(sch, SCX_EV_REFILL_SLICE_DFL, 1); 1642 } 1643 1644 /* 1645 * Return true if @p is moving due to an internal SCX migration, false 1646 * otherwise. 1647 */ 1648 static inline bool task_scx_migrating(struct task_struct *p) 1649 { 1650 /* 1651 * We only need to check sticky_cpu: it is set to the destination 1652 * CPU in move_remote_task_to_local_dsq() before deactivate_task() 1653 * and cleared when the task is enqueued on the destination, so it 1654 * is only non-negative during an internal SCX migration. 1655 */ 1656 return p->scx.sticky_cpu >= 0; 1657 } 1658 1659 /* Must be called under the lock serializing @p's custody transfers. */ 1660 static bool task_leave_custody(struct task_struct *p) 1661 { 1662 if (!(p->scx.flags & SCX_TASK_IN_CUSTODY) || task_scx_migrating(p)) 1663 return false; 1664 1665 p->scx.flags &= ~SCX_TASK_IN_CUSTODY; 1666 return true; 1667 } 1668 1669 /* 1670 * A task with an infinite slice may be running with its tick stopped. Lazy 1671 * rescheduling doesn't send an IPI, so restore the tick dependency to guarantee 1672 * that the lazy request is promoted by a real scheduler tick. Set the lazy 1673 * request first so that the dependency update's IPI can also serve it on return 1674 * to user space. 1675 */ 1676 static void scx_resched_curr_lazy(struct rq *rq) 1677 { 1678 resched_curr_lazy(rq); 1679 1680 if (rq->scx.flags & SCX_RQ_CAN_STOP_TICK) { 1681 rq->scx.flags &= ~SCX_RQ_CAN_STOP_TICK; 1682 if (rq->clock_update_flags < RQCF_UPDATED) 1683 update_rq_clock(rq); 1684 update_other_load_avgs(rq); 1685 sched_update_tick_dependency(rq); 1686 } 1687 } 1688 1689 static void rq_owned_post_enq(struct scx_sched *sch, struct rq *rq, 1690 struct scx_dispatch_q *dsq, struct task_struct *p, 1691 u64 enq_flags) 1692 { 1693 if (task_leave_custody(p) && SCX_HAS_OP(sch, dequeue)) 1694 SCX_CALL_OP_TASK(sch, dequeue, rq, p, 0); 1695 1696 /* 1697 * Only local inserts get the wakeup treatment below. Rejects kick a 1698 * deferred reenq and rescue parks are paced by the rescue timer. Proxy 1699 * rejects which aren't ready when drained request a later retry from 1700 * scx_proxy_reenqueue_retry(). 1701 */ 1702 if (unlikely(dsq->id != SCX_DSQ_LOCAL)) { 1703 if (dsq->id == SCX_DSQ_REJECT) 1704 schedule_deferred_locked(rq); 1705 return; 1706 } 1707 1708 /* 1709 * Note that @rq's lock may be dropped between this enqueue and @p 1710 * actually getting on CPU. This gives higher-class tasks (e.g. RT) 1711 * an opportunity to wake up on @rq and prevent @p from running. 1712 * Here are some concrete examples: 1713 * 1714 * Example 1: 1715 * 1716 * We dispatch two tasks from a single ops.dispatch(): 1717 * - First, a local task to this CPU's local DSQ; 1718 * - Second, a local/remote task to a remote CPU's local DSQ. 1719 * We must drop the local rq lock in order to finish the second 1720 * dispatch. In that time, an RT task can wake up on the local rq. 1721 * 1722 * Example 2: 1723 * 1724 * We dispatch a local/remote task to a remote CPU's local DSQ. 1725 * We must drop the remote rq lock before the dispatched task can run, 1726 * which gives an RT task an opportunity to wake up on the remote rq. 1727 * 1728 * Both examples work the same if we replace dispatching with moving 1729 * the tasks from a user-created DSQ. 1730 * 1731 * We must detect these wakeups so that we can re-enqueue IMMED tasks 1732 * from @rq's local DSQ. scx_wakeup_preempt() serves exactly this 1733 * purpose, but for it to be invoked, we must ensure that we bump 1734 * @rq->next_class to &ext_sched_class if it's currently idle. 1735 * 1736 * wakeup_preempt() does the bumping, and since we only invoke it if 1737 * @rq->next_class is below &ext_sched_class, it will also 1738 * resched_curr(rq). 1739 */ 1740 if (sched_class_above(p->sched_class, rq->next_class)) 1741 wakeup_preempt(rq, p, 0); 1742 1743 /* 1744 * If @rq is in dispatch, the CPU is already vacant and looking for the 1745 * next task to run. No need to preempt or trigger resched after moving 1746 * @p into its local DSQ. 1747 * Note that the wakeup_preempt() above may have already triggered 1748 * a resched if @rq->next_class was idle. It's harmless, since 1749 * need_resched is cleared immediately after task pick. 1750 */ 1751 if (rq->scx.flags & SCX_RQ_IN_DISPATCH) 1752 return; 1753 1754 if ((enq_flags & (SCX_ENQ_PREEMPT | SCX_ENQ_PREEMPT_LAZY)) && 1755 p != rq->donor && rq->donor->sched_class == &ext_sched_class) { 1756 if (likely(scx_set_task_slice(rq->donor, 0))) { 1757 if (enq_flags & SCX_ENQ_PREEMPT) 1758 resched_curr(rq); 1759 else 1760 scx_resched_curr_lazy(rq); 1761 } else { 1762 __scx_add_event(sch, SCX_EV_SLICE_DENIED, 1); 1763 } 1764 } 1765 } 1766 1767 static void scx_dispatch_enqueue(struct scx_sched *sch, struct rq *rq, 1768 struct scx_dispatch_q *dsq, struct task_struct *p, 1769 u64 slice, u64 vtime, u64 enq_flags) 1770 { 1771 bool is_rq_owned = dsq_is_rq_owned(dsq); 1772 1773 if (dsq->id == SCX_DSQ_LOCAL) 1774 dsq = scx_resolve_local_dsq(sch, rq, p, &enq_flags); 1775 1776 WARN_ON_ONCE(p->scx.dsq || !list_empty(&p->scx.dsq_list.node)); 1777 WARN_ON_ONCE((p->scx.dsq_flags & SCX_TASK_DSQ_ON_PRIQ) || 1778 !RB_EMPTY_NODE(&p->scx.dsq_priq)); 1779 1780 if (!is_rq_owned) { 1781 raw_spin_lock_nested(&dsq->lock, 1782 (enq_flags & SCX_ENQ_NESTED) ? SINGLE_DEPTH_NESTING : 0); 1783 1784 if (unlikely(dsq->id == SCX_DSQ_INVALID)) { 1785 scx_error(sch, "attempting to dispatch to a destroyed dsq"); 1786 /* fall back to the global dsq */ 1787 raw_spin_unlock(&dsq->lock); 1788 dsq = find_global_dsq(sch, task_cpu(p)); 1789 raw_spin_lock(&dsq->lock); 1790 } 1791 } 1792 1793 if (unlikely((dsq->id & SCX_DSQ_FLAG_BUILTIN) && 1794 (enq_flags & SCX_ENQ_DSQ_PRIQ))) { 1795 /* 1796 * SCX_DSQ_LOCAL and SCX_DSQ_GLOBAL DSQs always consume from 1797 * their FIFO queues. To avoid confusion and accidentally 1798 * starving vtime-dispatched tasks by FIFO-dispatched tasks, we 1799 * disallow any internal DSQ from doing vtime ordering of 1800 * tasks. 1801 */ 1802 scx_error(sch, "cannot use vtime ordering for built-in DSQs"); 1803 enq_flags &= ~SCX_ENQ_DSQ_PRIQ; 1804 } 1805 1806 /* 1807 * @dsq is locked and @enq_flags is sanitized. Commit the carried slice 1808 * and vtime before the PRIQ insertion below reads the new dsq_vtime. 1809 */ 1810 if (enq_flags & SCX_ENQ_APPLY_SLICE) 1811 apply_slice_vtime(p, slice, vtime, enq_flags); 1812 1813 if (enq_flags & SCX_ENQ_DSQ_PRIQ) { 1814 struct rb_node *rbp; 1815 1816 /* 1817 * A PRIQ DSQ shouldn't be using FIFO enqueueing. As tasks are 1818 * linked to both the rbtree and list on PRIQs, this can only be 1819 * tested easily when adding the first task. 1820 */ 1821 if (unlikely(RB_EMPTY_ROOT(&dsq->priq) && 1822 nldsq_next_task(dsq, NULL, false))) 1823 scx_error(sch, "DSQ ID 0x%016llx already had FIFO-enqueued tasks", 1824 dsq->id); 1825 1826 p->scx.dsq_flags |= SCX_TASK_DSQ_ON_PRIQ; 1827 rb_add(&p->scx.dsq_priq, &dsq->priq, scx_dsq_priq_less); 1828 1829 /* 1830 * Find the previous task and insert after it on the list so 1831 * that @dsq->list is vtime ordered. 1832 */ 1833 rbp = rb_prev(&p->scx.dsq_priq); 1834 if (rbp) { 1835 struct task_struct *prev = 1836 container_of(rbp, struct task_struct, 1837 scx.dsq_priq); 1838 list_add(&p->scx.dsq_list.node, &prev->scx.dsq_list.node); 1839 /* first task unchanged - no update needed */ 1840 } else { 1841 list_add(&p->scx.dsq_list.node, &dsq->list); 1842 /* not builtin and new task is at head - use fastpath */ 1843 rcu_assign_pointer(dsq->first_task, p); 1844 } 1845 } else { 1846 /* a FIFO DSQ shouldn't be using PRIQ enqueuing */ 1847 if (unlikely(!RB_EMPTY_ROOT(&dsq->priq))) 1848 scx_error(sch, "DSQ ID 0x%016llx already had PRIQ-enqueued tasks", 1849 dsq->id); 1850 1851 if (enq_flags & (SCX_ENQ_HEAD | SCX_ENQ_PREEMPT | SCX_ENQ_PREEMPT_LAZY)) { 1852 /* new task inserted at head - use fastpath */ 1853 if (dsq_insert_head(dsq, p) && !(dsq->id & SCX_DSQ_FLAG_BUILTIN)) 1854 rcu_assign_pointer(dsq->first_task, p); 1855 } else { 1856 /* 1857 * dsq->list can contain parked BPF iterator cursors, so 1858 * list_empty() here isn't a reliable proxy for "no real 1859 * task in the DSQ". Test dsq->first_task directly. 1860 */ 1861 list_add_tail(&p->scx.dsq_list.node, &dsq->list); 1862 if (!dsq->first_task && !(dsq->id & SCX_DSQ_FLAG_BUILTIN)) 1863 rcu_assign_pointer(dsq->first_task, p); 1864 } 1865 } 1866 1867 /* seq records the order tasks are queued, used by BPF DSQ iterator */ 1868 WRITE_ONCE(dsq->seq, dsq->seq + 1); 1869 p->scx.dsq_seq = dsq->seq; 1870 1871 dsq_inc_nr(dsq, p, enq_flags); 1872 p->scx.dsq = dsq; 1873 1874 /* 1875 * Update custody and call ops.dequeue() before clearing ops_state: 1876 * once ops_state is cleared, waiters in ops_dequeue() can proceed 1877 * and dequeue_task_scx() will RMW p->scx.flags. If we clear 1878 * ops_state first, both sides would modify p->scx.flags 1879 * concurrently in a non-atomic way. 1880 */ 1881 if (is_rq_owned) { 1882 rq_owned_post_enq(sch, rq, dsq, p, enq_flags); 1883 } else { 1884 bool call_dequeue = false; 1885 1886 /* 1887 * Global and bypass DSQs are terminal - the task leaves the 1888 * scheduler's custody, so ops.dequeue() fires. It can run 1889 * without @p's rq lock (finish_dispatch() passes the dispatch 1890 * rq); that's safe because dequeue_task_scx() waits on 1891 * SCX_OPSS_DISPATCHING (see the ops_state note above) and so 1892 * can't race it. A non-terminal DSQ keeps the task in custody. 1893 * The custody transfer happens under @dsq->lock so that later 1894 * consumers see the flag clear; the callback runs after 1895 * @dsq->lock is dropped because it may lock a DSQ itself. 1896 */ 1897 if (dsq->id == SCX_DSQ_GLOBAL || dsq->id == SCX_DSQ_BYPASS) 1898 call_dequeue = task_leave_custody(p); 1899 else 1900 p->scx.flags |= SCX_TASK_IN_CUSTODY; 1901 1902 raw_spin_unlock(&dsq->lock); 1903 1904 if (call_dequeue && SCX_HAS_OP(sch, dequeue)) 1905 SCX_CALL_OP_TASK(sch, dequeue, rq, p, 0); 1906 } 1907 1908 /* 1909 * We're transitioning out of QUEUEING or DISPATCHING. store_release to 1910 * match waiters' load_acquire. 1911 */ 1912 if (enq_flags & SCX_ENQ_CLEAR_OPSS) 1913 atomic_long_set_release(&p->scx.ops_state, SCX_OPSS_NONE); 1914 } 1915 1916 void scx_task_unlink_from_dsq(struct task_struct *p, struct scx_dispatch_q *dsq) 1917 { 1918 WARN_ON_ONCE(list_empty(&p->scx.dsq_list.node)); 1919 1920 if (p->scx.dsq_flags & SCX_TASK_DSQ_ON_PRIQ) { 1921 rb_erase(&p->scx.dsq_priq, &dsq->priq); 1922 RB_CLEAR_NODE(&p->scx.dsq_priq); 1923 p->scx.dsq_flags &= ~SCX_TASK_DSQ_ON_PRIQ; 1924 } 1925 p->scx.dsq_flags &= ~SCX_TASK_DSQ_REENQ; 1926 1927 list_del_init(&p->scx.dsq_list.node); 1928 dsq_dec_nr(dsq, p); 1929 1930 if (!(dsq->id & SCX_DSQ_FLAG_BUILTIN) && rcu_access_pointer(dsq->first_task) == p) { 1931 struct task_struct *first_task; 1932 1933 first_task = nldsq_next_task(dsq, NULL, false); 1934 rcu_assign_pointer(dsq->first_task, first_task); 1935 } 1936 } 1937 1938 void scx_dispatch_dequeue(struct rq *rq, struct task_struct *p) 1939 { 1940 struct scx_dispatch_q *dsq = p->scx.dsq; 1941 bool is_rq_owned = dsq && dsq_is_rq_owned(dsq); 1942 1943 lockdep_assert_rq_held(rq); 1944 1945 if (!dsq) { 1946 /* 1947 * If !dsq && on-list, @p is on @rq's ddsp_deferred_locals. 1948 * Unlinking is all that's needed to cancel. 1949 */ 1950 if (unlikely(!list_empty(&p->scx.dsq_list.node))) 1951 list_del_init(&p->scx.dsq_list.node); 1952 1953 /* 1954 * When dispatch_to_local_dsq() or remote consumption moves a 1955 * task to a local DSQ, the task isn't associated with any DSQ 1956 * but @p->scx.holding_cpu may be set. Clearing holding_cpu 1957 * tells dispatch_to_local_dsq() that it lost to a dequeue. 1958 */ 1959 if (p->scx.holding_cpu >= 0) 1960 p->scx.holding_cpu = -1; 1961 1962 return; 1963 } 1964 1965 if (!is_rq_owned) 1966 raw_spin_lock(&dsq->lock); 1967 1968 /* 1969 * Now that we hold @dsq->lock, @p->holding_cpu and @p->scx.dsq_* can't 1970 * change underneath us. 1971 */ 1972 if (p->scx.holding_cpu < 0) { 1973 /* @p must still be on @dsq, dequeue */ 1974 scx_task_unlink_from_dsq(p, dsq); 1975 } else { 1976 /* 1977 * We're racing against unlink_dsq_and_switch_rq_lock(), 1978 * which already removed @p from @dsq and set 1979 * @p->scx.holding_cpu. Clear holding_cpu to tell 1980 * unlink_dsq_and_switch_rq_lock() that it lost the race. 1981 */ 1982 WARN_ON_ONCE(!list_empty(&p->scx.dsq_list.node)); 1983 p->scx.holding_cpu = -1; 1984 } 1985 p->scx.dsq = NULL; 1986 1987 if (!is_rq_owned) 1988 raw_spin_unlock(&dsq->lock); 1989 } 1990 1991 /* 1992 * Abbreviated version of scx_dispatch_dequeue() that can be used when both 1993 * @p's rq and dsq are locked. 1994 */ 1995 static void dispatch_dequeue_locked(struct task_struct *p, 1996 struct scx_dispatch_q *dsq) 1997 { 1998 lockdep_assert_rq_held(task_rq(p)); 1999 lockdep_assert_held(&dsq->lock); 2000 2001 scx_task_unlink_from_dsq(p, dsq); 2002 p->scx.dsq = NULL; 2003 } 2004 2005 static struct scx_dispatch_q *find_dsq_for_dispatch(struct scx_sched *sch, 2006 struct rq *rq, u64 dsq_id, 2007 s32 tcpu) 2008 { 2009 struct scx_dispatch_q *dsq; 2010 2011 if (dsq_id == SCX_DSQ_LOCAL) 2012 return &rq->scx.local_dsq; 2013 2014 if ((dsq_id & SCX_DSQ_LOCAL_ON) == SCX_DSQ_LOCAL_ON) { 2015 s32 cpu = scx_cpu_ret(sch, dsq_id & SCX_DSQ_LOCAL_CPU_MASK); 2016 2017 if (!scx_cpu_valid(sch, cpu, "in SCX_DSQ_LOCAL_ON dispatch verdict")) 2018 return find_global_dsq(sch, tcpu); 2019 2020 return &cpu_rq(cpu)->scx.local_dsq; 2021 } 2022 2023 if (dsq_id == SCX_DSQ_GLOBAL) 2024 dsq = find_global_dsq(sch, tcpu); 2025 else 2026 dsq = find_user_dsq(sch, dsq_id); 2027 2028 /* 2029 * Built-in DSQs are never inserted into dsq_hash, so REJECT and RESCUE 2030 * hit the error below. They cannot be reached with an ID. 2031 */ 2032 if (unlikely(!dsq)) { 2033 scx_error(sch, "non-existent DSQ 0x%llx", dsq_id); 2034 return find_global_dsq(sch, tcpu); 2035 } 2036 2037 return dsq; 2038 } 2039 2040 static void mark_direct_dispatch(struct scx_sched *sch, 2041 struct task_struct *ddsp_task, 2042 struct task_struct *p, u64 dsq_id, 2043 u64 slice, u64 vtime, u64 enq_flags) 2044 { 2045 /* 2046 * Mark that dispatch already happened from ops.select_cpu() or 2047 * ops.enqueue() by spoiling direct_dispatch_task with a non-NULL value 2048 * which can never match a valid task pointer. 2049 */ 2050 __this_cpu_write(direct_dispatch_task, ERR_PTR(-ESRCH)); 2051 2052 /* @p must match the task on the enqueue path */ 2053 if (unlikely(p != ddsp_task)) { 2054 if (IS_ERR(ddsp_task)) 2055 scx_error(sch, "%s[%d] already direct-dispatched", 2056 p->comm, p->pid); 2057 else 2058 scx_error(sch, "scheduling for %s[%d] but trying to direct-dispatch %s[%d]", 2059 ddsp_task->comm, ddsp_task->pid, 2060 p->comm, p->pid); 2061 return; 2062 } 2063 2064 WARN_ON_ONCE(p->scx.ddsp_dsq_id != SCX_DSQ_INVALID); 2065 WARN_ON_ONCE(p->scx.ddsp_enq_flags); 2066 2067 p->scx.ddsp_slice = slice; 2068 p->scx.ddsp_vtime = vtime; 2069 p->scx.ddsp_dsq_id = dsq_id; 2070 p->scx.ddsp_enq_flags = enq_flags; 2071 } 2072 2073 /* 2074 * Clear @p direct dispatch state when leaving the scheduler. 2075 * 2076 * Direct dispatch state must be cleared in the following cases: 2077 * - direct_dispatch(): cleared on the synchronous enqueue path, deferred 2078 * dispatch keeps the state until consumed 2079 * - process_ddsp_deferred_locals(): cleared after consuming deferred state, 2080 * - scx_do_enqueue_task(): cleared on enqueue fallbacks where the dispatch 2081 * verdict is ignored (local/global/bypass) 2082 * - dequeue_task_scx(): cleared after scx_dispatch_dequeue(), covering 2083 * deferred cancellation and holding_cpu races 2084 * - scx_disable_task(): cleared for queued wakeup tasks, which are excluded by 2085 * the scx_bypass() loop, so that stale state is not reused by a subsequent 2086 * scheduler instance 2087 */ 2088 static inline void clear_direct_dispatch(struct task_struct *p) 2089 { 2090 p->scx.ddsp_dsq_id = SCX_DSQ_INVALID; 2091 p->scx.ddsp_enq_flags = 0; 2092 } 2093 2094 static void direct_dispatch(struct scx_sched *sch, struct task_struct *p, 2095 u64 enq_flags) 2096 { 2097 struct rq *rq = task_rq(p); 2098 struct scx_dispatch_q *dsq = 2099 find_dsq_for_dispatch(sch, rq, p->scx.ddsp_dsq_id, task_cpu(p)); 2100 u64 ddsp_enq_flags, slice, vtime; 2101 2102 p->scx.ddsp_enq_flags |= enq_flags; 2103 2104 /* 2105 * We are in the enqueue path with @rq locked and pinned, and thus can't 2106 * double lock a remote rq and enqueue to its local DSQ. For 2107 * DSQ_LOCAL_ON verdicts targeting the local DSQ of a remote CPU, defer 2108 * the enqueue so that it's executed when @rq can be unlocked. 2109 */ 2110 if (dsq->id == SCX_DSQ_LOCAL && dsq != &rq->scx.local_dsq) { 2111 unsigned long opss; 2112 2113 opss = atomic_long_read(&p->scx.ops_state) & SCX_OPSS_STATE_MASK; 2114 2115 switch (opss & SCX_OPSS_STATE_MASK) { 2116 case SCX_OPSS_NONE: 2117 break; 2118 case SCX_OPSS_QUEUEING: 2119 /* 2120 * As @p was never passed to the BPF side, _release is 2121 * not strictly necessary. Still do it for consistency. 2122 */ 2123 atomic_long_set_release(&p->scx.ops_state, SCX_OPSS_NONE); 2124 break; 2125 default: 2126 WARN_ONCE(true, "sched_ext: %s[%d] has invalid ops state 0x%lx in direct_dispatch()", 2127 p->comm, p->pid, opss); 2128 atomic_long_set_release(&p->scx.ops_state, SCX_OPSS_NONE); 2129 break; 2130 } 2131 2132 WARN_ON_ONCE(p->scx.dsq || !list_empty(&p->scx.dsq_list.node)); 2133 list_add_tail(&p->scx.dsq_list.node, 2134 &rq->scx.ddsp_deferred_locals); 2135 schedule_deferred_locked(rq); 2136 return; 2137 } 2138 2139 ddsp_enq_flags = p->scx.ddsp_enq_flags; 2140 slice = p->scx.ddsp_slice; 2141 vtime = p->scx.ddsp_vtime; 2142 clear_direct_dispatch(p); 2143 2144 scx_dispatch_enqueue(sch, rq, dsq, p, slice, vtime, 2145 ddsp_enq_flags | SCX_ENQ_APPLY_SLICE | SCX_ENQ_CLEAR_OPSS); 2146 } 2147 2148 bool scx_rq_online(struct rq *rq) 2149 { 2150 /* 2151 * Test both cpu_active() and %SCX_RQ_ONLINE. %SCX_RQ_ONLINE indicates 2152 * the online state as seen from the BPF scheduler. cpu_active() test 2153 * guarantees that, if this function returns %true, %SCX_RQ_ONLINE will 2154 * stay set until the current scheduling operation is complete even if 2155 * we aren't locking @rq. 2156 */ 2157 return likely((rq->scx.flags & SCX_RQ_ONLINE) && cpu_active(cpu_of(rq))); 2158 } 2159 2160 void scx_do_enqueue_task(struct rq *rq, struct task_struct *p, u64 enq_flags, 2161 int sticky_cpu) 2162 { 2163 enum { 2164 ENQ_ACTION_NONE, 2165 ENQ_ACTION_DIRECT, 2166 ENQ_ACTION_LOCAL_NOREFILL, 2167 ENQ_ACTION_ENQUEUE, 2168 } action = ENQ_ACTION_NONE; 2169 struct scx_sched *sch = scx_task_sched(p); 2170 struct task_struct **ddsp_taskp; 2171 struct scx_dispatch_q *dsq; 2172 unsigned long qseq; 2173 2174 WARN_ON_ONCE(!(p->scx.flags & SCX_TASK_QUEUED)); 2175 2176 /* internal movements - rq migration / RESTORE */ 2177 if (sticky_cpu == cpu_of(rq)) 2178 goto local_norefill; 2179 2180 /* 2181 * Clear persistent TASK_IMMED for fresh enqueues, see dsq_inc_nr(). 2182 * Note that exiting and migration-disabled tasks that skip 2183 * ops.enqueue() below will lose IMMED protection unless 2184 * %SCX_OPS_ENQ_EXITING / %SCX_OPS_ENQ_MIGRATION_DISABLED are set. 2185 */ 2186 p->scx.flags &= ~SCX_TASK_IMMED; 2187 2188 /* 2189 * A task reenqueued too many times without running means the scheduler 2190 * keeps re-deciding a placement it can't honor, e.g. re-inserting to a 2191 * cid it lacks caps on. Eject the owning scheduler and strand the task 2192 * to be picked up during sched exit. 2193 */ 2194 if (enq_flags & SCX_ENQ_REENQ) { 2195 if (++p->scx.reenq_cnt > 1) 2196 __scx_add_event(sch, SCX_EV_REENQ_REPEAT, 1); 2197 2198 if (unlikely(p->scx.reenq_cnt > SCX_REENQ_MAX_REPEAT)) { 2199 __scx_exit(sch, SCX_EXIT_ERROR_REENQ, 0, cpu_of(rq), 2200 "%s[%d] reenqueued %u times without running", 2201 p->comm, p->pid, p->scx.reenq_cnt); 2202 goto out; 2203 } 2204 } 2205 2206 /* 2207 * If !scx_rq_online(), we already told the BPF scheduler that the CPU 2208 * is offline and are just running the hotplug path. Don't bother the 2209 * BPF scheduler. 2210 */ 2211 if (!scx_rq_online(rq)) 2212 goto local; 2213 2214 if (scx_bypassing(sch, cpu_of(rq))) { 2215 __scx_add_event(sch, SCX_EV_BYPASS_DISPATCH, 1); 2216 goto bypass; 2217 } 2218 2219 if (p->scx.ddsp_dsq_id != SCX_DSQ_INVALID) 2220 goto direct; 2221 2222 /* 2223 * A full wakeup enqueue happens before is_blocked is cleared. Don't 2224 * report it as another blocked-donor admission. 2225 */ 2226 if ((sch->ops.flags & SCX_OPS_ENQ_BLOCKED) && p->is_blocked && 2227 !(enq_flags & SCX_ENQ_WAKEUP)) { 2228 enq_flags |= SCX_ENQ_BLOCKED; 2229 } else { 2230 /* see %SCX_OPS_ENQ_EXITING */ 2231 if (unlikely(p->flags & PF_EXITING) && 2232 !(sch->ops.flags & SCX_OPS_ENQ_EXITING)) { 2233 __scx_add_event(sch, SCX_EV_ENQ_SKIP_EXITING, 1); 2234 enq_flags |= SCX_ENQ_RESCUE; /* avoid looping on cap rejection */ 2235 goto local; 2236 } 2237 2238 /* see %SCX_OPS_ENQ_MIGRATION_DISABLED */ 2239 if (!(sch->ops.flags & SCX_OPS_ENQ_MIGRATION_DISABLED) && 2240 is_migration_disabled(p)) { 2241 __scx_add_event(sch, SCX_EV_ENQ_SKIP_MIGRATION_DISABLED, 1); 2242 goto local; 2243 } 2244 } 2245 2246 if (unlikely(!SCX_HAS_OP(sch, enqueue))) 2247 goto global; 2248 2249 /* 2250 * DSQ bypass didn't trigger, enqueue on the BPF scheduler. Wrap the 2251 * per-task qseq counter where the QSEQ field wraps and skip 0, which is 2252 * what scx_bpf_dsq_insert() records for a task in NONE or DISPATCHING. 2253 */ 2254 p->scx.ops_qseq = ((p->scx.ops_qseq + 1) & 2255 (SCX_OPSS_QSEQ_MASK >> SCX_OPSS_QSEQ_SHIFT)) ?: 1; 2256 qseq = (unsigned long)p->scx.ops_qseq << SCX_OPSS_QSEQ_SHIFT; 2257 2258 WARN_ON_ONCE(atomic_long_read(&p->scx.ops_state) != SCX_OPSS_NONE); 2259 atomic_long_set(&p->scx.ops_state, SCX_OPSS_QUEUEING | qseq); 2260 2261 ddsp_taskp = this_cpu_ptr(&direct_dispatch_task); 2262 WARN_ON_ONCE(*ddsp_taskp); 2263 *ddsp_taskp = p; 2264 2265 SCX_CALL_OP_TASK(sch, enqueue, rq, p, enq_flags); 2266 2267 *ddsp_taskp = NULL; 2268 if (p->scx.ddsp_dsq_id != SCX_DSQ_INVALID) 2269 goto direct; 2270 2271 /* 2272 * Task is now in BPF scheduler's custody. Set %SCX_TASK_IN_CUSTODY 2273 * so ops.dequeue() is called when it leaves custody. 2274 */ 2275 p->scx.flags |= SCX_TASK_IN_CUSTODY; 2276 2277 /* 2278 * If not directly dispatched, QUEUEING isn't clear yet and dispatch or 2279 * dequeue may be waiting. The store_release matches their load_acquire. 2280 */ 2281 atomic_long_set_release(&p->scx.ops_state, SCX_OPSS_QUEUED | qseq); 2282 goto out; 2283 2284 direct: 2285 action = ENQ_ACTION_DIRECT; 2286 goto out; 2287 local_norefill: 2288 action = ENQ_ACTION_LOCAL_NOREFILL; 2289 goto out; 2290 local: 2291 dsq = &rq->scx.local_dsq; 2292 goto enqueue; 2293 global: 2294 dsq = find_global_dsq(sch, task_cpu(p)); 2295 goto enqueue; 2296 bypass: 2297 dsq = bypass_enq_target_dsq(sch, task_cpu(p)); 2298 goto enqueue; 2299 2300 enqueue: 2301 action = ENQ_ACTION_ENQUEUE; 2302 out: 2303 /* The reason is input to ops.enqueue(), not to the resulting placement. */ 2304 p->scx.flags &= ~SCX_TASK_REENQ_REASON_MASK; 2305 2306 switch (action) { 2307 case ENQ_ACTION_DIRECT: 2308 direct_dispatch(sch, p, enq_flags); 2309 break; 2310 case ENQ_ACTION_LOCAL_NOREFILL: 2311 scx_dispatch_enqueue(sch, rq, &rq->scx.local_dsq, p, 0, 0, 2312 enq_flags); 2313 break; 2314 case ENQ_ACTION_ENQUEUE: 2315 refill_task_slice_dfl(sch, p); 2316 clear_direct_dispatch(p); 2317 scx_dispatch_enqueue(sch, rq, dsq, p, 0, 0, enq_flags); 2318 break; 2319 case ENQ_ACTION_NONE: 2320 break; 2321 } 2322 } 2323 2324 static bool task_runnable(const struct task_struct *p) 2325 { 2326 return !list_empty(&p->scx.runnable_node); 2327 } 2328 2329 static void set_task_runnable(struct rq *rq, struct task_struct *p) 2330 { 2331 lockdep_assert_rq_held(rq); 2332 2333 if (p->scx.flags & SCX_TASK_RESET_RUNNABLE_AT) { 2334 p->scx.runnable_at = jiffies; 2335 p->scx.flags &= ~SCX_TASK_RESET_RUNNABLE_AT; 2336 } 2337 2338 /* 2339 * list_add_tail() must be used. scx_bypass() and rq_offline_scx() 2340 * depend on tasks being appended to the runnable_list. 2341 */ 2342 list_add_tail(&p->scx.runnable_node, &rq->scx.runnable_list); 2343 2344 /* 2345 * Record the rq @p is runnable on, maintained under the rq lock so it 2346 * stays valid unlike task_cpu(), which a remote wakeup can move under 2347 * pi_lock alone. 2348 */ 2349 WRITE_ONCE(p->scx.runnable_cpu, cpu_of(rq)); 2350 } 2351 2352 static void clr_task_runnable(struct task_struct *p, bool reset_runnable_at) 2353 { 2354 list_del_init(&p->scx.runnable_node); 2355 WRITE_ONCE(p->scx.runnable_cpu, -1); 2356 if (reset_runnable_at) { 2357 p->scx.flags |= SCX_TASK_RESET_RUNNABLE_AT; 2358 p->scx.reenq_cnt = 0; 2359 } 2360 } 2361 2362 static void enqueue_task_scx(struct rq *rq, struct task_struct *p, int core_enq_flags) 2363 { 2364 struct scx_sched *sch = scx_task_sched(p); 2365 int sticky_cpu = p->scx.sticky_cpu; 2366 u64 enq_flags = core_enq_flags | rq->scx.remote_activate_enq_flags; 2367 2368 /* 2369 * An SCX-internal migration ends on arrival. Clear sticky_cpu so @p can 2370 * leave custody when inserted into the destination DSQ. 2371 */ 2372 if (sticky_cpu >= 0) 2373 p->scx.sticky_cpu = -1; 2374 2375 /* 2376 * SCX_RQ_IN_WAKEUP promises a task_woken_scx() call once this enqueue 2377 * returns. Only the core's wakeup path delivers one. The flags stashed 2378 * for a remote activation may carry the wakeup bit without it. 2379 */ 2380 if (core_enq_flags & ENQUEUE_WAKEUP) 2381 rq->scx.flags |= SCX_RQ_IN_WAKEUP; 2382 2383 /* 2384 * Restoring the current scheduling context will be immediately followed 2385 * by set_next_task_scx() which expects the task to not be on the BPF 2386 * scheduler as tasks can only start running through local DSQs. Force 2387 * direct-dispatch into the local DSQ by setting the sticky_cpu. Mark 2388 * IGNORE_CAPS to force entry into the local DSQ. 2389 */ 2390 if (unlikely(enq_flags & ENQUEUE_RESTORE) && 2391 task_current_donor(rq, p)) { 2392 sticky_cpu = cpu_of(rq); 2393 enq_flags |= SCX_ENQ_IGNORE_CAPS; 2394 } 2395 2396 if (p->scx.flags & SCX_TASK_QUEUED) { 2397 WARN_ON_ONCE(!task_runnable(p)); 2398 goto out; 2399 } 2400 2401 set_task_runnable(rq, p); 2402 p->scx.flags |= SCX_TASK_QUEUED; 2403 rq->scx.nr_running++; 2404 add_nr_running(rq, 1); 2405 2406 if (SCX_HAS_OP(sch, runnable) && !task_on_rq_migrating(p)) 2407 SCX_CALL_OP_TASK(sch, runnable, rq, p, enq_flags); 2408 2409 /* Start dl_server if this is the first task being enqueued */ 2410 if (rq->scx.nr_running == 1) 2411 dl_server_start(&rq->ext_server); 2412 2413 scx_do_enqueue_task(rq, p, enq_flags, sticky_cpu); 2414 out: 2415 rq->scx.flags &= ~SCX_RQ_IN_WAKEUP; 2416 2417 if ((enq_flags & SCX_ENQ_CPU_SELECTED) && 2418 unlikely(cpu_of(rq) != p->scx.selected_cpu)) 2419 __scx_add_event(sch, SCX_EV_SELECT_CPU_FALLBACK, 1); 2420 } 2421 2422 static void ops_dequeue(struct rq *rq, struct task_struct *p, u64 deq_flags) 2423 { 2424 struct scx_sched *sch = scx_task_sched(p); 2425 unsigned long opss; 2426 2427 /* dequeue is always temporary, don't reset runnable_at */ 2428 clr_task_runnable(p, false); 2429 2430 retry: 2431 /* acquire ensures that we see the preceding updates on QUEUED */ 2432 opss = atomic_long_read_acquire(&p->scx.ops_state); 2433 2434 switch (opss & SCX_OPSS_STATE_MASK) { 2435 case SCX_OPSS_NONE: 2436 break; 2437 case SCX_OPSS_QUEUEING: 2438 /* 2439 * QUEUEING is started and finished while holding @p's rq lock. 2440 * As we're holding the rq lock now, we shouldn't see QUEUEING. 2441 */ 2442 BUG(); 2443 case SCX_OPSS_QUEUED: 2444 /* 2445 * A queued task must always be in BPF scheduler's custody. If 2446 * SCX_TASK_IN_CUSTODY is clear, finish_dispatch() on another 2447 * CPU has already passed task_leave_custody() (which clears the 2448 * flag), but has not yet written SCX_OPSS_NONE. That final 2449 * store does not require this rq's lock, so retrying with 2450 * cpu_relax() is bounded: we will observe NONE (or DISPATCHING, 2451 * handled by the fallthrough) on a subsequent iteration. 2452 */ 2453 if (unlikely(!(READ_ONCE(p->scx.flags) & SCX_TASK_IN_CUSTODY))) { 2454 cpu_relax(); 2455 goto retry; 2456 } 2457 2458 if (atomic_long_try_cmpxchg(&p->scx.ops_state, &opss, 2459 SCX_OPSS_NONE)) 2460 break; 2461 fallthrough; 2462 case SCX_OPSS_DISPATCHING: 2463 /* 2464 * If @p is being dispatched from the BPF scheduler to a DSQ, 2465 * wait for the transfer to complete so that @p doesn't get 2466 * added to its DSQ after dequeueing is complete. 2467 * 2468 * As we're waiting on DISPATCHING with the rq locked, the 2469 * dispatching side shouldn't try to lock the rq while 2470 * DISPATCHING is set. See dispatch_to_local_dsq(). 2471 * 2472 * DISPATCHING shouldn't have qseq set and control can reach 2473 * here with NONE @opss from the above QUEUED case block. 2474 * Explicitly wait on %SCX_OPSS_DISPATCHING instead of @opss. 2475 */ 2476 wait_ops_state(p, SCX_OPSS_DISPATCHING); 2477 BUG_ON(atomic_long_read(&p->scx.ops_state) != SCX_OPSS_NONE); 2478 break; 2479 } 2480 2481 /* 2482 * Call ops.dequeue() if the task is still in BPF custody. 2483 * 2484 * The code that clears ops_state to %SCX_OPSS_NONE does not always 2485 * clear %SCX_TASK_IN_CUSTODY: in dispatch_to_local_dsq(), when 2486 * we're moving a task that was in %SCX_OPSS_DISPATCHING to a 2487 * remote CPU's local DSQ, we only set ops_state to %SCX_OPSS_NONE 2488 * so that a concurrent dequeue can proceed, but we clear 2489 * %SCX_TASK_IN_CUSTODY only when we later enqueue or move the 2490 * task. So we can see NONE + IN_CUSTODY here and we must handle 2491 * it. Similarly, after waiting on %SCX_OPSS_DISPATCHING we see 2492 * NONE but the task may still have %SCX_TASK_IN_CUSTODY set until 2493 * it is enqueued on the destination. 2494 */ 2495 if (task_leave_custody(p) && SCX_HAS_OP(sch, dequeue)) 2496 SCX_CALL_OP_TASK(sch, dequeue, rq, p, deq_flags); 2497 } 2498 2499 static bool dequeue_task_scx(struct rq *rq, struct task_struct *p, int core_deq_flags) 2500 { 2501 struct scx_sched *sch = scx_task_sched(p); 2502 u64 deq_flags = core_deq_flags; 2503 2504 /* 2505 * Set %SCX_DEQ_SCHED_CHANGE when the dequeue is due to a property 2506 * change (not sleep). 2507 */ 2508 if (!(deq_flags & DEQUEUE_SLEEP)) 2509 deq_flags |= SCX_DEQ_SCHED_CHANGE; 2510 2511 if (!(p->scx.flags & SCX_TASK_QUEUED)) { 2512 WARN_ON_ONCE(task_runnable(p)); 2513 return true; 2514 } 2515 2516 ops_dequeue(rq, p, deq_flags); 2517 2518 /* 2519 * A current scheduling context which is going off @rq first gets 2520 * dequeued and then stops running. As we want running <-> stopping 2521 * transitions to be contained within runnable <-> quiescent transitions, 2522 * trigger ->stopping() early here instead of in put_prev_task_scx(). 2523 * 2524 * @p may go through multiple stopping <-> running transitions between 2525 * here and put_prev_task_scx() if task attribute changes occur while 2526 * dispatch_one() leaves @rq unlocked. However, they don't contain any 2527 * information meaningful to the BPF scheduler and can be suppressed by 2528 * skipping the callbacks if the task is !QUEUED. 2529 */ 2530 if (task_current_donor(rq, p) && (p->scx.flags & SCX_TASK_RUN_TRACKED)) { 2531 if (SCX_HAS_OP(sch, stopping) || unlikely(p == scx_rescuee(rq))) { 2532 update_curr_scx(rq); 2533 if (SCX_HAS_OP(sch, stopping)) 2534 SCX_CALL_OP_TASK(sch, stopping, rq, p, false); 2535 } 2536 p->scx.flags &= ~SCX_TASK_RUN_TRACKED; 2537 } 2538 2539 if (SCX_HAS_OP(sch, quiescent) && !task_on_rq_migrating(p)) 2540 SCX_CALL_OP_TASK(sch, quiescent, rq, p, deq_flags); 2541 2542 if (deq_flags & SCX_DEQ_SLEEP) 2543 p->scx.flags |= SCX_TASK_DEQD_FOR_SLEEP; 2544 else 2545 p->scx.flags &= ~SCX_TASK_DEQD_FOR_SLEEP; 2546 2547 p->scx.flags &= ~SCX_TASK_QUEUED; 2548 rq->scx.nr_running--; 2549 sub_nr_running(rq, 1); 2550 2551 scx_dispatch_dequeue(rq, p); 2552 p->scx.flags &= ~SCX_TASK_REENQ_REASON_MASK; 2553 2554 /* see scx_task_slice_ended() for the save/restore exception */ 2555 if (!((deq_flags & DEQUEUE_SAVE) && task_current_donor(rq, p))) 2556 scx_task_slice_ended(rq, p); 2557 2558 clear_direct_dispatch(p); 2559 return true; 2560 } 2561 2562 static void yield_task_scx(struct rq *rq) 2563 { 2564 struct task_struct *p = rq->donor; 2565 struct scx_sched *sch = scx_task_sched(p); 2566 2567 /* a yield gives the slice up */ 2568 scx_task_slice_ended(rq, p); 2569 2570 if (SCX_HAS_OP(sch, yield)) 2571 SCX_CALL_OP_2TASKS_RET(sch, yield, rq, p, NULL); 2572 else 2573 scx_set_task_slice(p, 0); 2574 } 2575 2576 static bool yield_to_task_scx(struct rq *rq, struct task_struct *to) 2577 { 2578 struct task_struct *from = rq->donor; 2579 struct scx_sched *sch = scx_task_sched(from); 2580 2581 /* like a plain yield, giving the slice up ends the protection */ 2582 scx_task_slice_ended(rq, from); 2583 2584 if (SCX_HAS_OP(sch, yield) && sch == scx_task_sched(to)) 2585 return SCX_CALL_OP_2TASKS_RET(sch, yield, rq, from, to); 2586 else 2587 return false; 2588 } 2589 2590 static void wakeup_preempt_scx(struct rq *rq, struct task_struct *p, int wake_flags) 2591 { 2592 /* 2593 * Preemption between SCX tasks is implemented by resetting the victim 2594 * task's slice to 0 and triggering reschedule on the target CPU. 2595 * 2596 * A retained proxy donor can wake through ttwu_runnable() without another 2597 * ops.enqueue(). WF_TTWU_RQ identifies this path. Request rescheduling so 2598 * that ops.dispatch() can reconsider the task after ttwu_runnable() clears 2599 * is_blocked. A full wakeup activation has already enqueued the task and 2600 * doesn't need the additional reschedule. 2601 */ 2602 if (p->sched_class == &ext_sched_class) { 2603 if (sched_proxy_exec() && (wake_flags & WF_TTWU_RQ) && 2604 p->is_blocked) { 2605 struct scx_sched *sch = scx_task_sched(p); 2606 2607 if (sch && (sch->ops.flags & SCX_OPS_ENQ_BLOCKED)) 2608 resched_curr(rq); 2609 } 2610 return; 2611 } 2612 2613 /* 2614 * Getting preempted by a higher-priority class. Reenqueue IMMED tasks. 2615 * This captures all preemption cases including: 2616 * 2617 * - A SCX task is currently running. 2618 * 2619 * - @rq is waking from idle due to a SCX task waking to it. 2620 * 2621 * - A higher-priority wakes up while SCX dispatch is in progress. 2622 */ 2623 if (rq->scx.nr_immed) 2624 scx_schedule_reenq_local(rq, 0); 2625 } 2626 2627 void scx_move_local_task_to_local_dsq(struct scx_sched *sch, struct task_struct *p, 2628 u64 enq_flags, struct rq *dst_rq) 2629 { 2630 struct scx_dispatch_q *dst_dsq; 2631 2632 lockdep_assert_rq_held(dst_rq); 2633 2634 WARN_ON_ONCE(p->scx.holding_cpu >= 0); 2635 scx_wait_dispatching(p); 2636 2637 dst_dsq = scx_resolve_local_dsq(sch, dst_rq, p, &enq_flags); 2638 2639 if (enq_flags & (SCX_ENQ_HEAD | SCX_ENQ_PREEMPT | SCX_ENQ_PREEMPT_LAZY)) 2640 dsq_insert_head(dst_dsq, p); 2641 else 2642 list_add_tail(&p->scx.dsq_list.node, &dst_dsq->list); 2643 2644 dsq_inc_nr(dst_dsq, p, enq_flags); 2645 p->scx.dsq = dst_dsq; 2646 2647 rq_owned_post_enq(sch, dst_rq, dst_dsq, p, enq_flags); 2648 } 2649 2650 /** 2651 * move_remote_task_to_local_dsq - Move a task from a foreign rq to a local DSQ 2652 * @sch: scheduler placing @p 2653 * @p: task to move 2654 * @enq_flags: %SCX_ENQ_* 2655 * @src_rq: rq to move the task from, locked on entry, released on return 2656 * @dst_rq: rq to move the task into, locked on return 2657 * 2658 * Move @p which is currently on @src_rq to @dst_rq's local DSQ. 2659 */ 2660 static void move_remote_task_to_local_dsq(struct scx_sched *sch, 2661 struct task_struct *p, u64 enq_flags, 2662 struct rq *src_rq, struct rq *dst_rq) 2663 { 2664 lockdep_assert_rq_held(src_rq); 2665 2666 /* 2667 * Set sticky_cpu before deactivate_task() to properly mark the 2668 * beginning of an SCX-internal migration. 2669 */ 2670 p->scx.sticky_cpu = cpu_of(dst_rq); 2671 deactivate_task(src_rq, p, 0); 2672 set_task_cpu(p, cpu_of(dst_rq)); 2673 2674 switch_rq_lock(src_rq, dst_rq); 2675 2676 /* 2677 * activate_task() below truncates enq_flags to 32 bits and re-derives 2678 * @p's owner, dropping our scx flags and the placing @sch. We own @rq, 2679 * so stash both across the call. The enqueue reads them back, keeping 2680 * the scx flags and checking caps against the placer, not the owner. 2681 */ 2682 WARN_ON_ONCE(!cpumask_test_cpu(cpu_of(dst_rq), p->cpus_ptr)); 2683 WARN_ON_ONCE(dst_rq->scx.remote_activate_enq_flags || 2684 dst_rq->scx.remote_activate_sch); 2685 dst_rq->scx.remote_activate_enq_flags = enq_flags; 2686 dst_rq->scx.remote_activate_sch = sch; 2687 activate_task(dst_rq, p, 0); 2688 dst_rq->scx.remote_activate_enq_flags = 0; 2689 dst_rq->scx.remote_activate_sch = NULL; 2690 } 2691 2692 /* 2693 * Similar to kernel/sched/core.c::is_cpu_allowed(). However, there are two 2694 * differences: 2695 * 2696 * - is_cpu_allowed() asks "Can this task run on this CPU?" while 2697 * task_can_run_on_remote_rq() asks "Can the BPF scheduler migrate the task to 2698 * this CPU?". 2699 * 2700 * While migration is disabled, is_cpu_allowed() has to say "yes" as the task 2701 * must be allowed to finish on the CPU that it's currently on regardless of 2702 * the CPU state. However, task_can_run_on_remote_rq() must say "no" as the 2703 * BPF scheduler shouldn't attempt to migrate a task which has migration 2704 * disabled. 2705 * 2706 * - The BPF scheduler is bypassed while the rq is offline and we can always say 2707 * no to the BPF scheduler initiated migrations while offline. 2708 * 2709 * The caller must ensure that @p and @rq are on different CPUs. If @enforce is 2710 * true, report violations attributable to BPF-directed migrations. The caller 2711 * must hold @p's rq lock to avoid reporting a transient race as a scheduler 2712 * error. 2713 */ 2714 static bool task_can_run_on_remote_rq(struct scx_sched *sch, 2715 struct task_struct *p, struct rq *rq, 2716 bool enforce) 2717 { 2718 s32 cpu = cpu_of(rq); 2719 2720 if (enforce) 2721 lockdep_assert_rq_held(task_rq(p)); 2722 2723 WARN_ON_ONCE(task_cpu(p) == cpu); 2724 2725 /* 2726 * proxy_set_task_cpu() preserves wake_cpu when moving a donor's scheduling 2727 * context to its lock owner's rq. For example, if BPF places donor D on 2728 * CPU0 while its lock owner runs on CPU1, proxy execution moves D to CPU1 2729 * but leaves D->wake_cpu pointing to CPU0. If D is later put on a shared 2730 * DSQ, CPU0 could otherwise consume it and move it back, only for proxy 2731 * execution to return it to CPU1 again. 2732 * 2733 * When task_cpu() == wake_cpu, the donor has not been proxy-migrated and 2734 * BPF may still choose its placement. An actively donating task is 2735 * rejected separately by task_proxy_running_or_donating(). 2736 */ 2737 if (sched_proxy_exec() && p->is_blocked && task_cpu(p) != p->wake_cpu) 2738 return false; 2739 2740 /* 2741 * If @p has migration disabled, @p->cpus_ptr is updated to contain only 2742 * the pinned CPU in migrate_disable_switch() while @p is being switched 2743 * out. However, put_prev_task_scx() is called before @p->cpus_ptr is 2744 * updated and thus another CPU may see @p on a DSQ inbetween leading to 2745 * @p passing the below task_allowed_on_cpu() check while migration is 2746 * disabled. 2747 * 2748 * Test the migration disabled state first as the race window is narrow 2749 * and the BPF scheduler failing to check migration disabled state can 2750 * easily be masked if task_allowed_on_cpu() is done first. 2751 */ 2752 if (unlikely(is_migration_disabled(p))) { 2753 if (enforce) 2754 scx_error(sch, "SCX_DSQ_LOCAL[_ON] cannot move migration disabled %s[%d] from CPU %d to %d", 2755 p->comm, p->pid, task_cpu(p), cpu); 2756 return false; 2757 } 2758 2759 /* 2760 * We don't require the BPF scheduler to avoid dispatching to offline 2761 * CPUs mostly for convenience but also because CPUs can go offline 2762 * between scx_bpf_dsq_insert() calls and here. Trigger error iff the 2763 * picked CPU is outside the allowed mask. 2764 */ 2765 if (!task_allowed_on_cpu(p, cpu)) { 2766 if (enforce) 2767 scx_error(sch, "SCX_DSQ_LOCAL[_ON] target CPU %d not allowed for %s[%d]", 2768 cpu, p->comm, p->pid); 2769 return false; 2770 } 2771 2772 if (!scx_rq_online(rq)) { 2773 if (enforce) 2774 __scx_add_event(sch, SCX_EV_DISPATCH_LOCAL_DSQ_OFFLINE, 1); 2775 return false; 2776 } 2777 2778 return true; 2779 } 2780 2781 /* 2782 * Proxy execution can change @p's execution and migration-disabled state 2783 * without touching its DSQ entry or clearing holding_cpu. Check those states 2784 * with @p's rq locked. Without proxy execution, the holding_cpu handshake is 2785 * sufficient and this must not affect the existing migration path. 2786 * 2787 * A BPF-directed transfer to a remote local DSQ performs a normal task 2788 * migration and thus cannot move a migration-disabled task. In contrast, 2789 * proxy_migrate_task() moves only a blocked donor's scheduling context towards 2790 * the mutex owner and preserves its execution home in wake_cpu. The latter is 2791 * therefore allowed even when the donor is migration-disabled. 2792 */ 2793 static bool task_proxy_running_or_donating(struct task_struct *p) 2794 { 2795 struct rq *src_rq = task_rq(p); 2796 2797 lockdep_assert_rq_held(src_rq); 2798 2799 if (!sched_proxy_exec()) 2800 return false; 2801 2802 /* @p may be rq->curr under another task's scheduling context. */ 2803 if (task_on_cpu(src_rq, p)) 2804 return true; 2805 2806 /* Don't move an active scheduling context off its source rq. */ 2807 if (task_current_donor(src_rq, p)) 2808 return true; 2809 2810 return false; 2811 } 2812 2813 static bool task_proxy_unsafe_to_move(struct task_struct *p) 2814 { 2815 if (!sched_proxy_exec()) 2816 return false; 2817 2818 return task_proxy_running_or_donating(p) || is_migration_disabled(p); 2819 } 2820 2821 /* 2822 * Park a task whose remote transfer raced with proxy execution. Reenqueueing 2823 * from the source rq makes the task's owning scheduler choose its placement 2824 * again and preserves sub-scheduler containment. 2825 */ 2826 static void scx_proxy_reject_task(struct scx_sched *sch, struct rq *rq, 2827 struct task_struct *p, u64 enq_flags) 2828 { 2829 lockdep_assert_rq_held(rq); 2830 WARN_ON_ONCE(p->scx.flags & SCX_TASK_REENQ_REASON_MASK); 2831 2832 p->scx.holding_cpu = -1; 2833 p->scx.flags |= SCX_TASK_REENQ_PROXY; 2834 scx_divert_strip_flags(p, &enq_flags); 2835 2836 scx_dispatch_enqueue(sch, rq, &rq->scx.reject_dsq, p, 0, 0, enq_flags); 2837 } 2838 2839 /** 2840 * unlink_dsq_and_switch_rq_lock() - Unlink task and switch to its rq lock 2841 * @p: target task 2842 * @dsq: locked DSQ @p is currently on 2843 * @locked_rq: currently locked rq 2844 * @src_rq: rq @p is currently on, stable with @dsq locked 2845 * 2846 * Called with @dsq and @locked_rq locked. We want to move @p to a different DSQ, 2847 * including any local DSQ, but are not locking @src_rq. Locking @src_rq is 2848 * required when transferring into a local DSQ. Even when transferring into a 2849 * non-local DSQ, it's better to use the same mechanism to protect against 2850 * dequeues and maintain the invariant that @p->scx.dsq can only change while 2851 * @src_rq is locked, which e.g. scx_dump_task() depends on. 2852 * 2853 * We want to grab @src_rq but that can deadlock if we try while locking @dsq, 2854 * so we want to unlink @p from @dsq, drop its lock and then lock @src_rq. As 2855 * this may race with dequeue, which can't drop the rq lock or fail, do a little 2856 * dancing from our side. 2857 * 2858 * @p->scx.holding_cpu is set to this CPU before @dsq is unlocked. If @p gets 2859 * dequeued after we unlock @dsq but before locking @src_rq, the holding_cpu 2860 * would be cleared to -1. While other cpus may have updated it to different 2861 * values afterwards, as this operation can't be preempted or recurse, the 2862 * holding_cpu can never become this CPU again before we're done. Thus, we can 2863 * tell whether we lost to dequeue by testing whether the holding_cpu still 2864 * points to this CPU. See scx_dispatch_dequeue() for the counterpart. 2865 * 2866 * On return, @dsq is unlocked and @src_rq is locked. Returns %true if @p is 2867 * still valid and detached from @dsq. %false if lost to dequeue. 2868 */ 2869 static bool unlink_dsq_and_switch_rq_lock(struct task_struct *p, 2870 struct scx_dispatch_q *dsq, 2871 struct rq *locked_rq, 2872 struct rq *src_rq) 2873 { 2874 s32 cpu = raw_smp_processor_id(); 2875 2876 lockdep_assert_held(&dsq->lock); 2877 lockdep_assert_rq_held(locked_rq); 2878 2879 WARN_ON_ONCE(p->scx.holding_cpu >= 0); 2880 scx_task_unlink_from_dsq(p, dsq); 2881 p->scx.holding_cpu = cpu; 2882 2883 raw_spin_unlock(&dsq->lock); 2884 switch_rq_lock(locked_rq, src_rq); 2885 2886 /* task_rq couldn't have changed if we're still the holding cpu */ 2887 if (likely(p->scx.holding_cpu == cpu) && !WARN_ON_ONCE(src_rq != task_rq(p))) { 2888 /* 2889 * Keep ->dsq set until we own @src_rq so that a racing dequeue 2890 * can find @dsq and clear holding_cpu. Once ownership is 2891 * confirmed, clear it under @src_rq so that deactivate_task() 2892 * takes the !dsq path instead of retaking @dsq->lock. 2893 */ 2894 p->scx.dsq = NULL; 2895 scx_wait_dispatching(p); 2896 return true; 2897 } 2898 2899 return false; 2900 } 2901 2902 static bool consume_remote_task(struct scx_sched *sch, struct rq *this_rq, 2903 struct task_struct *p, u64 enq_flags, 2904 struct scx_dispatch_q *dsq, struct rq *src_rq) 2905 { 2906 if (unlink_dsq_and_switch_rq_lock(p, dsq, this_rq, src_rq)) { 2907 /* 2908 * Proxy execution may have changed @p's running or 2909 * migration-disabled state while switching rq locks without 2910 * clearing holding_cpu. Park it on the source rq and let its 2911 * owning scheduler choose its placement again. 2912 */ 2913 if (unlikely(task_proxy_unsafe_to_move(p))) { 2914 p->scx.dsq = NULL; 2915 scx_proxy_reject_task(sch, src_rq, p, enq_flags | SCX_ENQ_CLEAR_OPSS); 2916 switch_rq_lock(src_rq, this_rq); 2917 return false; 2918 } 2919 2920 move_remote_task_to_local_dsq(sch, p, enq_flags, src_rq, this_rq); 2921 return true; 2922 } else { 2923 switch_rq_lock(src_rq, this_rq); 2924 return false; 2925 } 2926 } 2927 2928 /** 2929 * move_task_between_dsqs() - Move a task from one DSQ to another 2930 * @sch: scx_sched being operated on 2931 * @p: target task 2932 * @enq_flags: %SCX_ENQ_* 2933 * @src_dsq: DSQ @p is currently on, must not be a local DSQ 2934 * @dst_dsq: DSQ @p is being moved to, can be any DSQ 2935 * 2936 * Must be called with @p's task_rq and @src_dsq locked. If @dst_dsq is a local 2937 * DSQ and @p is on a different CPU, @p will be migrated and thus its task_rq 2938 * will change. As @p's task_rq is locked, this function doesn't need to use the 2939 * holding_cpu mechanism. 2940 * 2941 * On return, @src_dsq is unlocked and only @p's new task_rq, which is the 2942 * return value, is locked. 2943 */ 2944 static struct rq *move_task_between_dsqs(struct scx_sched *sch, 2945 struct task_struct *p, u64 enq_flags, 2946 struct scx_dispatch_q *src_dsq, 2947 struct scx_dispatch_q *dst_dsq) 2948 { 2949 struct rq *src_rq = task_rq(p), *dst_rq; 2950 2951 BUG_ON(src_dsq->id == SCX_DSQ_LOCAL); 2952 lockdep_assert_held(&src_dsq->lock); 2953 lockdep_assert_rq_held(src_rq); 2954 2955 scx_wait_dispatching(p); 2956 2957 if (dst_dsq->id == SCX_DSQ_LOCAL) { 2958 dst_rq = container_of(dst_dsq, struct rq, scx.local_dsq); 2959 /* 2960 * Unlike the rq-lock handoff paths, @src_rq has been locked 2961 * throughout this operation. Only active proxy state can race the 2962 * move here; let the enforcing check below diagnose an ordinary 2963 * migration-disabled task. 2964 */ 2965 if (src_rq != dst_rq && 2966 unlikely(task_proxy_running_or_donating(p))) { 2967 dispatch_dequeue_locked(p, src_dsq); 2968 raw_spin_unlock(&src_dsq->lock); 2969 scx_proxy_reject_task(sch, src_rq, p, enq_flags); 2970 return src_rq; 2971 } 2972 if (src_rq != dst_rq && 2973 unlikely(!task_can_run_on_remote_rq(sch, p, dst_rq, true))) { 2974 dst_dsq = find_global_dsq(sch, task_cpu(p)); 2975 dst_rq = src_rq; 2976 enq_flags |= SCX_ENQ_GDSQ_FALLBACK; 2977 } 2978 } else { 2979 /* no need to migrate if destination is a non-local DSQ */ 2980 dst_rq = src_rq; 2981 } 2982 2983 /* 2984 * Move @p into $dst_dsq. If $dst_dsq is the local DSQ of a different 2985 * CPU, @p will be migrated. 2986 */ 2987 if (dst_dsq->id == SCX_DSQ_LOCAL) { 2988 /* @p is going from a non-local DSQ to a local DSQ */ 2989 if (src_rq == dst_rq) { 2990 scx_task_unlink_from_dsq(p, src_dsq); 2991 raw_spin_unlock(&src_dsq->lock); 2992 scx_move_local_task_to_local_dsq(sch, p, enq_flags, dst_rq); 2993 } else { 2994 dispatch_dequeue_locked(p, src_dsq); 2995 raw_spin_unlock(&src_dsq->lock); 2996 move_remote_task_to_local_dsq(sch, p, enq_flags, src_rq, dst_rq); 2997 } 2998 } else { 2999 /* 3000 * @p is going from a non-local DSQ to a non-local DSQ. As 3001 * $src_dsq is already locked, do an abbreviated dequeue. 3002 */ 3003 dispatch_dequeue_locked(p, src_dsq); 3004 raw_spin_unlock(&src_dsq->lock); 3005 3006 scx_dispatch_enqueue(sch, dst_rq, dst_dsq, p, 0, 0, enq_flags); 3007 } 3008 3009 return dst_rq; 3010 } 3011 3012 bool scx_consume_dispatch_q(struct scx_sched *sch, struct rq *rq, 3013 struct scx_dispatch_q *dsq, u64 enq_flags) 3014 { 3015 struct task_struct *p; 3016 retry: 3017 /* 3018 * The caller can't expect to successfully consume a task if the task's 3019 * addition to @dsq isn't guaranteed to be visible somehow. Test 3020 * @dsq->list without locking and skip if it seems empty. 3021 */ 3022 if (list_empty(&dsq->list)) 3023 return false; 3024 3025 raw_spin_lock(&dsq->lock); 3026 3027 nldsq_for_each_task(p, dsq) { 3028 struct rq *task_rq = task_rq(p); 3029 3030 /* 3031 * This loop can lead to multiple lockup scenarios, e.g. the BPF 3032 * scheduler can put an enormous number of affinitized tasks into 3033 * a contended DSQ, or the outer retry loop can repeatedly race 3034 * against scx_bypass() dequeueing tasks from @dsq trying to put 3035 * the system into the bypass mode. This can easily live-lock the 3036 * machine. If aborting, exit from all non-bypass DSQs. 3037 */ 3038 if (unlikely(READ_ONCE(sch->aborting)) && dsq->id != SCX_DSQ_BYPASS) 3039 break; 3040 3041 if (rq == task_rq) { 3042 scx_task_unlink_from_dsq(p, dsq); 3043 raw_spin_unlock(&dsq->lock); 3044 scx_move_local_task_to_local_dsq(sch, p, enq_flags, rq); 3045 return true; 3046 } 3047 3048 if (task_can_run_on_remote_rq(sch, p, rq, false)) { 3049 if (likely(consume_remote_task(sch, rq, p, enq_flags, dsq, task_rq))) 3050 return true; 3051 goto retry; 3052 } 3053 } 3054 3055 raw_spin_unlock(&dsq->lock); 3056 return false; 3057 } 3058 3059 bool scx_consume_global_dsq(struct scx_sched *sch, struct rq *rq) 3060 { 3061 int node = cpu_to_node(cpu_of(rq)); 3062 3063 return scx_consume_dispatch_q(sch, rq, &sch->pnode[node]->global_dsq, 0); 3064 } 3065 3066 /** 3067 * dispatch_to_local_dsq - Dispatch a task to a local dsq 3068 * @sch: scx_sched being operated on 3069 * @rq: current rq which is locked 3070 * @dst_dsq: destination DSQ 3071 * @p: task to dispatch 3072 * @slice: slice carried by the insert verdict, 0 keeps the current value 3073 * @vtime: vtime carried by the insert verdict, committed on PRIQ inserts 3074 * @enq_flags: %SCX_ENQ_* 3075 * 3076 * We're holding @rq lock and want to dispatch @p to @dst_dsq which is a local 3077 * DSQ. This function performs all the synchronization dancing needed because 3078 * local DSQs are protected with rq locks. 3079 * 3080 * The caller must have exclusive ownership of @p (e.g. through 3081 * %SCX_OPSS_DISPATCHING). 3082 */ 3083 static void dispatch_to_local_dsq(struct scx_sched *sch, struct rq *rq, 3084 struct scx_dispatch_q *dst_dsq, struct task_struct *p, 3085 u64 slice, u64 vtime, u64 enq_flags) 3086 { 3087 struct rq *src_rq = task_rq(p); 3088 struct rq *dst_rq = container_of(dst_dsq, struct rq, scx.local_dsq); 3089 struct rq *locked_rq = rq; 3090 3091 /* 3092 * We're synchronized against dequeue through DISPATCHING. As @p can't 3093 * be dequeued, its task_rq and cpus_allowed are stable too. 3094 * 3095 * If dispatching to @rq that @p is already on, no lock dancing needed. 3096 */ 3097 if (rq == src_rq && rq == dst_rq) { 3098 scx_dispatch_enqueue(sch, rq, dst_dsq, p, slice, vtime, 3099 enq_flags | SCX_ENQ_APPLY_SLICE | SCX_ENQ_CLEAR_OPSS); 3100 return; 3101 } 3102 3103 /* 3104 * @p is on a possibly remote @src_rq which we need to lock to move the 3105 * task. If dequeue is in progress, it'd be locking @src_rq and waiting 3106 * on DISPATCHING, so we can't grab @src_rq lock while holding 3107 * DISPATCHING. 3108 * 3109 * As DISPATCHING guarantees that @p is wholly ours, we can pretend that 3110 * we're moving from a DSQ and use the same mechanism - mark the task 3111 * under transfer with holding_cpu, release DISPATCHING and then follow 3112 * the same protocol. See unlink_dsq_and_switch_rq_lock(). 3113 */ 3114 p->scx.holding_cpu = raw_smp_processor_id(); 3115 3116 /* store_release ensures that dequeue sees the above */ 3117 atomic_long_set_release(&p->scx.ops_state, SCX_OPSS_NONE); 3118 3119 /* switch to @src_rq lock */ 3120 if (locked_rq != src_rq) { 3121 switch_rq_lock(locked_rq, src_rq); 3122 locked_rq = src_rq; 3123 } 3124 3125 /* task_rq couldn't have changed if we're still the holding cpu */ 3126 if (likely(p->scx.holding_cpu == raw_smp_processor_id()) && 3127 !WARN_ON_ONCE(src_rq != task_rq(p))) { 3128 bool fallback = false; 3129 3130 /* 3131 * If @p is staying on the same rq, there's no need to go 3132 * through the full deactivate/activate cycle. Optimize by 3133 * abbreviating move_remote_task_to_local_dsq(). 3134 */ 3135 if (src_rq == dst_rq) { 3136 p->scx.holding_cpu = -1; 3137 scx_dispatch_enqueue(sch, dst_rq, &dst_rq->scx.local_dsq, p, 3138 slice, vtime, enq_flags | SCX_ENQ_APPLY_SLICE); 3139 } else if (unlikely(task_proxy_unsafe_to_move(p))) { 3140 fallback = true; 3141 scx_proxy_reject_task(sch, src_rq, p, enq_flags); 3142 } else if (unlikely(!task_can_run_on_remote_rq(sch, p, dst_rq, true))) { 3143 p->scx.holding_cpu = -1; 3144 fallback = true; 3145 scx_dispatch_enqueue(sch, src_rq, find_global_dsq(sch, task_cpu(p)), 3146 p, slice, vtime, 3147 enq_flags | SCX_ENQ_APPLY_SLICE | 3148 SCX_ENQ_GDSQ_FALLBACK); 3149 } else { 3150 apply_slice_vtime(p, slice, vtime, enq_flags); 3151 move_remote_task_to_local_dsq(sch, p, enq_flags, src_rq, dst_rq); 3152 /* task has been moved to dst_rq, which is now locked */ 3153 locked_rq = dst_rq; 3154 } 3155 3156 /* if the destination CPU is idle, wake it up */ 3157 if (!fallback && sched_class_above(p->sched_class, 3158 dst_rq->donor->sched_class)) 3159 resched_curr(dst_rq); 3160 } 3161 3162 /* switch back to @rq lock */ 3163 if (locked_rq != rq) 3164 switch_rq_lock(locked_rq, rq); 3165 } 3166 3167 /** 3168 * finish_dispatch - Asynchronously finish dispatching a task 3169 * @sch: the scheduler 3170 * @rq: current rq which is locked 3171 * @p: task to finish dispatching 3172 * @qseq_at_dispatch: qseq when @p started getting dispatched 3173 * @dsq_id: destination DSQ ID 3174 * @slice: slice carried by the insert verdict, 0 keeps the current value 3175 * @vtime: vtime carried by the insert verdict, committed on PRIQ inserts 3176 * @enq_flags: %SCX_ENQ_* 3177 * 3178 * Dispatching to local DSQs may need to wait for queueing to complete or 3179 * require rq lock dancing. As we don't wanna do either while inside 3180 * ops.dispatch() to avoid locking order inversion, we split dispatching into 3181 * two parts. scx_bpf_dsq_insert() which is called by ops.dispatch() records the 3182 * task and its qseq. Once ops.dispatch() returns, this function is called to 3183 * finish up. 3184 * 3185 * There is no guarantee that @p is still valid for dispatching or even that it 3186 * was valid in the first place. Make sure that the task is still owned by the 3187 * BPF scheduler and claim the ownership before dispatching. 3188 */ 3189 static void finish_dispatch(struct scx_sched *sch, struct rq *rq, struct task_struct *p, 3190 unsigned long qseq_at_dispatch, u64 dsq_id, 3191 u64 slice, u64 vtime, u64 enq_flags) 3192 { 3193 struct scx_dispatch_q *dsq; 3194 unsigned long opss; 3195 3196 retry: 3197 /* 3198 * No need for _acquire here. @p is accessed only after a successful 3199 * try_cmpxchg to DISPATCHING. 3200 */ 3201 opss = atomic_long_read(&p->scx.ops_state); 3202 3203 switch (opss & SCX_OPSS_STATE_MASK) { 3204 case SCX_OPSS_DISPATCHING: 3205 case SCX_OPSS_NONE: 3206 /* someone else already got to it */ 3207 return; 3208 case SCX_OPSS_QUEUED: 3209 /* 3210 * If qseq doesn't match, @p has gone through at least one 3211 * dispatch/dequeue and re-enqueue cycle between 3212 * scx_bpf_dsq_insert() and here and we have no claim on it. 3213 */ 3214 if ((opss & SCX_OPSS_QSEQ_MASK) != qseq_at_dispatch) 3215 return; 3216 3217 /* see SCX_EV_INSERT_NOT_OWNED definition */ 3218 if (unlikely(!scx_task_on_sched(sch, p))) { 3219 __scx_add_event(sch, SCX_EV_INSERT_NOT_OWNED, 1); 3220 return; 3221 } 3222 3223 /* 3224 * While we know @p is accessible, we don't yet have a claim on 3225 * it - the BPF scheduler is allowed to dispatch tasks 3226 * spuriously and there can be a racing dequeue attempt. Let's 3227 * claim @p by atomically transitioning it from QUEUED to 3228 * DISPATCHING. 3229 */ 3230 if (likely(atomic_long_try_cmpxchg(&p->scx.ops_state, &opss, 3231 SCX_OPSS_DISPATCHING))) 3232 break; 3233 goto retry; 3234 case SCX_OPSS_QUEUEING: 3235 /* 3236 * scx_do_enqueue_task() is in the process of transferring the 3237 * task to the BPF scheduler while holding @p's rq lock. As we 3238 * aren't holding any kernel or BPF resource that the enqueue 3239 * path may depend upon, it's safe to wait. 3240 */ 3241 wait_ops_state(p, opss); 3242 goto retry; 3243 } 3244 3245 BUG_ON(!(p->scx.flags & SCX_TASK_QUEUED)); 3246 3247 dsq = find_dsq_for_dispatch(sch, rq, dsq_id, task_cpu(p)); 3248 3249 if (dsq->id == SCX_DSQ_LOCAL) 3250 dispatch_to_local_dsq(sch, rq, dsq, p, slice, vtime, enq_flags); 3251 else 3252 scx_dispatch_enqueue(sch, rq, dsq, p, slice, vtime, 3253 enq_flags | SCX_ENQ_APPLY_SLICE | SCX_ENQ_CLEAR_OPSS); 3254 } 3255 3256 void scx_flush_dispatch_buf(struct scx_sched *sch, struct rq *rq) 3257 { 3258 struct scx_dsp_ctx *dspc = &this_cpu_ptr(sch->pcpu)->dsp_ctx; 3259 u32 u; 3260 3261 for (u = 0; u < dspc->cursor; u++) { 3262 struct scx_dsp_buf_ent *ent = &dspc->buf[u]; 3263 3264 finish_dispatch(sch, rq, ent->task, ent->qseq, ent->dsq_id, 3265 ent->slice, ent->vtime, ent->enq_flags); 3266 } 3267 3268 dspc->nr_tasks += dspc->cursor; 3269 dspc->cursor = 0; 3270 } 3271 3272 static inline void maybe_queue_balance_callback(struct rq *rq) 3273 { 3274 lockdep_assert_rq_held(rq); 3275 3276 if (!(rq->scx.flags & SCX_RQ_BAL_CB_PENDING)) 3277 return; 3278 3279 queue_balance_callback(rq, &rq->scx.deferred_bal_cb, 3280 deferred_bal_cb_workfn); 3281 3282 rq->scx.flags &= ~SCX_RQ_BAL_CB_PENDING; 3283 } 3284 3285 static enum scx_dsp_verdict dispatch_one(struct rq *rq, struct task_struct *prev) 3286 { 3287 struct scx_sched *root_sch = scx_root_protected_live(); 3288 enum scx_dsp_verdict verdict; 3289 s32 cpu = cpu_of(rq); 3290 3291 lockdep_assert_rq_held(rq); 3292 rq->scx.flags |= SCX_RQ_IN_DISPATCH; 3293 3294 scx_process_sync_ecaps(rq, prev); 3295 3296 if ((root_sch->ops.flags & SCX_OPS_HAS_CPU_PREEMPT) && 3297 unlikely(rq->scx.cpu_released)) { 3298 /* 3299 * If the previous sched_class for the current CPU was not SCX, 3300 * notify the BPF scheduler that it again has control of the 3301 * core. This callback complements ->cpu_release(), which is 3302 * emitted in switch_class(). 3303 */ 3304 if (root_sch->ops.cpu_acquire) 3305 SCX_CALL_OP(root_sch, cpu_acquire, rq, cpu, NULL); 3306 rq->scx.cpu_released = false; 3307 } 3308 3309 if (prev->sched_class == &ext_sched_class) { 3310 update_curr_scx(rq); 3311 3312 /* 3313 * If @prev is runnable & has slice left, it has priority and 3314 * fetching more just increases latency for the fetched tasks. 3315 * Tell pick_task_scx() to keep running @prev. If the BPF 3316 * scheduler wants to handle this explicitly, it should 3317 * implement ->cpu_release(). 3318 * 3319 * See scx_disable_workfn() for the explanation on the bypassing 3320 * test. 3321 */ 3322 if ((prev->scx.flags & SCX_TASK_QUEUED) && prev->scx.slice && 3323 !scx_bypassing(scx_task_sched(prev), cpu)) { 3324 verdict = SCX_DSP_PREV; 3325 goto has_tasks; 3326 } 3327 } 3328 3329 /* if there already are tasks to run, nothing to do */ 3330 if (rq->scx.local_dsq.nr) { 3331 verdict = SCX_DSP_LOCAL; 3332 goto has_tasks; 3333 } 3334 3335 verdict = scx_dispatch_sched(root_sch, rq, prev, false); 3336 if (verdict != SCX_DSP_NONE) 3337 goto has_tasks; 3338 3339 /* 3340 * Didn't find another task to run. Keep running @prev unless its own 3341 * scheduler set %SCX_OPS_ENQ_LAST and takes the enqueue instead, see 3342 * put_prev_task_scx(). Read the scheduler here as the dispatch above 3343 * may have dropped the rq lock while @prev changed class or scheduler. 3344 */ 3345 if (prev->scx.flags & SCX_TASK_QUEUED) { 3346 struct scx_sched *prev_sch = scx_task_sched(prev); 3347 3348 if ((!(prev_sch->ops.flags & SCX_OPS_ENQ_LAST) || 3349 scx_bypassing(prev_sch, cpu)) && scx_task_can_stay_on_cpu(rq, prev)) { 3350 __scx_add_event(prev_sch, SCX_EV_DISPATCH_KEEP_LAST, 1); 3351 verdict = SCX_DSP_PREV; 3352 goto has_tasks; 3353 } 3354 } 3355 rq->scx.flags &= ~SCX_RQ_IN_DISPATCH; 3356 return SCX_DSP_NONE; 3357 3358 has_tasks: 3359 /* 3360 * @rq may have extra IMMED tasks without reenq scheduled: 3361 * 3362 * - rq_is_open() can't reliably tell when and how slice is going to be 3363 * modified for $curr and allows IMMED tasks to be queued while 3364 * dispatch is in progress. 3365 * 3366 * - A non-IMMED HEAD task can get queued in front of an IMMED task 3367 * between the IMMED queueing and the subsequent scheduling event. 3368 */ 3369 if (unlikely(rq->scx.local_dsq.nr > 1 && rq->scx.nr_immed)) 3370 scx_schedule_reenq_local(rq, 0); 3371 3372 rq->scx.flags &= ~SCX_RQ_IN_DISPATCH; 3373 return verdict; 3374 } 3375 3376 static void scx_start_task_running(struct rq *rq, struct task_struct *p) 3377 { 3378 struct scx_sched *sch = scx_task_sched(p); 3379 3380 if (p->scx.flags & SCX_TASK_RUN_TRACKED) 3381 return; 3382 3383 scx_cid_sched_update(rq, sch); 3384 3385 if (SCX_HAS_OP(sch, running)) 3386 SCX_CALL_OP_TASK(sch, running, rq, p); 3387 3388 p->scx.flags |= SCX_TASK_RUN_TRACKED; 3389 } 3390 3391 static void set_next_task_scx(struct rq *rq, struct task_struct *p, enum snt_e type) 3392 { 3393 bool first = type == SNT_PICK; 3394 bool can_stop_tick; 3395 3396 /* 3397 * A blocked pick is provisional until proxy resolution completes, see 3398 * put_prev_task_scx(). A retry can repick the same donor, so 3399 * SNT_REPICK must set it again. 3400 */ 3401 rq->scx.flags &= ~SCX_RQ_PROXY_PENDING; 3402 if (sched_proxy_exec() && p->is_blocked && 3403 (type == SNT_PICK || type == SNT_REPICK)) 3404 rq->scx.flags |= SCX_RQ_PROXY_PENDING; 3405 3406 if (type == SNT_REPICK) 3407 return; 3408 3409 if (p->scx.flags & SCX_TASK_QUEUED) { 3410 /* 3411 * Core-sched might decide to execute @p before it is 3412 * dispatched. Call ops_dequeue() to notify the BPF scheduler. 3413 */ 3414 ops_dequeue(rq, p, SCX_DEQ_CORE_SCHED_EXEC); 3415 scx_dispatch_dequeue(rq, p); 3416 p->scx.flags &= ~SCX_TASK_REENQ_REASON_MASK; 3417 } 3418 3419 p->se.exec_start = rq_clock_task(rq); 3420 3421 /* 3422 * See dequeue_task_scx() for why we skip when !QUEUED. 3423 * 3424 * During a normal switch (@first), a blocked task is only a provisional 3425 * donor. Proxy resolution may fail or migrate the donor to another CPU, 3426 * so defer ops.running() until scx_proxy_donor_start() confirms that 3427 * resolution succeeded. 3428 * 3429 * !@first denotes restoration after a SAVE/RESTORE cycle. The matching 3430 * dequeue already issued ops.stopping(), so restart the session here 3431 * regardless of the donor state. 3432 */ 3433 if ((p->scx.flags & SCX_TASK_QUEUED) && !(p->is_blocked && first)) 3434 scx_start_task_running(rq, p); 3435 3436 clr_task_runnable(p, true); 3437 3438 /* apply any pending out-of-band slice request before the tick decision */ 3439 apply_task_slice_oob(rq, p); 3440 can_stop_tick = p->scx.slice == SCX_SLICE_INF && !p->is_blocked; 3441 3442 /* 3443 * @p is getting newly scheduled or got kicked after someone updated its 3444 * slice. Update SCX_RQ_CAN_STOP_TICK to reflect whether the tick can be 3445 * stopped. See scx_can_stop_tick(). 3446 * 3447 * Moreover, refresh the load_avgs just when transitioning in and out of 3448 * nohz. In the future, we might want to add a mechanism to update 3449 * load_avgs periodically on tick-stopped CPUs. 3450 */ 3451 if (can_stop_tick) { 3452 if (!(rq->scx.flags & SCX_RQ_CAN_STOP_TICK)) { 3453 /* 3454 * Bypass mode always assigns finite slices, so @p 3455 * can't have an infinite slice while bypassing. 3456 * Therefore, sched_update_tick_dependency() can safely 3457 * evaluate the outgoing task. 3458 */ 3459 rq->scx.flags |= SCX_RQ_CAN_STOP_TICK; 3460 sched_update_tick_dependency(rq); 3461 3462 update_other_load_avgs(rq); 3463 } 3464 } else { 3465 if (rq->scx.flags & SCX_RQ_CAN_STOP_TICK) { 3466 rq->scx.flags &= ~SCX_RQ_CAN_STOP_TICK; 3467 update_other_load_avgs(rq); 3468 } 3469 3470 /* 3471 * @rq still references the outgoing scheduling context. A finite 3472 * slice or a blocked proxy donor is sufficient by itself to require 3473 * the tick. 3474 */ 3475 if (tick_nohz_full_cpu(cpu_of(rq))) 3476 tick_nohz_dep_set_cpu(cpu_of(rq), TICK_DEP_BIT_SCHED); 3477 } 3478 } 3479 3480 void scx_proxy_donor_start(struct rq *rq) 3481 { 3482 struct task_struct *donor = rq->donor; 3483 3484 lockdep_assert_rq_held(rq); 3485 rq->scx.flags &= ~SCX_RQ_PROXY_PENDING; 3486 3487 if (donor->sched_class == &ext_sched_class && (donor->scx.flags & SCX_TASK_QUEUED)) 3488 scx_start_task_running(rq, donor); 3489 } 3490 3491 static enum scx_cpu_preempt_reason 3492 preempt_reason_from_class(const struct sched_class *class) 3493 { 3494 if (class == &stop_sched_class) 3495 return SCX_CPU_PREEMPT_STOP; 3496 if (class == &dl_sched_class) 3497 return SCX_CPU_PREEMPT_DL; 3498 if (class == &rt_sched_class) 3499 return SCX_CPU_PREEMPT_RT; 3500 return SCX_CPU_PREEMPT_UNKNOWN; 3501 } 3502 3503 static void switch_class(struct rq *rq, struct task_struct *next) 3504 { 3505 struct scx_sched *sch = scx_root_protected_live(); 3506 const struct sched_class *next_class = next->sched_class; 3507 3508 if (!(sch->ops.flags & SCX_OPS_HAS_CPU_PREEMPT)) 3509 return; 3510 3511 /* 3512 * The callback is conceptually meant to convey that the CPU is no 3513 * longer under the control of SCX. Therefore, don't invoke the callback 3514 * if the next class is below SCX (in which case the BPF scheduler has 3515 * actively decided not to schedule any tasks on the CPU). 3516 */ 3517 if (sched_class_above(&ext_sched_class, next_class)) 3518 return; 3519 3520 /* 3521 * At this point we know that SCX was preempted by a higher priority 3522 * sched_class, so invoke the ->cpu_release() callback if we have not 3523 * done so already. We only send the callback once between SCX being 3524 * preempted, and it regaining control of the CPU. 3525 * 3526 * ->cpu_release() complements ->cpu_acquire(), which is emitted the 3527 * next time that dispatch_one() is invoked. 3528 */ 3529 if (!rq->scx.cpu_released) { 3530 if (sch->ops.cpu_release) { 3531 struct scx_cpu_release_args args = { 3532 .reason = preempt_reason_from_class(next_class), 3533 .task = next, 3534 }; 3535 3536 SCX_CALL_OP(sch, cpu_release, rq, cpu_of(rq), &args); 3537 } 3538 rq->scx.cpu_released = true; 3539 } 3540 } 3541 3542 static void put_prev_task_scx(struct rq *rq, struct task_struct *p, 3543 struct task_struct *next) 3544 { 3545 struct scx_sched *sch = scx_task_sched(p); 3546 bool proxy_put = p->is_blocked && next == rq->idle && 3547 (rq->scx.flags & SCX_RQ_PROXY_PENDING); 3548 bool proxy_block = rq->scx.flags & SCX_RQ_PROXY_BLOCKING; 3549 bool rescue_keep = false; 3550 3551 rq->scx.flags &= ~SCX_RQ_PROXY_PENDING; 3552 3553 /* see kick_sync_wait_bal_cb() */ 3554 smp_store_release(&rq->scx.kick_sync, rq->scx.kick_sync + 1); 3555 3556 update_curr_scx(rq); 3557 3558 /* 3559 * If the slice is consumed, protection ends with it. A rescuee 3560 * preempted beforehand keeps going, see scx_rescue_keep(). 3561 */ 3562 if (!p->scx.slice) { 3563 if (unlikely(p == scx_rescuee(rq))) 3564 rescue_keep = scx_rescue_keep(rq, p); 3565 if (!rescue_keep) 3566 scx_task_slice_ended(rq, p); 3567 } 3568 3569 /* 3570 * Preserve the running session when proxy execution refreshes the same 3571 * donor around an execution-context switch on this rq. 3572 */ 3573 if (next != p && (p->scx.flags & SCX_TASK_QUEUED) && 3574 (p->scx.flags & SCX_TASK_RUN_TRACKED)) { 3575 if (SCX_HAS_OP(sch, stopping)) 3576 SCX_CALL_OP_TASK(sch, stopping, rq, p, !proxy_block); 3577 3578 p->scx.flags &= ~SCX_TASK_RUN_TRACKED; 3579 } 3580 3581 if (p->scx.flags & SCX_TASK_QUEUED) { 3582 if (proxy_block) 3583 goto switch_class; 3584 3585 set_task_runnable(rq, p); 3586 3587 /* 3588 * If the donor is the same and only the mutex owner changes, 3589 * avoid triggering another ops.enqueue(): the BPF scheduler has 3590 * already admitted the donor, so it can continue running. 3591 */ 3592 if (p->is_blocked && next == p) 3593 goto switch_class; 3594 3595 /* 3596 * If @p has slice left and is being put, @p is getting 3597 * preempted by a higher priority scheduler class or core-sched 3598 * forcing a different task. Leave it at the head of the local 3599 * DSQ unless it was an IMMED task. IMMED tasks should not 3600 * linger on a busy CPU, reenqueue them to the BPF scheduler. 3601 * 3602 * The exception is an IMMED donor put by proxy_resched_idle(): 3603 * the CPU isn't busy, proxy resolution is only retrying through 3604 * idle, so keep the donor where it can be picked again. 3605 * 3606 * An open rescue must keep @p on the local DSQ even if the 3607 * scheduler zeroed the slice in ops.stopping() above. 3608 */ 3609 if ((p->scx.slice || unlikely(p == scx_rescuee(rq))) && 3610 !scx_bypassing(sch, cpu_of(rq))) { 3611 if ((p->scx.flags & SCX_TASK_IMMED) && !proxy_put) { 3612 p->scx.flags |= SCX_TASK_REENQ_PREEMPTED; 3613 scx_do_enqueue_task(rq, p, SCX_ENQ_REENQ, -1); 3614 } else { 3615 u64 enq_flags = 0; 3616 3617 /* 3618 * Keep a preempted rescue going. If preempted 3619 * by another SCX task, append to the local DSQ, 3620 * see scx_rescue_keep(). 3621 */ 3622 if (unlikely(p == scx_rescuee(rq))) { 3623 enq_flags |= SCX_ENQ_IGNORE_CAPS; 3624 if (!rescue_keep) 3625 enq_flags |= SCX_ENQ_HEAD; 3626 } else { 3627 enq_flags |= SCX_ENQ_HEAD; 3628 /* only require SCX_CAP_ENQ_IMMED, see scx_caps_for_enq() */ 3629 if (proxy_put && (p->scx.flags & SCX_TASK_IMMED)) 3630 enq_flags |= SCX_ENQ_IMMED; 3631 } 3632 3633 scx_dispatch_enqueue(sch, rq, &rq->scx.local_dsq, p, 0, 0, 3634 enq_flags); 3635 } 3636 goto switch_class; 3637 } 3638 3639 /* 3640 * If @p is runnable but we're about to enter a lower 3641 * sched_class, %SCX_OPS_ENQ_LAST must be set. Tell 3642 * ops.enqueue() that @p is the only one available for this cpu. 3643 * This doesn't apply if the baseline access on the CPU is lost or 3644 * proxy resolution temporarily switches to idle. 3645 * 3646 * Under core scheduling, a pick dispatches only when nothing is 3647 * locally runnable and can legitimately go idle with @p still 3648 * runnable (see do_pick_task_scx()). 3649 */ 3650 if (!proxy_put && next && 3651 sched_class_above(&ext_sched_class, next->sched_class) && 3652 scx_task_can_stay_on_cpu(rq, p)) { 3653 WARN_ON_ONCE(!sched_core_enabled(rq) && 3654 !(sch->ops.flags & SCX_OPS_ENQ_LAST)); 3655 scx_do_enqueue_task(rq, p, SCX_ENQ_LAST, -1); 3656 3657 /* 3658 * A task put on the local DSQ runs, as anywhere else. 3659 * Here the insert can't reschedule on its own: the pick 3660 * has settled on @next and @p is still curr, so 3661 * resched_curr() would flag @p and __schedule() clears 3662 * that right after the pick. Flag @next instead. 3663 */ 3664 if (p->scx.dsq == &rq->scx.local_dsq) 3665 set_tsk_need_resched(next); 3666 } else { 3667 scx_do_enqueue_task(rq, p, 0, -1); 3668 } 3669 } 3670 3671 switch_class: 3672 if (next && next->sched_class != &ext_sched_class) { 3673 scx_cid_sched_update(rq, NULL); 3674 switch_class(rq, next); 3675 } 3676 } 3677 3678 static void kick_sync_wait_bal_cb(struct rq *rq) 3679 { 3680 struct scx_kick_syncs __rcu *ks; 3681 unsigned long *ksyncs; 3682 bool waited; 3683 s32 cpu; 3684 3685 /* 3686 * This callback is queued and normally flushed within @rq's own 3687 * scheduling pass. However, dispatch can drop the rq lock while it sits 3688 * queued, and lock takers in that window (the sched class change paths, 3689 * the scx task iterator) flush pending balance callbacks on release, 3690 * running this one on a foreign CPU whose snapshots are unrelated. The 3691 * kicked CPUs are already on their way to advance the kick_syncs being 3692 * waited on. Don't get in the way. 3693 */ 3694 if (unlikely(cpu_of(rq) != smp_processor_id())) 3695 return; 3696 3697 ks = __this_cpu_read(scx_kick_syncs); 3698 ksyncs = rcu_dereference_sched(ks)->syncs; 3699 3700 /* 3701 * Drop rq lock and enable IRQs while waiting. IRQs must be enabled 3702 * — a target CPU may be waiting for us to process an IPI (e.g. TLB 3703 * flush) while we wait for its kick_sync to advance. 3704 * 3705 * Also, keep advancing our own kick_sync so that new kick_sync waits 3706 * targeting us, which can start after we drop the lock, cannot form 3707 * cyclic dependencies. 3708 */ 3709 retry: 3710 waited = false; 3711 for_each_cpu(cpu, rq->scx.cpus_to_sync) { 3712 /* 3713 * smp_load_acquire() pairs with smp_store_release() on 3714 * kick_sync updates on the target CPUs. 3715 */ 3716 if (cpu == cpu_of(rq) || 3717 smp_load_acquire(&cpu_rq(cpu)->scx.kick_sync) != ksyncs[cpu]) { 3718 cpumask_clear_cpu(cpu, rq->scx.cpus_to_sync); 3719 continue; 3720 } 3721 3722 scx_rq_lock_drop(rq); 3723 raw_spin_rq_unlock_irq(rq); 3724 while (READ_ONCE(cpu_rq(cpu)->scx.kick_sync) == ksyncs[cpu]) { 3725 smp_store_release(&rq->scx.kick_sync, rq->scx.kick_sync + 1); 3726 cpu_relax(); 3727 } 3728 raw_spin_rq_lock_irq(rq); 3729 waited = true; 3730 } 3731 3732 if (waited) 3733 goto retry; 3734 } 3735 3736 static struct task_struct *first_local_task(struct rq *rq) 3737 { 3738 return list_first_entry_or_null(&rq->scx.local_dsq.list, 3739 struct task_struct, scx.dsq_list.node); 3740 } 3741 3742 /* 3743 * Run dispatch for a pick. The follow-up work is queued by do_pick_task_scx() 3744 * once the pick is final. 3745 */ 3746 static enum scx_dsp_verdict dispatch_pick(struct rq *rq, struct rq_flags *rf, 3747 struct task_struct *prev) 3748 { 3749 enum scx_dsp_verdict verdict; 3750 3751 rq_unpin_lock(rq, rf); 3752 verdict = dispatch_one(rq, prev); 3753 rq_repin_lock(rq, rf); 3754 3755 return verdict; 3756 } 3757 3758 #ifdef CONFIG_SCHED_CORE 3759 /* 3760 * Dispatch for a pick when core scheduling is enabled. The selection picks for 3761 * all SMT siblings and the rq_i->core_pick state it builds must stay atomic 3762 * throughout. If the dispatch released the rq lock, anything can have happened 3763 * in between - return %SCX_DSP_RETRY to restart the selection against current 3764 * state. 3765 */ 3766 static enum scx_dsp_verdict dispatch_core_pick(struct rq *rq, struct rq_flags *rf, 3767 struct task_struct *prev) 3768 { 3769 enum scx_dsp_verdict verdict; 3770 u32 seq = rq->scx.lock_drop_seq; 3771 3772 /* another dispatch is in flight on @rq, let that handle it */ 3773 if (rq->scx.flags & SCX_RQ_IN_DISPATCH) 3774 return SCX_DSP_NONE; 3775 3776 rq_unpin_lock(rq, rf); 3777 3778 verdict = dispatch_one(rq, prev); 3779 3780 /* 3781 * A pick that returns a task isn't final under core scheduling: the 3782 * selection goes on to pick the siblings, and their dispatch can 3783 * release the rq lock, which can't happen with balance callbacks 3784 * queued. Don't queue the deferred work as a balance callback, for this 3785 * CPU or a sibling, and run it from irq_work instead. 3786 * 3787 * do_pick_task_scx() leaves %SCX_RQ_BAL_CB_PENDING alone under core 3788 * scheduling, so that the early return above leaves it to the dispatch 3789 * in flight, which handles it here. 3790 */ 3791 if (unlikely(rq->scx.flags & SCX_RQ_BAL_CB_PENDING)) { 3792 rq->scx.flags &= ~SCX_RQ_BAL_CB_PENDING; 3793 schedule_deferred(rq); 3794 } 3795 3796 rq_repin_lock(rq, rf); 3797 3798 /* if dispatch_one() released the rq lock, restart the selection */ 3799 if (rq->scx.lock_drop_seq != seq) 3800 return SCX_DSP_RETRY; 3801 3802 return verdict; 3803 } 3804 #else /* CONFIG_SCHED_CORE */ 3805 static enum scx_dsp_verdict dispatch_core_pick(struct rq *rq, struct rq_flags *rf, 3806 struct task_struct *prev) 3807 { 3808 return SCX_DSP_NONE; 3809 } 3810 #endif /* CONFIG_SCHED_CORE */ 3811 3812 static struct task_struct * 3813 do_pick_task_scx(struct rq *rq, struct rq_flags *rf, bool force_scx) 3814 { 3815 struct task_struct *prev = rq->donor; 3816 bool core_sched = sched_core_enabled(rq); 3817 enum scx_dsp_verdict verdict; 3818 struct task_struct *p; 3819 3820 /* A retry can abandon a provisional blocked-donor pick. */ 3821 rq->scx.flags &= ~SCX_RQ_PROXY_PENDING; 3822 3823 /* see kick_sync_wait_bal_cb() */ 3824 smp_store_release(&rq->scx.kick_sync, rq->scx.kick_sync + 1); 3825 3826 rq_modified_begin(rq, &ext_sched_class); 3827 3828 /* 3829 * Core scheduling can get enabled while dispatch_pick() has the rq lock 3830 * released. Stick to @core_sched, so that the follow-up work below 3831 * matches the dispatch that ran. 3832 */ 3833 if (core_sched) 3834 verdict = dispatch_core_pick(rq, rf, prev); 3835 else 3836 verdict = dispatch_pick(rq, rf, prev); 3837 3838 if (verdict == SCX_DSP_RETRY) { 3839 p = RETRY_TASK; 3840 goto out; 3841 } 3842 3843 /* 3844 * If any higher-priority sched class enqueued a runnable task on this 3845 * rq during dispatch_one(), abort and return RETRY_TASK, so that the 3846 * scheduler loop can restart. 3847 * 3848 * If @force_scx is true, always try to pick a SCHED_EXT task, 3849 * regardless of any higher-priority sched classes activity. 3850 */ 3851 if (!force_scx && rq_modified_above(rq, &ext_sched_class)) { 3852 p = RETRY_TASK; 3853 goto out; 3854 } 3855 3856 /* 3857 * If we're keeping @prev, replenish slice if necessary and keep running 3858 * @prev. Otherwise, pop the first one from the local DSQ. 3859 */ 3860 if (verdict == SCX_DSP_PREV) { 3861 p = prev; 3862 if (!p->scx.slice) { 3863 /* the slice is consumed, protection ends */ 3864 scx_task_slice_ended(rq, p); 3865 refill_task_slice_dfl(scx_task_sched(p), p); 3866 } 3867 } else { 3868 p = first_local_task(rq); 3869 if (!p) 3870 goto out; 3871 3872 if (unlikely(!p->scx.slice) && scx_task_can_stay_on_cpu(rq, p)) { 3873 struct scx_sched *sch = scx_task_sched(p); 3874 3875 if (!scx_bypassing(sch, cpu_of(rq)) && 3876 !sch->warned_zero_slice) { 3877 printk_deferred(KERN_WARNING "sched_ext: %s[%d] has zero slice in %s()\n", 3878 p->comm, p->pid, __func__); 3879 sch->warned_zero_slice = true; 3880 } 3881 refill_task_slice_dfl(sch, p); 3882 } 3883 } 3884 3885 out: 3886 if (cpu_of(rq) != smp_processor_id()) 3887 return p; 3888 3889 /* 3890 * Balance callbacks must be consumed before the rq lock is released, so 3891 * queue them only when the pick is final. On RETRY_TASK, or after a 3892 * NULL pick from the dl_server, the core continues picking and can 3893 * release the rq lock (e.g., prev_balance() or another dispatch). In 3894 * that case, run the deferred work from irq_work, which doesn't depend 3895 * on the current rq lock section, and leave the kick sync wait pending 3896 * for the next pick. 3897 */ 3898 if (p != RETRY_TASK && (p || !force_scx)) { 3899 /* under core scheduling, see dispatch_core_pick() */ 3900 if (!core_sched) 3901 maybe_queue_balance_callback(rq); 3902 3903 /* 3904 * Defer to a balance callback which can drop rq lock and enable 3905 * IRQs. Waiting directly in the pick path would deadlock against 3906 * CPUs sending us IPIs (e.g., TLB flushes) while we wait for 3907 * them. 3908 */ 3909 if (unlikely(rq->scx.kick_sync_pending)) { 3910 rq->scx.kick_sync_pending = false; 3911 queue_balance_callback(rq, &rq->scx.kick_sync_bal_cb, 3912 kick_sync_wait_bal_cb); 3913 } 3914 } else if (!core_sched && (rq->scx.flags & SCX_RQ_BAL_CB_PENDING)) { 3915 rq->scx.flags &= ~SCX_RQ_BAL_CB_PENDING; 3916 schedule_deferred(rq); 3917 } 3918 3919 return p; 3920 } 3921 3922 static struct task_struct *pick_task_scx(struct rq *rq, struct rq_flags *rf) 3923 { 3924 return do_pick_task_scx(rq, rf, false); 3925 } 3926 3927 /* 3928 * Select the next task to run from the ext scheduling class. 3929 * 3930 * Use do_pick_task_scx() directly with @force_scx enabled, since the 3931 * dl_server must always select a sched_ext task. 3932 */ 3933 static struct task_struct * 3934 ext_server_pick_task(struct sched_dl_entity *dl_se, struct rq_flags *rf) 3935 { 3936 if (!scx_enabled()) 3937 return NULL; 3938 3939 return do_pick_task_scx(dl_se->rq, rf, true); 3940 } 3941 3942 /* 3943 * Initialize the ext server deadline entity. 3944 */ 3945 void ext_server_init(struct rq *rq) 3946 { 3947 struct sched_dl_entity *dl_se = &rq->ext_server; 3948 3949 init_dl_entity(dl_se); 3950 3951 dl_server_init(dl_se, rq, ext_server_pick_task); 3952 } 3953 3954 #ifdef CONFIG_SCHED_CORE 3955 /** 3956 * scx_prio_less - Task ordering for core-sched 3957 * @a: task A 3958 * @b: task B 3959 * @in_fi: in forced idle state 3960 * 3961 * Core-sched is implemented as an additional scheduling layer on top of the 3962 * usual sched_class'es and needs to find out the expected task ordering. For 3963 * SCX, core-sched calls this function to interrogate the task ordering. 3964 * 3965 * A pair of tasks owned by one scheduler is ordered by the owner's 3966 * ops.core_sched_before(). A pair spanning two schedulers is ordered by their 3967 * nearest common ancestor which implements the op - the one case where the op 3968 * is called on tasks that the scheduler delegated to its sub-schedulers and may 3969 * not be scheduling anymore. 3970 * 3971 * When neither applies, or the deciding scheduler is bypassing on either task's 3972 * CPU, the default ordering runs the task which has been waiting longer first. 3973 * A running task counts as the most recently serviced and orders after every 3974 * waiting task. Waiting tasks are compared by @p->scx.runnable_at. 3975 * 3976 * Return: %true if @a should run after @b. 3977 */ 3978 bool scx_prio_less(const struct task_struct *a, const struct task_struct *b, 3979 bool in_fi) 3980 { 3981 struct scx_sched *sch_a = scx_task_sched(a); 3982 struct scx_sched *sch_b = scx_task_sched(b); 3983 struct scx_sched *sch = NULL; 3984 bool a_running, b_running; 3985 3986 if (sch_a == sch_b) { 3987 if (SCX_HAS_OP(sch_a, core_sched_before)) 3988 sch = sch_a; 3989 } else { 3990 s32 level; 3991 3992 for (level = min(sch_a->level, sch_b->level); level >= 0; level--) { 3993 struct scx_sched *anc = sch_a->ancestors[level]; 3994 3995 if (anc == sch_b->ancestors[level] && 3996 SCX_HAS_OP(anc, core_sched_before)) { 3997 sch = anc; 3998 break; 3999 } 4000 } 4001 } 4002 4003 /* 4004 * scx_prio_less() returns whether @a should run after @b while 4005 * ops.core_sched_before() returns whether its first argument should run 4006 * before the second. Swap the arguments. 4007 * 4008 * The const qualifiers are dropped from task_struct pointers when 4009 * calling ops.core_sched_before(). Accesses are controlled by the 4010 * verifier. 4011 */ 4012 if (sch && !scx_bypassing(sch, task_cpu(a)) && !scx_bypassing(sch, task_cpu(b))) 4013 return SCX_CALL_OP_2TASKS_RET(sch, core_sched_before, task_rq(a), 4014 (struct task_struct *)b, 4015 (struct task_struct *)a); 4016 4017 /* 4018 * runnable_at is refreshed only on enqueue, so a task which keeps 4019 * occupying its CPU carries a stale stamp. A running task is the most 4020 * recently serviced whatever its stamp says. Order it after every 4021 * waiting task. 4022 */ 4023 a_running = a->on_cpu; 4024 b_running = b->on_cpu; 4025 if (a_running != b_running) 4026 return a_running; 4027 4028 return time_after(a->scx.runnable_at, b->scx.runnable_at); 4029 } 4030 #endif /* CONFIG_SCHED_CORE */ 4031 4032 static int select_task_rq_scx(struct task_struct *p, int prev_cpu, int wake_flags) 4033 { 4034 struct scx_sched *sch = scx_task_sched(p); 4035 bool bypassing; 4036 4037 /* 4038 * sched_exec() calls with %WF_EXEC when @p is about to exec(2) as it 4039 * can be a good migration opportunity with low cache and memory 4040 * footprint. Returning a CPU different than @prev_cpu triggers 4041 * immediate rq migration. However, for SCX, as the current rq 4042 * association doesn't dictate where the task is going to run, this 4043 * doesn't fit well. If necessary, we can later add a dedicated method 4044 * which can decide to preempt self to force it through the regular 4045 * scheduling path. 4046 */ 4047 if (unlikely(wake_flags & WF_EXEC)) 4048 return prev_cpu; 4049 4050 bypassing = scx_bypassing(sch, task_cpu(p)); 4051 if (likely(SCX_HAS_OP(sch, select_cpu)) && !bypassing) { 4052 s32 cpu; 4053 struct task_struct **ddsp_taskp; 4054 4055 ddsp_taskp = this_cpu_ptr(&direct_dispatch_task); 4056 WARN_ON_ONCE(*ddsp_taskp); 4057 *ddsp_taskp = p; 4058 4059 this_rq()->scx.in_select_cpu = true; 4060 cpu = SCX_CALL_OP_TASK_RET(sch, select_cpu, NULL, p, 4061 scx_cpu_arg(prev_cpu), wake_flags); 4062 cpu = scx_cpu_ret(sch, cpu); 4063 this_rq()->scx.in_select_cpu = false; 4064 p->scx.selected_cpu = cpu; 4065 *ddsp_taskp = NULL; 4066 if (scx_cpu_valid(sch, cpu, "from ops.select_cpu()")) 4067 return cpu; 4068 else 4069 return prev_cpu; 4070 } else { 4071 s32 cpu; 4072 4073 /* 4074 * While bypassing, the enqueue path routes @p to a bypass DSQ 4075 * without consulting the direct-dispatch target, making the 4076 * default selection pointless. It doesn't work anyway when the 4077 * scheduler does its own idle tracking and the built-in idle 4078 * cpumasks are not updated. Leave @p on @prev_cpu. 4079 */ 4080 if (bypassing) { 4081 __scx_add_event(sch, SCX_EV_BYPASS_DISPATCH, 1); 4082 p->scx.selected_cpu = prev_cpu; 4083 return prev_cpu; 4084 } 4085 4086 cpu = scx_select_cpu_dfl(p, prev_cpu, wake_flags, NULL, 0); 4087 if (cpu >= 0) { 4088 /* 4089 * Carry the slice refill and let the insertion commit 4090 * it under rq lock. See the write rules. 4091 */ 4092 __scx_add_event(sch, SCX_EV_REFILL_SLICE_DFL, 1); 4093 p->scx.ddsp_slice = READ_ONCE(sch->slice_dfl); 4094 p->scx.ddsp_enq_flags = SCX_ENQ_SLICE_DFL; 4095 p->scx.ddsp_dsq_id = SCX_DSQ_LOCAL; 4096 } else { 4097 cpu = prev_cpu; 4098 } 4099 p->scx.selected_cpu = cpu; 4100 4101 return cpu; 4102 } 4103 } 4104 4105 static void task_woken_scx(struct rq *rq, struct task_struct *p) 4106 { 4107 run_deferred(rq); 4108 } 4109 4110 static void set_cpus_allowed_scx(struct task_struct *p, 4111 struct affinity_context *ac) 4112 { 4113 struct scx_sched *sch = scx_task_sched(p); 4114 4115 set_cpus_allowed_common(p, ac); 4116 4117 if (task_dead_and_done(p)) 4118 return; 4119 4120 /* 4121 * The effective cpumask is stored in @p->cpus_ptr which may temporarily 4122 * differ from the configured one in @p->cpus_mask. Always tell the bpf 4123 * scheduler the effective one. 4124 * 4125 * Fine-grained memory write control is enforced by BPF making the const 4126 * designation pointless. Cast it away when calling the operation. 4127 * 4128 * The cid form receives the initial mask when the task is enabled and 4129 * hears about changes only afterwards, see struct scx_enable_args. 4130 */ 4131 if (SCX_HAS_OP(sch, set_cpumask) && 4132 (!scx_is_cid_type() || scx_get_task_state(p) == SCX_TASK_ENABLED)) 4133 scx_call_op_set_cpumask(sch, task_rq(p), p, (struct cpumask *)p->cpus_ptr); 4134 } 4135 4136 static void handle_hotplug(struct rq *rq, bool online) 4137 { 4138 struct scx_sched *sch = scx_root_protected(); 4139 s32 cpu = cpu_of(rq); 4140 s32 cpu_or_cid = cpu; 4141 4142 atomic_long_inc(&scx_hotplug_seq); 4143 4144 /* 4145 * scx_root updates are protected by cpus_read_lock() and will stay 4146 * stable here. Note that we can't depend on scx_enabled() test as the 4147 * hotplug ops need to be enabled before __scx_enabled is set. 4148 */ 4149 if (unlikely(!sch)) 4150 return; 4151 4152 if (scx_enabled()) 4153 scx_idle_update_selcpu_topology(&sch->ops); 4154 4155 if (online) 4156 scx_online_ecaps(rq); 4157 else 4158 scx_offline_ecaps(rq); 4159 4160 /* 4161 * The tables can't be retired while this function is running as the 4162 * retirement is inside cpus_read_lock. However, scx_cpu_arg() is 4163 * awkward here as the tables can be NULL after root enable failure and 4164 * lockdep would trigger without surrounding rcu_read_lock(). Open code 4165 * the translation. If the table is NULL, the ops are also cleared and 4166 * @cpu_or_cid goes unused. 4167 */ 4168 if (scx_is_cid_type()) { 4169 s16 *tbl = rcu_dereference_check(scx_cpu_to_cid_tbl, 4170 lockdep_is_cpus_held()); 4171 4172 if (tbl) { 4173 struct scx_sched *pos; 4174 4175 cpu_or_cid = tbl[cpu]; 4176 4177 guard(raw_spinlock_irqsave)(&scx_sched_lock); 4178 list_for_each_entry(pos, &scx_sched_all, all) { 4179 struct scx_cmask *mask = pos->online_cmask; 4180 4181 if (mask) 4182 __assign_bit(cpu_or_cid, (unsigned long *)mask->bits, 4183 online); 4184 } 4185 } 4186 } 4187 4188 if (online && SCX_HAS_OP(sch, cpu_online)) 4189 SCX_CALL_OP(sch, cpu_online, NULL, cpu_or_cid); 4190 else if (!online && SCX_HAS_OP(sch, cpu_offline)) 4191 SCX_CALL_OP(sch, cpu_offline, NULL, cpu_or_cid); 4192 else 4193 scx_exit(sch, SCX_EXIT_UNREG_KERN, 4194 SCX_ECODE_ACT_RESTART | SCX_ECODE_RSN_HOTPLUG, 4195 "cpu %d going %s, exiting scheduler", cpu, 4196 online ? "online" : "offline"); 4197 } 4198 4199 void scx_rq_activate(struct rq *rq) 4200 { 4201 handle_hotplug(rq, true); 4202 } 4203 4204 void scx_rq_deactivate(struct rq *rq) 4205 { 4206 handle_hotplug(rq, false); 4207 } 4208 4209 static void rq_online_scx(struct rq *rq) 4210 { 4211 rq->scx.flags |= SCX_RQ_ONLINE; 4212 } 4213 4214 static void rq_offline_scx(struct rq *rq) 4215 { 4216 struct task_struct *p, *n; 4217 4218 rq->scx.flags &= ~SCX_RQ_ONLINE; 4219 4220 /* sched domain rebuilds call rq_offline with the CPU staying alive */ 4221 if (cpu_active(cpu_of(rq))) 4222 return; 4223 4224 scx_rescue_flush(rq); 4225 4226 /* 4227 * An offline CPU no longer calls ops.dispatch(). Re-enqueue its tasks 4228 * onto the local DSQ so that they run here and balance_push() moves 4229 * them off. 4230 */ 4231 list_for_each_entry_safe_reverse(p, n, &rq->scx.runnable_list, scx.runnable_node) { 4232 if (p->scx.dsq == &rq->scx.local_dsq) 4233 continue; 4234 guard(sched_change)(p, DEQUEUE_SAVE | DEQUEUE_MOVE | DEQUEUE_NOCLOCK); 4235 } 4236 } 4237 4238 static bool check_rq_for_timeouts(struct rq *rq) 4239 { 4240 struct scx_sched *sch; 4241 struct task_struct *p; 4242 struct rq_flags rf; 4243 bool timed_out = false; 4244 4245 rq_lock_irqsave(rq, &rf); 4246 sch = rcu_dereference_bh(scx_root); 4247 if (unlikely(!sch)) 4248 goto out_unlock; 4249 4250 list_for_each_entry(p, &rq->scx.runnable_list, scx.runnable_node) { 4251 struct scx_sched *sch = scx_task_sched(p); 4252 unsigned long last_runnable = p->scx.runnable_at; 4253 4254 if (unlikely(time_after(jiffies, 4255 last_runnable + READ_ONCE(sch->watchdog_timeout)))) { 4256 struct scx_dispatch_q *dsq = READ_ONCE(p->scx.dsq); 4257 u32 dur_ms = jiffies_to_msecs(jiffies - last_runnable); 4258 4259 /* 4260 * A task can be stuck on a DSQ that a sched other than 4261 * its owner is responsible for draining, e.g. an 4262 * ancestor's bypass DSQ while the owner is bypassing. 4263 * Blame the drainer. The local DSQ is consumed by the 4264 * cpu itself and keeps blame on the owner. 4265 */ 4266 if (dsq && dsq->sched && dsq->id != SCX_DSQ_LOCAL) 4267 sch = dsq->sched; 4268 4269 __scx_exit(sch, SCX_EXIT_ERROR_STALL, 0, cpu_of(rq), 4270 "%s[%d] failed to run for %u.%03us", 4271 p->comm, p->pid, dur_ms / 1000, 4272 dur_ms % 1000); 4273 timed_out = true; 4274 break; 4275 } 4276 } 4277 out_unlock: 4278 rq_unlock_irqrestore(rq, &rf); 4279 return timed_out; 4280 } 4281 4282 static void scx_watchdog_workfn(struct work_struct *work) 4283 { 4284 unsigned long intv; 4285 int cpu; 4286 4287 WRITE_ONCE(scx_watchdog_timestamp, jiffies); 4288 4289 for_each_online_cpu(cpu) { 4290 if (unlikely(check_rq_for_timeouts(cpu_rq(cpu)))) 4291 break; 4292 4293 cond_resched(); 4294 } 4295 4296 intv = READ_ONCE(scx_watchdog_interval); 4297 if (intv < ULONG_MAX) 4298 queue_delayed_work(system_dfl_wq, to_delayed_work(work), intv); 4299 } 4300 4301 void scx_tick(struct rq *rq) 4302 { 4303 struct scx_sched *root; 4304 unsigned long last_check; 4305 4306 if (!scx_enabled()) 4307 return; 4308 4309 root = rcu_dereference_bh(scx_root); 4310 if (unlikely(!root)) 4311 return; 4312 4313 last_check = READ_ONCE(scx_watchdog_timestamp); 4314 if (unlikely(time_after(jiffies, 4315 last_check + READ_ONCE(root->watchdog_timeout)))) { 4316 u32 dur_ms = jiffies_to_msecs(jiffies - last_check); 4317 4318 scx_exit(root, SCX_EXIT_ERROR_STALL, 0, 4319 "watchdog failed to check in for %u.%03us", 4320 dur_ms / 1000, dur_ms % 1000); 4321 } 4322 4323 update_other_load_avgs(rq); 4324 } 4325 4326 static void task_tick_scx(struct rq *rq, struct task_struct *donor, int queued) 4327 { 4328 struct scx_sched *sch = scx_task_sched(donor); 4329 4330 update_curr_scx(rq); 4331 4332 /* 4333 * While disabling, always resched as we can't trust the slice 4334 * management. 4335 */ 4336 if (scx_bypassing(sch, cpu_of(rq))) 4337 scx_set_task_slice(donor, 0); 4338 else if (SCX_HAS_OP(sch, tick)) 4339 SCX_CALL_OP_TASK(sch, tick, rq, donor); 4340 4341 if (!donor->scx.slice) { 4342 /* the slice can't be trusted while bypassing */ 4343 if (READ_ONCE(donor->scx.lazy_resched) && 4344 !scx_bypassing(sch, cpu_of(rq))) 4345 scx_resched_curr_lazy(rq); 4346 else 4347 resched_curr(rq); 4348 } 4349 } 4350 4351 #ifdef CONFIG_EXT_GROUP_SCHED 4352 static struct cgroup *tg_cgrp(struct task_group *tg) 4353 { 4354 /* 4355 * If CGROUP_SCHED is disabled, @tg is NULL. If @tg is an autogroup, 4356 * @tg->css.cgroup is NULL. In both cases, @tg can be treated as the 4357 * root cgroup. 4358 */ 4359 if (tg && tg->css.cgroup) 4360 return tg->css.cgroup; 4361 else 4362 return &cgrp_dfl_root.cgrp; 4363 } 4364 4365 #define SCX_INIT_TASK_ARGS_CGROUP(cgrp) .cgroup = (cgrp), 4366 4367 #else /* CONFIG_EXT_GROUP_SCHED */ 4368 4369 #define SCX_INIT_TASK_ARGS_CGROUP(cgrp) 4370 4371 #endif /* CONFIG_EXT_GROUP_SCHED */ 4372 4373 /** 4374 * __scx_init_task - Initialize a task for a sched 4375 * @sch: sched to initialize @p for 4376 * @p: task of interest 4377 * @cgrp: cgroup @p is joining, %NULL for @p's current task_group's cgroup 4378 * @fork: %true if @p is being forked 4379 * 4380 * Pre-commit cgroup migration passes @cgrp explicitly as @p's task_group 4381 * still reflects the source. 4382 * 4383 * Return 0 on success, -errno on failure. 4384 */ 4385 int __scx_init_task(struct scx_sched *sch, struct task_struct *p, 4386 struct cgroup *cgrp, bool fork) 4387 { 4388 int ret; 4389 4390 p->scx.disallow = false; 4391 4392 if (SCX_HAS_OP(sch, init_task)) { 4393 struct scx_init_task_args args = { 4394 SCX_INIT_TASK_ARGS_CGROUP(cgrp ?: tg_cgrp(task_group(p))) 4395 .fork = fork, 4396 }; 4397 4398 ret = SCX_CALL_OP_RET(sch, init_task, NULL, p, &args); 4399 if (unlikely(ret)) { 4400 ret = scx_ops_sanitize_err(sch, "init_task", ret); 4401 return ret; 4402 } 4403 } 4404 4405 if (p->scx.disallow) { 4406 if (unlikely(scx_parent(sch))) { 4407 scx_error(sch, "non-root ops.init_task() set task->scx.disallow for %s[%d]", 4408 p->comm, p->pid); 4409 } else if (unlikely(fork)) { 4410 scx_error(sch, "ops.init_task() set task->scx.disallow for %s[%d] during fork", 4411 p->comm, p->pid); 4412 } else if (unlikely(scx_enable_state() != SCX_ENABLING)) { 4413 scx_error(sch, "ops.init_task() set task->scx.disallow for %s[%d] outside the enable path", 4414 p->comm, p->pid); 4415 } else { 4416 struct rq *rq; 4417 struct rq_flags rf; 4418 4419 rq = task_rq_lock(p, &rf); 4420 4421 /* 4422 * We're in the load path and @p->policy will be applied 4423 * right after. Reverting @p->policy here and rejecting 4424 * %SCHED_EXT transitions from scx_check_setscheduler() 4425 * guarantees that if ops.init_task() sets @p->disallow, 4426 * @p can never be in SCX. 4427 */ 4428 if (p->policy == SCHED_EXT) { 4429 p->policy = SCHED_NORMAL; 4430 atomic_long_inc(&scx_nr_rejected); 4431 } 4432 4433 task_rq_unlock(rq, p, &rf); 4434 } 4435 } 4436 4437 return 0; 4438 } 4439 4440 static void __scx_enable_task(struct scx_sched *sch, struct task_struct *p) 4441 { 4442 struct rq *rq = task_rq(p); 4443 u32 weight; 4444 4445 lockdep_assert_rq_held(rq); 4446 4447 /* 4448 * Verify the task is not in BPF scheduler's custody. If flag 4449 * transitions are consistent, the flag should always be clear 4450 * here. 4451 */ 4452 WARN_ON_ONCE(p->scx.flags & SCX_TASK_IN_CUSTODY); 4453 4454 /* 4455 * Set the weight before calling ops.enable() so that the scheduler 4456 * doesn't see a stale value if they inspect the task struct. 4457 */ 4458 if (task_has_idle_policy(p)) 4459 weight = WEIGHT_IDLEPRIO; 4460 else 4461 weight = sched_prio_to_weight[p->static_prio - MAX_RT_PRIO]; 4462 4463 p->scx.weight = sched_weight_to_cgroup(weight); 4464 p->scx.lazy_resched = sch->ops.flags & SCX_OPS_LAZY_RESCHED; 4465 4466 if (SCX_HAS_OP(sch, enable)) { 4467 if (scx_is_cid_type()) { 4468 struct scx_cmask *cmask = scx_fill_cmask_scratch(sch, p->cpus_ptr); 4469 struct scx_enable_args args = { 4470 .cmask_arena_addr = scx_kaddr_to_arena(sch, cmask), 4471 }; 4472 4473 SCX_CALL_CID_OP_TASK(sch, enable, rq, p, &args); 4474 } else { 4475 SCX_CALL_OP_TASK(sch, enable, rq, p); 4476 } 4477 } 4478 4479 /* 4480 * The initial mask also goes out through set_cmask() so a scheduler can 4481 * track affinity there alone, and before set_weight() so that the mask 4482 * is in place when weight-dependent state is derived, see struct 4483 * scx_enable_args. 4484 */ 4485 if (scx_is_cid_type() && SCX_HAS_OP(sch, set_cpumask)) 4486 scx_call_op_set_cpumask(sch, rq, p, p->cpus_ptr); 4487 4488 if (SCX_HAS_OP(sch, set_weight)) 4489 SCX_CALL_OP_TASK(sch, set_weight, rq, p, p->scx.weight); 4490 } 4491 4492 void scx_enable_task(struct scx_sched *sch, struct task_struct *p) 4493 { 4494 __scx_enable_task(sch, p); 4495 scx_set_task_state(p, SCX_TASK_ENABLED); 4496 } 4497 4498 static void scx_disable_task(struct scx_sched *sch, struct task_struct *p) 4499 { 4500 struct rq *rq = task_rq(p); 4501 4502 lockdep_assert_rq_held(rq); 4503 WARN_ON_ONCE(scx_get_task_state(p) != SCX_TASK_ENABLED); 4504 4505 clear_direct_dispatch(p); 4506 4507 if (SCX_HAS_OP(sch, disable)) 4508 SCX_CALL_OP_TASK(sch, disable, rq, p); 4509 scx_set_task_state(p, SCX_TASK_READY); 4510 4511 /* 4512 * Reset the SCX-managed fields when @p leaves the BPF scheduler's 4513 * control, after ops.disable() has observed their final values. 4514 */ 4515 p->scx.dsq_vtime = 0; 4516 scx_task_slice_ended(rq, p); 4517 scx_set_task_slice(p, 0); 4518 p->scx.reenq_cnt = 0; 4519 4520 /* 4521 * Verify the task is not in BPF scheduler's custody. If flag 4522 * transitions are consistent, the flag should always be clear 4523 * here. 4524 */ 4525 WARN_ON_ONCE(p->scx.flags & SCX_TASK_IN_CUSTODY); 4526 } 4527 4528 void __scx_disable_and_exit_task(struct scx_sched *sch, struct task_struct *p) 4529 { 4530 struct scx_exit_task_args args = { 4531 .cancelled = false, 4532 }; 4533 4534 lockdep_assert_held(&p->pi_lock); 4535 lockdep_assert_rq_held(task_rq(p)); 4536 4537 switch (scx_get_task_state(p)) { 4538 case SCX_TASK_NONE: 4539 return; 4540 case SCX_TASK_INIT: 4541 args.cancelled = true; 4542 break; 4543 case SCX_TASK_READY: 4544 break; 4545 case SCX_TASK_ENABLED: 4546 scx_disable_task(sch, p); 4547 break; 4548 default: 4549 WARN_ON_ONCE(true); 4550 return; 4551 } 4552 4553 if (SCX_HAS_OP(sch, exit_task)) 4554 SCX_CALL_OP_TASK(sch, exit_task, task_rq(p), p, &args); 4555 } 4556 4557 /* 4558 * Undo a completed __scx_init_task(sch, p, false) when scx_enable_task() never 4559 * ran. The task state has not been transitioned, so this mirrors the 4560 * SCX_TASK_INIT branch in __scx_disable_and_exit_task(). 4561 */ 4562 void scx_sub_init_cancel_task(struct scx_sched *sch, struct task_struct *p) 4563 { 4564 struct scx_exit_task_args args = { .cancelled = true }; 4565 4566 lockdep_assert_held(&p->pi_lock); 4567 lockdep_assert_rq_held(task_rq(p)); 4568 4569 /* @p was never associated with @sch, dispatch on the explicit @sch */ 4570 if (SCX_HAS_OP(sch, exit_task)) 4571 __SCX_CALL_OP_TASK(sch, ops, exit_task, task_rq(p), p, &args); 4572 } 4573 4574 void scx_disable_and_exit_task(struct scx_sched *sch, struct task_struct *p) 4575 { 4576 __scx_disable_and_exit_task(sch, p); 4577 4578 /* 4579 * If set, @p exited between __scx_init_task() and scx_enable_task() in 4580 * scx_sub_enable() and is initialized for both the associated sched and 4581 * its parent. Exit for the child too - scx_enable_task() never ran for 4582 * it, so undo only init_task. The flag is only set on the sub-enable 4583 * path, so it's always clear when @p arrives here in %SCX_TASK_NONE. 4584 */ 4585 if (p->scx.flags & SCX_TASK_SUB_INIT) { 4586 if (!WARN_ON_ONCE(!scx_enabling_sub_sched)) 4587 scx_sub_init_cancel_task(scx_enabling_sub_sched, p); 4588 p->scx.flags &= ~SCX_TASK_SUB_INIT; 4589 } 4590 4591 scx_set_task_sched(p, NULL); 4592 scx_set_task_state(p, SCX_TASK_NONE); 4593 } 4594 4595 void init_scx_entity(struct sched_ext_entity *scx) 4596 { 4597 memset(scx, 0, sizeof(*scx)); 4598 INIT_LIST_HEAD(&scx->dsq_list.node); 4599 RB_CLEAR_NODE(&scx->dsq_priq); 4600 scx->sticky_cpu = -1; 4601 scx->holding_cpu = -1; 4602 scx->runnable_cpu = -1; 4603 INIT_LIST_HEAD(&scx->runnable_node); 4604 scx->runnable_at = jiffies; 4605 scx->ddsp_dsq_id = SCX_DSQ_INVALID; 4606 scx->slice = SCX_SLICE_DFL; 4607 } 4608 4609 /* See scx_tid_alloc / scx_tid_cursor. */ 4610 static u64 scx_alloc_tid(void) 4611 { 4612 struct scx_tid_alloc *ta; 4613 4614 guard(preempt)(); 4615 ta = this_cpu_ptr(&scx_tid_alloc); 4616 4617 if (unlikely(ta->next >= ta->end)) { 4618 ta->next = atomic64_fetch_add(SCX_TID_CHUNK, &scx_tid_cursor); 4619 ta->end = ta->next + SCX_TID_CHUNK; 4620 } 4621 return ta->next++; 4622 } 4623 4624 static void scx_tid_hash_insert(struct task_struct *p) 4625 { 4626 int ret; 4627 4628 lockdep_assert_held(&scx_tasks_lock); 4629 4630 ret = rhashtable_lookup_insert_fast(&scx_tid_hash, 4631 &p->scx.tid_hash_node, 4632 scx_tid_hash_params); 4633 WARN_ON_ONCE(ret); 4634 } 4635 4636 void scx_pre_fork(struct task_struct *p) 4637 { 4638 /* 4639 * BPF scheduler enable/disable paths want to be able to iterate and 4640 * update all tasks which can become complex when racing forks. As 4641 * enable/disable are very cold paths, let's use a percpu_rwsem to 4642 * exclude forks. 4643 */ 4644 percpu_down_read(&scx_fork_rwsem); 4645 } 4646 4647 int scx_fork(struct task_struct *p, struct kernel_clone_args *kargs) 4648 { 4649 s32 ret; 4650 4651 percpu_rwsem_assert_held(&scx_fork_rwsem); 4652 4653 p->scx.tid = scx_alloc_tid(); 4654 4655 if (scx_init_task_enabled) { 4656 #ifdef CONFIG_EXT_SUB_SCHED 4657 struct scx_sched *sch = scx_cgroup_sched(kargs->cset->dfl_cgrp); 4658 #else 4659 struct scx_sched *sch = scx_root_protected_live(); 4660 #endif 4661 scx_set_task_state(p, SCX_TASK_INIT_BEGIN); 4662 ret = __scx_init_task(sch, p, NULL, true); 4663 if (unlikely(ret)) { 4664 scx_set_task_state(p, SCX_TASK_NONE); 4665 return ret; 4666 } 4667 scx_set_task_state(p, SCX_TASK_INIT); 4668 scx_set_task_sched(p, sch); 4669 } 4670 4671 return 0; 4672 } 4673 4674 void scx_post_fork(struct task_struct *p) 4675 { 4676 if (scx_init_task_enabled) { 4677 scx_set_task_state(p, SCX_TASK_READY); 4678 4679 /* 4680 * Enable the task immediately if it's running on sched_ext. 4681 * Otherwise, it'll be enabled in switching_to_scx() if and 4682 * when it's ever configured to run with a SCHED_EXT policy. 4683 */ 4684 if (p->sched_class == &ext_sched_class) { 4685 struct rq_flags rf; 4686 struct rq *rq; 4687 4688 rq = task_rq_lock(p, &rf); 4689 scx_enable_task(scx_task_sched(p), p); 4690 task_rq_unlock(rq, p, &rf); 4691 } 4692 } 4693 4694 scoped_guard(raw_spinlock_irq, &scx_tasks_lock) { 4695 list_add_tail(&p->scx.tasks_node, &scx_tasks); 4696 if (scx_tid_to_task_enabled()) 4697 scx_tid_hash_insert(p); 4698 } 4699 4700 percpu_up_read(&scx_fork_rwsem); 4701 } 4702 4703 void scx_cancel_fork(struct task_struct *p) 4704 { 4705 if (scx_init_task_enabled) { 4706 struct rq *rq; 4707 struct rq_flags rf; 4708 4709 rq = task_rq_lock(p, &rf); 4710 WARN_ON_ONCE(scx_get_task_state(p) >= SCX_TASK_READY); 4711 scx_disable_and_exit_task(scx_task_sched(p), p); 4712 task_rq_unlock(rq, p, &rf); 4713 } 4714 4715 percpu_up_read(&scx_fork_rwsem); 4716 } 4717 4718 /** 4719 * task_dead_and_done - Is a task dead and done running? 4720 * @p: target task 4721 * 4722 * Once sched_ext_dead() removes the dead task from scx_tasks and exits it, the 4723 * task no longer exists from SCX's POV. However, certain sched_class ops may be 4724 * invoked on these dead tasks leading to failures - e.g. sched_setscheduler() 4725 * may try to switch a task which finished sched_ext_dead() back into SCX 4726 * triggering invalid SCX task state transitions and worse. 4727 * 4728 * Once a task has finished the final switch, sched_ext_dead() is the only thing 4729 * that needs to happen on the task. Use this test to short-circuit sched_class 4730 * operations which may be called on dead tasks. 4731 */ 4732 static bool task_dead_and_done(struct task_struct *p) 4733 { 4734 struct rq *rq = task_rq(p); 4735 4736 lockdep_assert_rq_held(rq); 4737 4738 /* 4739 * In do_task_dead(), a dying task sets %TASK_DEAD with preemption 4740 * disabled and __schedule(). If @p has %TASK_DEAD set and off CPU, @p 4741 * won't ever run again. 4742 */ 4743 return unlikely(READ_ONCE(p->__state) == TASK_DEAD) && 4744 !task_on_cpu(rq, p); 4745 } 4746 4747 void sched_ext_dead(struct task_struct *p) 4748 { 4749 /* 4750 * By the time control reaches here, @p has %TASK_DEAD set, switched out 4751 * for the last time and then dropped the rq lock - task_dead_and_done() 4752 * should be returning %true nullifying the straggling sched_class ops. 4753 * Remove from scx_tasks and exit @p. 4754 */ 4755 scoped_guard(raw_spinlock_irqsave, &scx_tasks_lock) { 4756 list_del_init(&p->scx.tasks_node); 4757 if (scx_tid_to_task_enabled()) 4758 rhashtable_remove_fast(&scx_tid_hash, 4759 &p->scx.tid_hash_node, 4760 scx_tid_hash_params); 4761 } 4762 4763 /* 4764 * @p is off scx_tasks and wholly ours. scx_root_enable()'s READY -> 4765 * ENABLED transitions can't race us. Disable ops for @p. 4766 * 4767 * %SCX_TASK_DEAD synchronizes against cgroup task iteration - see 4768 * scx_task_iter_next_locked(). NONE tasks need no marking: cgroup 4769 * iteration is only used from sub-sched paths, which require root 4770 * enabled. Root enable transitions every live task to at least READY. 4771 * 4772 * %INIT_BEGIN means ops.init_task() is running for @p. Don't call 4773 * into ops; transition to %DEAD so the post-init recheck unwinds 4774 * via scx_sub_init_cancel_task(). 4775 */ 4776 if (scx_get_task_state(p) != SCX_TASK_NONE) { 4777 struct rq_flags rf; 4778 struct rq *rq; 4779 4780 rq = task_rq_lock(p, &rf); 4781 if (scx_get_task_state(p) != SCX_TASK_INIT_BEGIN) 4782 scx_disable_and_exit_task(scx_task_sched(p), p); 4783 scx_set_task_state(p, SCX_TASK_DEAD); 4784 task_rq_unlock(rq, p, &rf); 4785 } 4786 } 4787 4788 static void reweight_task_scx(struct rq *rq, struct task_struct *p, 4789 const struct load_weight *lw) 4790 { 4791 struct scx_sched *sch = scx_task_sched(p); 4792 4793 lockdep_assert_rq_held(task_rq(p)); 4794 4795 if (task_dead_and_done(p)) 4796 return; 4797 4798 /* 4799 * When switching sched_class away from SCX, reweight_task_scx() 4800 * is called _after_ scx_disable_task(). Skip calling ops.set_weight() 4801 * since the BPF scheduler may have already forgotten the task in 4802 * ops.disable(). 4803 * p->scx.weight will be recalculated in scx_enable_task() if the task 4804 * ever returns to SCX class. 4805 */ 4806 if (scx_get_task_state(p) != SCX_TASK_ENABLED) 4807 return; 4808 4809 p->scx.weight = sched_weight_to_cgroup(scale_load_down(lw->weight)); 4810 if (SCX_HAS_OP(sch, set_weight)) 4811 SCX_CALL_OP_TASK(sch, set_weight, rq, p, p->scx.weight); 4812 } 4813 4814 static void prio_changed_scx(struct rq *rq, struct task_struct *p, u64 oldprio) 4815 { 4816 } 4817 4818 static void switching_to_scx(struct rq *rq, struct task_struct *p) 4819 { 4820 struct scx_sched *sch = scx_task_sched(p); 4821 4822 if (task_dead_and_done(p)) 4823 return; 4824 4825 scx_enable_task(sch, p); 4826 4827 /* 4828 * set_cpus_allowed_scx() is not called while @p is associated with a 4829 * different scheduler class. Keep the BPF scheduler up-to-date. The cid 4830 * form gets its mask from scx_enable_task(). 4831 */ 4832 if (!scx_is_cid_type() && SCX_HAS_OP(sch, set_cpumask)) 4833 scx_call_op_set_cpumask(sch, rq, p, (struct cpumask *)p->cpus_ptr); 4834 } 4835 4836 static void switched_from_scx(struct rq *rq, struct task_struct *p) 4837 { 4838 /* 4839 * A class change of the running task: sched_change_begin() put @p with 4840 * no successor, which leaves rq->scx.sched set. 4841 */ 4842 if (task_current_donor(rq, p)) 4843 scx_cid_sched_update(rq, NULL); 4844 4845 if (task_dead_and_done(p)) 4846 return; 4847 4848 /* 4849 * %NONE means SCX is no longer tracking @p at the task level (e.g. 4850 * scx_fail_parent() handed @p back to the parent at NONE pending the 4851 * parent's own teardown). There is nothing to disable; calling 4852 * scx_disable_task() would WARN on the non-%ENABLED state and trigger a 4853 * NONE -> READY validation failure. 4854 */ 4855 if (scx_get_task_state(p) == SCX_TASK_NONE) 4856 return; 4857 4858 scx_disable_task(scx_task_sched(p), p); 4859 } 4860 4861 static void switched_to_scx(struct rq *rq, struct task_struct *p) {} 4862 4863 int scx_check_setscheduler(struct task_struct *p, int policy) 4864 { 4865 lockdep_assert_rq_held(task_rq(p)); 4866 4867 /* If disallow, reject transitioning into SCX. */ 4868 if (scx_enabled() && READ_ONCE(p->scx.disallow) && 4869 p->policy != policy && policy == SCHED_EXT) 4870 return -EACCES; 4871 4872 return 0; 4873 } 4874 4875 /* 4876 * Don't carry a donor retained by another class into sched_ext. The caller 4877 * has updated the rq clock and invokes this immediately before 4878 * sched_change_begin() records the task's queued state. 4879 */ 4880 void scx_prepare_setscheduler(struct task_struct *p, int policy) 4881 { 4882 lockdep_assert_held(&p->pi_lock); 4883 lockdep_assert_rq_held(task_rq(p)); 4884 4885 if (scx_enabled() && p->policy != policy && policy == SCHED_EXT) 4886 scx_block_proxy_donor(task_rq(p), p); 4887 } 4888 4889 static void process_ddsp_deferred_locals(struct rq *rq) 4890 { 4891 struct task_struct *p; 4892 4893 lockdep_assert_rq_held(rq); 4894 4895 /* 4896 * Now that @rq can be unlocked, execute the deferred enqueueing of 4897 * tasks directly dispatched to the local DSQs of other CPUs. See 4898 * direct_dispatch(). Keep popping from the head instead of using 4899 * list_for_each_entry_safe() as dispatch_local_dsq() may unlock @rq 4900 * temporarily. 4901 */ 4902 while ((p = list_first_entry_or_null(&rq->scx.ddsp_deferred_locals, 4903 struct task_struct, scx.dsq_list.node))) { 4904 struct scx_sched *sch = scx_task_sched(p); 4905 struct scx_dispatch_q *dsq; 4906 u64 dsq_id = p->scx.ddsp_dsq_id; 4907 u64 enq_flags = p->scx.ddsp_enq_flags; 4908 u64 slice = p->scx.ddsp_slice; 4909 u64 vtime = p->scx.ddsp_vtime; 4910 4911 list_del_init(&p->scx.dsq_list.node); 4912 clear_direct_dispatch(p); 4913 4914 dsq = find_dsq_for_dispatch(sch, rq, dsq_id, task_cpu(p)); 4915 if (!WARN_ON_ONCE(dsq->id != SCX_DSQ_LOCAL)) 4916 dispatch_to_local_dsq(sch, rq, dsq, p, slice, vtime, enq_flags); 4917 } 4918 } 4919 4920 /* 4921 * Determine whether @p should be reenqueued from a local DSQ. 4922 * 4923 * @reenq_flags is mutable and accumulates state across the DSQ walk: 4924 * 4925 * - %SCX_REENQ_TSR_NOT_FIRST: Set after the first task is visited. "First" 4926 * tracks position in the DSQ list, not among IMMED tasks. A non-IMMED task at 4927 * the head consumes the first slot. 4928 * 4929 * - %SCX_REENQ_TSR_RQ_OPEN: Set by reenq_local() before the walk if 4930 * rq_is_open() is true. 4931 * 4932 * An IMMED task is kept (returns %false) only if it's the first task in the DSQ 4933 * AND the current task is done — i.e. it will execute immediately. All other 4934 * IMMED tasks are reenqueued. This means if a non-IMMED task sits at the head, 4935 * every IMMED task behind it gets reenqueued. 4936 * 4937 * Reenqueued tasks go through ops.enqueue() with %SCX_ENQ_REENQ | 4938 * %SCX_TASK_REENQ_IMMED. If the BPF scheduler dispatches back to the same local 4939 * DSQ with %SCX_ENQ_IMMED while the CPU is still unavailable, this triggers 4940 * another reenq cycle. Repetitions are bounded by %SCX_REENQ_MAX_REPEAT in 4941 * scx_do_enqueue_task(), which ejects the task's owning scheduler. 4942 */ 4943 static bool local_task_should_reenq(struct rq *rq, struct task_struct *p, 4944 u64 *reenq_flags, u32 *reason) 4945 { 4946 bool first; 4947 4948 first = !(*reenq_flags & SCX_REENQ_TSR_NOT_FIRST); 4949 *reenq_flags |= SCX_REENQ_TSR_NOT_FIRST; 4950 4951 if (unlikely((p->scx.flags & SCX_TASK_PROTECTED) || p == scx_rescuee(rq))) 4952 return false; 4953 4954 *reason = SCX_TASK_REENQ_KFUNC; 4955 4956 if ((p->scx.flags & SCX_TASK_IMMED) && 4957 (!first || !(*reenq_flags & SCX_REENQ_TSR_RQ_OPEN))) { 4958 __scx_add_event(scx_task_sched(p), SCX_EV_REENQ_IMMED, 1); 4959 *reason = SCX_TASK_REENQ_IMMED; 4960 return true; 4961 } 4962 4963 if ((*reenq_flags & SCX_REENQ_CAP_REVOKE) && 4964 scx_task_reenq_on_cap_revoke(rq, p)) { 4965 *reason = SCX_TASK_REENQ_CAP; 4966 return true; 4967 } 4968 4969 return *reenq_flags & SCX_REENQ_ANY; 4970 } 4971 4972 /* 4973 * The dispatcher runs ops.dequeue() and stores the final ops_state after 4974 * dropping the DSQ lock, so @p can be found on a DSQ while still 4975 * %SCX_OPSS_DISPATCHING. Wait for the dispatch to finish before operating on 4976 * @p. 4977 */ 4978 void scx_wait_dispatching(struct task_struct *p) 4979 { 4980 if (unlikely(atomic_long_read_acquire(&p->scx.ops_state) == SCX_OPSS_DISPATCHING)) 4981 wait_ops_state(p, SCX_OPSS_DISPATCHING); 4982 } 4983 4984 static u32 reenq_local(struct scx_sched *sch, struct rq *rq, u64 reenq_flags) 4985 { 4986 LIST_HEAD(tasks); 4987 u32 nr_enqueued = 0; 4988 struct task_struct *p, *n; 4989 4990 lockdep_assert_rq_held(rq); 4991 4992 if (WARN_ON_ONCE(reenq_flags & __SCX_REENQ_TSR_MASK)) 4993 reenq_flags &= ~__SCX_REENQ_TSR_MASK; 4994 if (rq_is_open(rq, 0)) 4995 reenq_flags |= SCX_REENQ_TSR_RQ_OPEN; 4996 4997 /* 4998 * The BPF scheduler may choose to dispatch tasks back to 4999 * @rq->scx.local_dsq. Move all candidate tasks off to a private list 5000 * first to avoid processing the same tasks repeatedly. 5001 */ 5002 list_for_each_entry_safe(p, n, &rq->scx.local_dsq.list, 5003 scx.dsq_list.node) { 5004 struct scx_sched *task_sch = scx_task_sched(p); 5005 u32 reason; 5006 5007 /* 5008 * If @p is being migrated, @p's current CPU may not agree with 5009 * its allowed CPUs and the migration_cpu_stop is about to 5010 * deactivate and re-activate @p anyway. Skip re-enqueueing. 5011 * 5012 * While racing sched property changes may also dequeue and 5013 * re-enqueue a migrating task while its current CPU and allowed 5014 * CPUs disagree, they use %ENQUEUE_RESTORE which is bypassed to 5015 * the current local DSQ for running tasks and thus are not 5016 * visible to the BPF scheduler. 5017 */ 5018 if (p->migration_pending) 5019 continue; 5020 5021 if (!scx_is_descendant(task_sch, sch)) 5022 continue; 5023 5024 if (!local_task_should_reenq(rq, p, &reenq_flags, &reason)) 5025 continue; 5026 5027 scx_wait_dispatching(p); 5028 scx_dispatch_dequeue(rq, p); 5029 5030 WARN_ON_ONCE(p->scx.flags & SCX_TASK_REENQ_REASON_MASK); 5031 p->scx.flags |= reason; 5032 5033 list_add_tail(&p->scx.dsq_list.node, &tasks); 5034 } 5035 5036 list_for_each_entry_safe(p, n, &tasks, scx.dsq_list.node) { 5037 list_del_init(&p->scx.dsq_list.node); 5038 5039 scx_do_enqueue_task(rq, p, SCX_ENQ_REENQ, -1); 5040 5041 nr_enqueued++; 5042 } 5043 5044 /* 5045 * The revoke that scheduled this scan may have raced the pick: donor 5046 * may be a now-capless task, either one that kept running or one 5047 * promoted off the local DSQ between the ecaps sync and this scan. 5048 * Zero the slice to evict it. The enqueue gate blocks new capless 5049 * inserts, so no later pick can slip through after the scan. 5050 */ 5051 if ((reenq_flags & SCX_REENQ_CAP_REVOKE) && 5052 rq->donor->sched_class == &ext_sched_class && 5053 scx_task_reenq_on_cap_revoke(rq, rq->donor)) { 5054 scx_set_task_slice(rq->donor, 0); 5055 resched_curr(rq); 5056 } 5057 5058 return nr_enqueued; 5059 } 5060 5061 static void process_deferred_reenq_locals(struct rq *rq) 5062 { 5063 lockdep_assert_rq_held(rq); 5064 5065 /* 5066 * A task can be re-queued within this loop when a reenqueued task 5067 * bounces straight back to the local DSQ. That recursion is bounded by 5068 * the per-task reenqueue cap in scx_do_enqueue_task(). 5069 */ 5070 while (true) { 5071 struct scx_sched *sch; 5072 u64 reenq_flags; 5073 5074 scoped_guard (raw_spinlock, &rq->scx.deferred_reenq_lock) { 5075 struct scx_deferred_reenq_local *drl = 5076 list_first_entry_or_null(&rq->scx.deferred_reenq_locals, 5077 struct scx_deferred_reenq_local, 5078 node); 5079 struct scx_sched_pcpu *sch_pcpu; 5080 5081 if (!drl) 5082 return; 5083 5084 sch_pcpu = container_of(drl, struct scx_sched_pcpu, 5085 deferred_reenq_local); 5086 sch = sch_pcpu->sch; 5087 5088 reenq_flags = drl->flags; 5089 WRITE_ONCE(drl->flags, 0); 5090 list_del_init(&drl->node); 5091 } 5092 5093 /* see schedule_dsq_reenq() */ 5094 smp_mb(); 5095 5096 reenq_local(sch, rq, reenq_flags); 5097 } 5098 } 5099 5100 static bool user_task_should_reenq(struct task_struct *p, u64 reenq_flags, u32 *reason) 5101 { 5102 *reason = SCX_TASK_REENQ_KFUNC; 5103 if (reenq_flags & SCX_REENQ_ANY) 5104 return true; 5105 return (reenq_flags & SCX_REENQ_MARKED) && (p->scx.dsq_flags & SCX_TASK_DSQ_REENQ); 5106 } 5107 5108 static void reenq_user(struct rq *rq, struct scx_dispatch_q *dsq, u64 reenq_flags) 5109 { 5110 struct rq *locked_rq = rq; 5111 struct scx_sched *sch = dsq->sched; 5112 struct scx_dsq_list_node cursor = INIT_DSQ_LIST_CURSOR(cursor, dsq, 0); 5113 struct task_struct *p; 5114 s32 nr_visited = 0; 5115 5116 lockdep_assert_rq_held(rq); 5117 5118 raw_spin_lock(&dsq->lock); 5119 5120 while (likely(!READ_ONCE(sch->bypass_depth))) { 5121 struct rq *task_rq; 5122 u32 reason; 5123 5124 /* 5125 * Count skipped tasks too so that a long walk doesn't hold the 5126 * locks throughout. The cursor keeps the position. 5127 */ 5128 if (!(++nr_visited % SCX_TASK_ITER_BATCH)) { 5129 raw_spin_unlock(&dsq->lock); 5130 if (locked_rq) { 5131 scx_rq_lock_drop(locked_rq); 5132 raw_spin_rq_unlock(locked_rq); 5133 locked_rq = NULL; 5134 } 5135 cpu_relax(); 5136 raw_spin_lock(&dsq->lock); 5137 } 5138 5139 p = nldsq_cursor_next_task(&cursor, dsq); 5140 if (!p) 5141 break; 5142 5143 if (!user_task_should_reenq(p, reenq_flags, &reason)) 5144 continue; 5145 5146 task_rq = task_rq(p); 5147 5148 if (locked_rq != task_rq) { 5149 if (locked_rq) { 5150 scx_rq_lock_drop(locked_rq); 5151 raw_spin_rq_unlock(locked_rq); 5152 } 5153 if (unlikely(!raw_spin_rq_trylock(task_rq))) { 5154 raw_spin_unlock(&dsq->lock); 5155 raw_spin_rq_lock(task_rq); 5156 raw_spin_lock(&dsq->lock); 5157 } 5158 locked_rq = task_rq; 5159 5160 /* did we lose @p while switching locks? */ 5161 if (nldsq_cursor_lost_task(&cursor, task_rq, dsq, p)) 5162 continue; 5163 } 5164 5165 /* @p is on @dsq, its rq and @dsq are locked */ 5166 scx_wait_dispatching(p); 5167 dispatch_dequeue_locked(p, dsq); 5168 raw_spin_unlock(&dsq->lock); 5169 5170 WARN_ON_ONCE(p->scx.flags & SCX_TASK_REENQ_REASON_MASK); 5171 p->scx.flags |= reason; 5172 5173 scx_do_enqueue_task(task_rq, p, SCX_ENQ_REENQ, -1); 5174 5175 raw_spin_lock(&dsq->lock); 5176 } 5177 5178 list_del_init(&cursor.node); 5179 raw_spin_unlock(&dsq->lock); 5180 5181 if (locked_rq != rq) { 5182 if (locked_rq) { 5183 scx_rq_lock_drop(locked_rq); 5184 raw_spin_rq_unlock(locked_rq); 5185 } 5186 raw_spin_rq_lock(rq); 5187 } 5188 } 5189 5190 static void process_deferred_reenq_users(struct rq *rq) 5191 { 5192 lockdep_assert_rq_held(rq); 5193 5194 while (true) { 5195 struct scx_dispatch_q *dsq; 5196 u64 dsq_id, reenq_flags; 5197 5198 scoped_guard (raw_spinlock, &rq->scx.deferred_reenq_lock) { 5199 struct scx_deferred_reenq_user *dru = 5200 list_first_entry_or_null(&rq->scx.deferred_reenq_users, 5201 struct scx_deferred_reenq_user, 5202 node); 5203 struct scx_dsq_pcpu *dsq_pcpu; 5204 5205 if (!dru) 5206 return; 5207 5208 dsq_pcpu = container_of(dru, struct scx_dsq_pcpu, 5209 deferred_reenq_user); 5210 dsq = dsq_pcpu->dsq; 5211 reenq_flags = dru->flags; 5212 WRITE_ONCE(dru->flags, 0); 5213 list_del_init(&dru->node); 5214 } 5215 5216 /* see schedule_dsq_reenq() */ 5217 smp_mb(); 5218 5219 /* destroy_dsq() may have raced and invalidated @dsq, nothing to reenq */ 5220 dsq_id = READ_ONCE(dsq->id); 5221 if (unlikely(dsq_id == SCX_DSQ_INVALID)) 5222 continue; 5223 5224 BUG_ON(dsq_id & SCX_DSQ_FLAG_BUILTIN); 5225 reenq_user(rq, dsq, reenq_flags); 5226 } 5227 } 5228 5229 /* 5230 * Drain ready tasks from @rq->scx.reject_dsq and reenqueue them so that their 5231 * owning BPF schedulers choose placement again. Proxy-active tasks remain 5232 * parked and rearm the retry notification for a later proxy resolution. 5233 * 5234 * A task can be re-rejected repeatedly. Reenqueues are bounded per task by 5235 * SCX_REENQ_MAX_REPEAT in scx_do_enqueue_task(), which ejects the owning 5236 * scheduler. 5237 */ 5238 static void scx_reenq_reject(struct rq *rq) 5239 { 5240 LIST_HEAD(tasks); 5241 struct task_struct *p, *n; 5242 5243 lockdep_assert_rq_held(rq); 5244 5245 if (list_empty(&rq->scx.reject_dsq.list)) 5246 return; 5247 5248 /* 5249 * Move ready tasks to a private list so a task re-rejected by 5250 * scx_do_enqueue_task() below isn't revisited this round. 5251 */ 5252 list_for_each_entry_safe(p, n, &rq->scx.reject_dsq.list, scx.dsq_list.node) { 5253 u32 reason = p->scx.flags & SCX_TASK_REENQ_REASON_MASK; 5254 5255 WARN_ON_ONCE(!reason); 5256 5257 if (sched_proxy_exec() && reason == SCX_TASK_REENQ_PROXY) { 5258 /* Affinity machinery will dequeue and reactivate @p. */ 5259 if (p->migration_pending) 5260 continue; 5261 5262 if (task_on_cpu(rq, p) || task_current_donor(rq, p)) { 5263 rq->scx.flags |= SCX_RQ_PROXY_RETRY; 5264 continue; 5265 } 5266 } else { 5267 WARN_ON_ONCE(p->migration_pending); 5268 } 5269 5270 scx_wait_dispatching(p); 5271 scx_dispatch_dequeue(rq, p); 5272 5273 list_add_tail(&p->scx.dsq_list.node, &tasks); 5274 } 5275 5276 list_for_each_entry_safe(p, n, &tasks, scx.dsq_list.node) { 5277 list_del_init(&p->scx.dsq_list.node); 5278 5279 scx_do_enqueue_task(rq, p, SCX_ENQ_REENQ, -1); 5280 } 5281 } 5282 5283 static void run_deferred(struct rq *rq) 5284 { 5285 process_ddsp_deferred_locals(rq); 5286 5287 if (!list_empty(&rq->scx.deferred_reenq_locals)) 5288 process_deferred_reenq_locals(rq); 5289 5290 if (!list_empty(&rq->scx.deferred_reenq_users)) 5291 process_deferred_reenq_users(rq); 5292 5293 scx_reenq_reject(rq); 5294 } 5295 5296 #ifdef CONFIG_NO_HZ_FULL 5297 bool scx_can_stop_tick(struct rq *rq) 5298 { 5299 struct task_struct *p = rq->donor; 5300 struct scx_sched *sch = scx_task_sched(p); 5301 5302 /* Proxy execution is conservatively tick-driven for now. */ 5303 if (rq->scx.flags & SCX_RQ_PROXY_TICK) 5304 return false; 5305 5306 if (p->sched_class != &ext_sched_class) 5307 return true; 5308 5309 /* 5310 * @rq->donor may still reference an outgoing EXT task after it has been 5311 * dequeued. If no EXT tasks are accounted on @rq, ignore its stale 5312 * slice state. If another task is dispatched from a DSQ, 5313 * set_next_task_scx() will update the dependency for the incoming task. 5314 */ 5315 if (!rq->scx.nr_running) 5316 return true; 5317 5318 if (scx_bypassing(sch, cpu_of(rq))) 5319 return false; 5320 5321 /* 5322 * A running rescuee's charging and expiry are tick-driven, see 5323 * scx_rescue_charge(). Keep the tick while rescue is in progress. 5324 */ 5325 if (unlikely(p == scx_rescuee(rq))) 5326 return false; 5327 5328 /* 5329 * @rq can dispatch from different DSQs, so we can't tell whether it 5330 * needs the tick or not by looking at nr_running. Allow stopping ticks 5331 * iff set_next_task_scx() determined that the selected scheduling context 5332 * can run tickless. 5333 */ 5334 return rq->scx.flags & SCX_RQ_CAN_STOP_TICK; 5335 } 5336 #endif 5337 5338 #ifdef CONFIG_EXT_GROUP_SCHED 5339 5340 DEFINE_STATIC_PERCPU_RWSEM(scx_cgroup_ops_rwsem); 5341 5342 void scx_tg_init(struct task_group *tg) 5343 { 5344 tg->scx.weight = CGROUP_WEIGHT_DFL; 5345 tg->scx.bw_period_us = default_bw_period_us(); 5346 tg->scx.bw_quota_us = RUNTIME_INF; 5347 tg->scx.sched_idle = false; 5348 } 5349 5350 /** 5351 * scx_tg_sched - Resolve a task_group's sched 5352 * @tg: task_group of interest 5353 * 5354 * Return the sched that @tg's ops.cgroup_init() succeeded on, %NULL if @tg 5355 * isn't inited. An autogroup tg has no cgroup of its own and resolves to the 5356 * root sched. 5357 * 5358 * When a child sched exits, its task_groups are moved to the parent and 5359 * re-inited on it. A failed re-init fails the parent in turn and leaves the 5360 * task_group without a sched it's inited on, resolving to %NULL. See 5361 * scx_cgroup_return_subtree(). 5362 * 5363 * Safe for callers read-locking the ops rwsem. tg->scx.sched rewrites 5364 * write-lock it, and tg on/offline can't overlap such callers as a css's files 5365 * are created after online and drained before offline. 5366 */ 5367 static struct scx_sched *scx_tg_sched(struct task_group *tg) 5368 { 5369 lockdep_assert(lockdep_is_held(&cgroup_mutex) || 5370 lockdep_is_held(&scx_cgroup_ops_rwsem)); 5371 5372 if (!tg->css.cgroup) 5373 tg = &root_task_group; 5374 /* INITED means ops.cgroup_init() succeeded on @tg->scx.sched */ 5375 return (tg->scx.flags & SCX_TG_INITED) ? tg->scx.sched : NULL; 5376 } 5377 5378 /** 5379 * scx_tg_knob_sched - Resolve the sched receiving a task_group's knob updates 5380 * @tg: task_group of interest 5381 * 5382 * Knobs of a cgroup belong to the parent. Deliver the set_* ops to the 5383 * parent task_group's sched, which equals @tg's own sched everywhere except 5384 * at a sub-scheduler attach point, where the sub's parent sched receives 5385 * them. 5386 * 5387 * Return %NULL if the parent task_group has no sched. That can happen when the 5388 * parent's ops.cgroup_init() fails while a sub-scheduler is being disabled. 5389 * 5390 * The callers sit in @tg's cgroup file writes holding the ops rwsem read 5391 * side. That extends scx_tg_sched()'s file-write argument to the parent's 5392 * sched read: a parent css outlives its children's files. 5393 */ 5394 static struct scx_sched *scx_tg_knob_sched(struct task_group *tg) 5395 { 5396 lockdep_assert(lockdep_is_held(&cgroup_mutex) || 5397 lockdep_is_held(&scx_cgroup_ops_rwsem)); 5398 5399 if (!tg->css.cgroup || !tg->css.parent) 5400 return scx_tg_sched(&root_task_group); 5401 return scx_tg_sched(css_tg(tg->css.parent)); 5402 } 5403 5404 int scx_tg_online(struct task_group *tg) 5405 { 5406 int ret = 0; 5407 5408 WARN_ON_ONCE(tg->scx.flags & (SCX_TG_ONLINE | SCX_TG_INITED)); 5409 5410 if (scx_cgroup_enabled) { 5411 struct scx_sched *sch; 5412 5413 /* 5414 * The cgroup lifetime notifier populates cgrp->scx_sched before 5415 * css_online, but only on the default hierarchy. Sub-scheds are 5416 * attached to the cgroup2 hierarchy, so a cgroup1 task_group 5417 * always belongs to the root sched. 5418 */ 5419 if (cgroup_on_dfl(tg->css.cgroup)) 5420 sch = scx_cgroup_sched(tg->css.cgroup); 5421 else 5422 sch = scx_tg_sched(&root_task_group); 5423 5424 if (SCX_HAS_OP(sch, cgroup_init)) { 5425 struct scx_cgroup_init_args args = 5426 { .weight = tg->scx.weight, 5427 .bw_period_us = tg->scx.bw_period_us, 5428 .bw_quota_us = tg->scx.bw_quota_us, 5429 .bw_burst_us = tg->scx.bw_burst_us, 5430 .sched_idle = tg->scx.sched_idle }; 5431 5432 ret = SCX_CALL_OP_RET(sch, cgroup_init, 5433 NULL, tg->css.cgroup, &args); 5434 if (ret) 5435 ret = scx_ops_sanitize_err(sch, "cgroup_init", ret); 5436 } 5437 if (ret == 0) { 5438 tg->scx.sched = sch; 5439 tg->scx.flags |= SCX_TG_ONLINE | SCX_TG_INITED; 5440 } 5441 } else { 5442 tg->scx.flags |= SCX_TG_ONLINE; 5443 } 5444 5445 return ret; 5446 } 5447 5448 void scx_tg_offline(struct task_group *tg) 5449 { 5450 struct scx_sched *sch = tg->scx.sched; 5451 5452 WARN_ON_ONCE(!(tg->scx.flags & SCX_TG_ONLINE)); 5453 5454 /* INITED implies non-NULL @sch, test before SCX_HAS_OP() derefs */ 5455 if (scx_cgroup_enabled && (tg->scx.flags & SCX_TG_INITED) && 5456 SCX_HAS_OP(sch, cgroup_exit)) 5457 SCX_CALL_OP(sch, cgroup_exit, NULL, tg->css.cgroup); 5458 tg->scx.sched = NULL; 5459 tg->scx.flags &= ~(SCX_TG_ONLINE | SCX_TG_INITED); 5460 } 5461 5462 /* 5463 * @p's sched for the cgroup migration paths. Stable as re-homes happen either 5464 * at CGROUP_TASK_MIGRATED of the same migration or under scx_cgroup_lock(), 5465 * both while holding cgroup_mutex. 5466 */ 5467 static struct scx_sched *scx_cgroup_task_sched(struct task_struct *p) 5468 { 5469 return rcu_dereference_protected(p->scx.sched, lockdep_is_held(&cgroup_mutex)); 5470 } 5471 5472 int scx_cgroup_can_attach(struct cgroup_taskset *tset) 5473 { 5474 struct cgroup_subsys_state *css; 5475 struct task_struct *p; 5476 int ret; 5477 5478 if (!scx_cgroup_enabled) 5479 return 0; 5480 5481 cgroup_taskset_for_each(p, css, tset) { 5482 struct scx_sched *sch = scx_cgroup_task_sched(p); 5483 struct cgroup *from = tg_cgrp(task_group(p)); 5484 struct cgroup *to = tg_cgrp(css_tg(css)); 5485 5486 WARN_ON_ONCE(p->scx.cgrp_moving_from); 5487 5488 /* 5489 * sched_move_task() omits identity migrations. Let's match the 5490 * behavior so that ops.cgroup_prep_move() and ops.cgroup_move() 5491 * always match one-to-one. 5492 */ 5493 if (from == to) 5494 continue; 5495 5496 /* 5497 * The cgroup_move ops are delivered to @p's sched, and only for 5498 * moves that don't re-home @p. A re-homing move changes the dfl 5499 * cgroup's sched and is reported through the 5500 * exit_task/init_task pair that the re-homing generates. 5501 */ 5502 if (!sch || sch != scx_cgroup_sched(task_css_set(p)->mg_dst_cset->dfl_cgrp)) 5503 continue; 5504 5505 if (SCX_HAS_OP(sch, cgroup_prep_move)) { 5506 ret = SCX_CALL_OP_RET(sch, cgroup_prep_move, NULL, 5507 p, from, css->cgroup); 5508 if (ret) { 5509 ret = scx_ops_sanitize_err(sch, "cgroup_prep_move", ret); 5510 goto err; 5511 } 5512 } 5513 5514 p->scx.cgrp_moving_from = from; 5515 } 5516 5517 return 0; 5518 5519 err: 5520 cgroup_taskset_for_each(p, css, tset) { 5521 struct scx_sched *sch = scx_cgroup_task_sched(p); 5522 5523 /* cgrp_moving_from implies non-NULL @sch, test it first */ 5524 if (p->scx.cgrp_moving_from && SCX_HAS_OP(sch, cgroup_cancel_move)) 5525 SCX_CALL_OP(sch, cgroup_cancel_move, NULL, 5526 p, p->scx.cgrp_moving_from, css->cgroup); 5527 p->scx.cgrp_moving_from = NULL; 5528 } 5529 5530 return ret; 5531 } 5532 5533 void scx_cgroup_move_task(struct task_struct *p) 5534 { 5535 struct scx_sched *sch; 5536 5537 if (!scx_cgroup_enabled) 5538 return; 5539 5540 /* 5541 * Migration keys off css rather than cgroup identity, so it can hand an 5542 * unchanged-cgroup task here with cgrp_moving_from NULL. Nothing to 5543 * report to the BPF scheduler then, so skip it and keep prep_move and 5544 * move paired. 5545 */ 5546 sch = scx_cgroup_task_sched(p); 5547 if (p->scx.cgrp_moving_from && SCX_HAS_OP(sch, cgroup_move)) 5548 SCX_CALL_OP_TASK(sch, cgroup_move, task_rq(p), 5549 p, p->scx.cgrp_moving_from, 5550 tg_cgrp(task_group(p))); 5551 p->scx.cgrp_moving_from = NULL; 5552 } 5553 5554 void scx_cgroup_cancel_attach(struct cgroup_taskset *tset) 5555 { 5556 struct cgroup_subsys_state *css; 5557 struct task_struct *p; 5558 5559 if (!scx_cgroup_enabled) 5560 return; 5561 5562 cgroup_taskset_for_each(p, css, tset) { 5563 struct scx_sched *sch = scx_cgroup_task_sched(p); 5564 5565 /* cgrp_moving_from implies non-NULL @sch, test it first */ 5566 if (p->scx.cgrp_moving_from && SCX_HAS_OP(sch, cgroup_cancel_move)) 5567 SCX_CALL_OP(sch, cgroup_cancel_move, NULL, 5568 p, p->scx.cgrp_moving_from, css->cgroup); 5569 p->scx.cgrp_moving_from = NULL; 5570 } 5571 } 5572 5573 void scx_group_set_weight(struct task_group *tg, unsigned long weight) 5574 { 5575 struct scx_sched *sch; 5576 5577 percpu_down_read(&scx_cgroup_ops_rwsem); 5578 sch = scx_tg_knob_sched(tg); 5579 5580 if (scx_cgroup_enabled && sch && SCX_HAS_OP(sch, cgroup_set_weight) && 5581 tg->scx.weight != weight) 5582 SCX_CALL_OP(sch, cgroup_set_weight, NULL, tg_cgrp(tg), weight); 5583 5584 tg->scx.weight = weight; 5585 5586 percpu_up_read(&scx_cgroup_ops_rwsem); 5587 } 5588 5589 void scx_group_set_idle(struct task_group *tg, bool idle) 5590 { 5591 struct scx_sched *sch; 5592 5593 percpu_down_read(&scx_cgroup_ops_rwsem); 5594 sch = scx_tg_knob_sched(tg); 5595 5596 if (scx_cgroup_enabled && sch && SCX_HAS_OP(sch, cgroup_set_idle) && 5597 tg->scx.sched_idle != idle) 5598 SCX_CALL_OP(sch, cgroup_set_idle, NULL, tg_cgrp(tg), idle); 5599 5600 /* Update the task group's idle state */ 5601 tg->scx.sched_idle = idle; 5602 5603 percpu_up_read(&scx_cgroup_ops_rwsem); 5604 } 5605 5606 void scx_group_set_bandwidth(struct task_group *tg, 5607 u64 period_us, u64 quota_us, u64 burst_us) 5608 { 5609 struct scx_sched *sch; 5610 5611 percpu_down_read(&scx_cgroup_ops_rwsem); 5612 sch = scx_tg_knob_sched(tg); 5613 5614 if (scx_cgroup_enabled && sch && SCX_HAS_OP(sch, cgroup_set_bandwidth) && 5615 (tg->scx.bw_period_us != period_us || 5616 tg->scx.bw_quota_us != quota_us || 5617 tg->scx.bw_burst_us != burst_us)) 5618 SCX_CALL_OP(sch, cgroup_set_bandwidth, NULL, 5619 tg_cgrp(tg), period_us, quota_us, burst_us); 5620 5621 tg->scx.bw_period_us = period_us; 5622 tg->scx.bw_quota_us = quota_us; 5623 tg->scx.bw_burst_us = burst_us; 5624 5625 percpu_up_read(&scx_cgroup_ops_rwsem); 5626 } 5627 #endif /* CONFIG_EXT_GROUP_SCHED */ 5628 5629 #if defined(CONFIG_EXT_GROUP_SCHED) || defined(CONFIG_EXT_SUB_SCHED) 5630 static struct cgroup *root_cgroup(void) 5631 { 5632 return &cgrp_dfl_root.cgrp; 5633 } 5634 5635 /* 5636 * cgroup_lock() must nest outside the rwsem write side: a writer waiting 5637 * for cgroup_mutex deadlocks with cgroup teardown, which holds it while 5638 * draining a set_* file write blocked on the rwsem behind the writer. 5639 */ 5640 void scx_cgroup_lock(void) 5641 { 5642 cgroup_lock(); 5643 #ifdef CONFIG_EXT_GROUP_SCHED 5644 percpu_down_write(&scx_cgroup_ops_rwsem); 5645 #endif 5646 } 5647 5648 void scx_cgroup_unlock(void) 5649 { 5650 #ifdef CONFIG_EXT_GROUP_SCHED 5651 percpu_up_write(&scx_cgroup_ops_rwsem); 5652 #endif 5653 cgroup_unlock(); 5654 } 5655 #else /* CONFIG_EXT_GROUP_SCHED || CONFIG_EXT_SUB_SCHED */ 5656 static inline struct cgroup *root_cgroup(void) { return NULL; } 5657 static inline void scx_cgroup_lock(void) {} 5658 static inline void scx_cgroup_unlock(void) {} 5659 #endif /* CONFIG_EXT_GROUP_SCHED || CONFIG_EXT_SUB_SCHED */ 5660 5661 /* 5662 * Omitted operations: 5663 * 5664 * - migrate_task_rq: Unnecessary as task to cpu mapping is transient. 5665 * 5666 * - task_fork/dead: We need fork/dead notifications for all tasks regardless of 5667 * their current sched_class. Call them directly from sched core instead. 5668 */ 5669 DEFINE_SCHED_CLASS(ext) = { 5670 .enqueue_task = enqueue_task_scx, 5671 .dequeue_task = dequeue_task_scx, 5672 .yield_task = yield_task_scx, 5673 .yield_to_task = yield_to_task_scx, 5674 5675 .wakeup_preempt = wakeup_preempt_scx, 5676 5677 .pick_task = pick_task_scx, 5678 5679 .put_prev_task = put_prev_task_scx, 5680 .set_next_task = set_next_task_scx, 5681 5682 .select_task_rq = select_task_rq_scx, 5683 .task_woken = task_woken_scx, 5684 .set_cpus_allowed = set_cpus_allowed_scx, 5685 5686 .rq_online = rq_online_scx, 5687 .rq_offline = rq_offline_scx, 5688 5689 .task_tick = task_tick_scx, 5690 5691 .switching_to = switching_to_scx, 5692 .switched_from = switched_from_scx, 5693 .switched_to = switched_to_scx, 5694 .reweight_task = reweight_task_scx, 5695 .prio_changed = prio_changed_scx, 5696 5697 .update_curr = update_curr_scx, 5698 5699 #ifdef CONFIG_UCLAMP_TASK 5700 .uclamp_enabled = 1, 5701 #endif 5702 }; 5703 5704 s32 scx_init_dsq(struct scx_dispatch_q *dsq, u64 dsq_id, struct scx_sched *sch) 5705 { 5706 s32 cpu; 5707 5708 memset(dsq, 0, sizeof(*dsq)); 5709 5710 raw_spin_lock_init(&dsq->lock); 5711 INIT_LIST_HEAD(&dsq->list); 5712 dsq->id = dsq_id; 5713 dsq->sched = sch; 5714 5715 /* per-DSQ deferred reenq state is only needed for user DSQs */ 5716 if (dsq_id & SCX_DSQ_FLAG_BUILTIN) 5717 return 0; 5718 5719 dsq->pcpu_user = alloc_percpu(struct scx_dsq_pcpu); 5720 if (!dsq->pcpu_user) 5721 return -ENOMEM; 5722 5723 for_each_possible_cpu(cpu) { 5724 struct scx_dsq_pcpu *pcpu = per_cpu_ptr(dsq->pcpu_user, cpu); 5725 5726 pcpu->dsq = dsq; 5727 INIT_LIST_HEAD(&pcpu->deferred_reenq_user.node); 5728 } 5729 5730 return 0; 5731 } 5732 5733 static void exit_dsq(struct scx_dispatch_q *dsq) 5734 { 5735 s32 cpu; 5736 5737 if (!dsq->pcpu_user) 5738 return; 5739 5740 for_each_possible_cpu(cpu) { 5741 struct scx_dsq_pcpu *pcpu = per_cpu_ptr(dsq->pcpu_user, cpu); 5742 struct scx_deferred_reenq_user *dru = &pcpu->deferred_reenq_user; 5743 struct rq *rq = cpu_rq(cpu); 5744 5745 /* 5746 * free_dsq_irq_workfn() cancelled the reenqs before the grace 5747 * period and schedule_dsq_reenq() queues nothing after that. 5748 */ 5749 if (WARN_ON_ONCE(!list_empty(&dru->node))) { 5750 guard(raw_spinlock_irqsave)(&rq->scx.deferred_reenq_lock); 5751 list_del_init(&dru->node); 5752 } 5753 } 5754 5755 free_percpu(dsq->pcpu_user); 5756 } 5757 5758 static void free_dsq_rcufn(struct rcu_head *rcu) 5759 { 5760 struct scx_dispatch_q *dsq = container_of(rcu, struct scx_dispatch_q, rcu); 5761 5762 exit_dsq(dsq); 5763 kfree(dsq); 5764 } 5765 5766 static void free_dsq_irq_workfn(struct irq_work *irq_work) 5767 { 5768 struct llist_node *to_free = llist_del_all(&dsqs_to_free); 5769 struct scx_dispatch_q *dsq, *tmp_dsq; 5770 5771 llist_for_each_entry_safe(dsq, tmp_dsq, to_free, free_node) { 5772 s32 cpu; 5773 5774 /* 5775 * Cancel pending reenqs. Only a run_deferred() that started 5776 * before the grace period can hold one, and it keeps IRQs off, 5777 * so the grace period waits for it. After this sweep, 5778 * schedule_dsq_reenq() sees the invalid id under the same lock 5779 * and queues nothing. 5780 */ 5781 for_each_possible_cpu(cpu) { 5782 struct scx_dsq_pcpu *pcpu = per_cpu_ptr(dsq->pcpu_user, cpu); 5783 struct rq *rq = cpu_rq(cpu); 5784 5785 guard(raw_spinlock_irqsave)(&rq->scx.deferred_reenq_lock); 5786 list_del_init(&pcpu->deferred_reenq_user.node); 5787 } 5788 5789 call_rcu(&dsq->rcu, free_dsq_rcufn); 5790 } 5791 } 5792 5793 static DEFINE_IRQ_WORK(free_dsq_irq_work, free_dsq_irq_workfn); 5794 5795 static void destroy_dsq(struct scx_sched *sch, u64 dsq_id) 5796 { 5797 struct scx_dispatch_q *dsq; 5798 unsigned long flags; 5799 5800 rcu_read_lock(); 5801 5802 dsq = find_user_dsq(sch, dsq_id); 5803 if (!dsq) 5804 goto out_unlock_rcu; 5805 5806 raw_spin_lock_irqsave(&dsq->lock, flags); 5807 5808 if (dsq->nr) { 5809 scx_error(sch, "attempting to destroy in-use dsq 0x%016llx (nr=%u)", 5810 dsq->id, dsq->nr); 5811 goto out_unlock_dsq; 5812 } 5813 5814 if (rhashtable_remove_fast(&sch->dsq_hash, &dsq->hash_node, 5815 dsq_hash_params)) 5816 goto out_unlock_dsq; 5817 5818 /* 5819 * Mark dead by invalidating ->id to prevent scx_dispatch_enqueue() from 5820 * queueing more tasks. As this function can be called from anywhere, 5821 * freeing is bounced through an irq work to avoid nesting RCU 5822 * operations inside scheduler locks. 5823 */ 5824 dsq->id = SCX_DSQ_INVALID; 5825 if (llist_add(&dsq->free_node, &dsqs_to_free)) 5826 irq_work_queue(&free_dsq_irq_work); 5827 5828 out_unlock_dsq: 5829 raw_spin_unlock_irqrestore(&dsq->lock, flags); 5830 out_unlock_rcu: 5831 rcu_read_unlock(); 5832 } 5833 5834 #ifdef CONFIG_EXT_GROUP_SCHED 5835 static void scx_cgroup_exit(struct scx_sched *sch) 5836 { 5837 struct cgroup_subsys_state *css; 5838 5839 /* 5840 * scx_tg_on/offline() are excluded through cgroup_lock(). If we walk 5841 * cgroups and exit all the inited ones, all online cgroups are exited. 5842 */ 5843 css_for_each_descendant_post(css, &root_task_group.css) { 5844 struct task_group *tg = css_tg(css); 5845 5846 /* also clear the sched of tgs whose ops.cgroup_init() failed */ 5847 tg->scx.sched = NULL; 5848 if (tg->scx.flags & SCX_TG_INITED) { 5849 tg->scx.flags &= ~SCX_TG_INITED; 5850 if (sch->ops.cgroup_exit) 5851 SCX_CALL_OP(sch, cgroup_exit, NULL, css->cgroup); 5852 } 5853 } 5854 } 5855 5856 static int scx_cgroup_init(struct scx_sched *sch) 5857 { 5858 struct cgroup_subsys_state *css; 5859 int ret; 5860 5861 /* 5862 * scx_tg_on/offline() are excluded through cgroup_lock(). If we walk 5863 * cgroups and init, all online cgroups are initialized. 5864 */ 5865 css_for_each_descendant_pre(css, &root_task_group.css) { 5866 struct task_group *tg = css_tg(css); 5867 5868 if ((tg->scx.flags & (SCX_TG_ONLINE | SCX_TG_INITED)) != SCX_TG_ONLINE) 5869 continue; 5870 5871 if (sch->ops.cgroup_init) { 5872 struct scx_cgroup_init_args args = { 5873 .weight = tg->scx.weight, 5874 .bw_period_us = tg->scx.bw_period_us, 5875 .bw_quota_us = tg->scx.bw_quota_us, 5876 .bw_burst_us = tg->scx.bw_burst_us, 5877 .sched_idle = tg->scx.sched_idle, 5878 }; 5879 5880 ret = SCX_CALL_OP_RET(sch, cgroup_init, NULL, css->cgroup, &args); 5881 if (ret) { 5882 scx_error(sch, "ops.cgroup_init() failed (%d)", ret); 5883 return ret; 5884 } 5885 } 5886 5887 tg->scx.sched = sch; 5888 tg->scx.flags |= SCX_TG_INITED; 5889 } 5890 5891 return 0; 5892 } 5893 5894 #else 5895 static void scx_cgroup_exit(struct scx_sched *sch) {} 5896 static int scx_cgroup_init(struct scx_sched *sch) { return 0; } 5897 #endif 5898 5899 5900 /******************************************************************************** 5901 * Sysfs interface and ops enable/disable. 5902 */ 5903 5904 #define SCX_ATTR(_name) \ 5905 static struct kobj_attribute scx_attr_##_name = { \ 5906 .attr = { .name = __stringify(_name), .mode = 0444 }, \ 5907 .show = scx_attr_##_name##_show, \ 5908 } 5909 5910 static ssize_t scx_attr_state_show(struct kobject *kobj, 5911 struct kobj_attribute *ka, char *buf) 5912 { 5913 return sysfs_emit(buf, "%s\n", scx_enable_state_str[scx_enable_state()]); 5914 } 5915 SCX_ATTR(state); 5916 5917 static ssize_t scx_attr_switch_all_show(struct kobject *kobj, 5918 struct kobj_attribute *ka, char *buf) 5919 { 5920 return sysfs_emit(buf, "%d\n", READ_ONCE(scx_switching_all)); 5921 } 5922 SCX_ATTR(switch_all); 5923 5924 static ssize_t scx_attr_nr_rejected_show(struct kobject *kobj, 5925 struct kobj_attribute *ka, char *buf) 5926 { 5927 return sysfs_emit(buf, "%ld\n", atomic_long_read(&scx_nr_rejected)); 5928 } 5929 SCX_ATTR(nr_rejected); 5930 5931 static ssize_t scx_attr_hotplug_seq_show(struct kobject *kobj, 5932 struct kobj_attribute *ka, char *buf) 5933 { 5934 return sysfs_emit(buf, "%ld\n", atomic_long_read(&scx_hotplug_seq)); 5935 } 5936 SCX_ATTR(hotplug_seq); 5937 5938 static ssize_t scx_attr_enable_seq_show(struct kobject *kobj, 5939 struct kobj_attribute *ka, char *buf) 5940 { 5941 return sysfs_emit(buf, "%ld\n", atomic_long_read(&scx_enable_seq)); 5942 } 5943 SCX_ATTR(enable_seq); 5944 5945 static struct attribute *scx_global_attrs[] = { 5946 &scx_attr_state.attr, 5947 &scx_attr_switch_all.attr, 5948 &scx_attr_nr_rejected.attr, 5949 &scx_attr_hotplug_seq.attr, 5950 &scx_attr_enable_seq.attr, 5951 NULL, 5952 }; 5953 5954 static const struct attribute_group scx_global_attr_group = { 5955 .attrs = scx_global_attrs, 5956 }; 5957 5958 static void free_pnode(struct scx_sched_pnode *pnode); 5959 static void free_exit_info(struct scx_exit_info *ei); 5960 static const char *scx_exit_reason(enum scx_exit_kind kind); 5961 static bool scx_claim_exit(struct scx_sched *sch, enum scx_exit_kind kind); 5962 5963 s32 scx_alloc_kern_arena_objs(struct scx_sched *sch) 5964 { 5965 size_t size = struct_size_t(struct scx_cmask, bits, 5966 SCX_CMASK_NR_WORDS(num_possible_cpus())); 5967 struct scx_cmask *online; 5968 struct scx_cmask_ref ref; 5969 int cpu; 5970 5971 /* hotplug stays excluded until the online mask is published */ 5972 lockdep_assert_cpus_held(); 5973 5974 if (!sch->is_cid_type || !sch->arena_pool) 5975 return 0; 5976 5977 sch->set_cmask_scratch = alloc_percpu(struct scx_cmask *); 5978 if (!sch->set_cmask_scratch) 5979 return -ENOMEM; 5980 5981 for_each_possible_cpu(cpu) { 5982 struct scx_cmask **slot = per_cpu_ptr(sch->set_cmask_scratch, cpu); 5983 5984 *slot = scx_arena_alloc(sch, size); 5985 if (!*slot) 5986 return -ENOMEM; 5987 scx_cmask_init(*slot, 0, num_possible_cpus()); 5988 } 5989 5990 /* pack the online mask alongside the scratch masks */ 5991 online = scx_arena_alloc(sch, size); 5992 if (!online) 5993 return -ENOMEM; 5994 5995 scoped_guard(rcu) { 5996 scx_cmask_ref_init_kern(sch, online, 0, num_possible_cpus(), &ref); 5997 scx_cmask_ref_from_cpumask(&ref, cpu_active_mask); 5998 } 5999 sch->online_cmask = online; 6000 6001 return 0; 6002 } 6003 6004 static void scx_free_kern_arena_objs(struct scx_sched *sch) 6005 { 6006 size_t size = struct_size_t(struct scx_cmask, bits, 6007 SCX_CMASK_NR_WORDS(num_possible_cpus())); 6008 int cpu; 6009 6010 scx_arena_free(sch, sch->online_cmask, size); 6011 if (!sch->set_cmask_scratch) 6012 return; 6013 6014 for_each_possible_cpu(cpu) { 6015 struct scx_cmask **slot = per_cpu_ptr(sch->set_cmask_scratch, cpu); 6016 6017 scx_arena_free(sch, *slot, size); 6018 } 6019 free_percpu(sch->set_cmask_scratch); 6020 sch->set_cmask_scratch = NULL; 6021 } 6022 6023 static void scx_sched_free_rcu_work(struct work_struct *work) 6024 { 6025 struct rcu_work *rcu_work = to_rcu_work(work); 6026 struct scx_sched *sch = container_of(rcu_work, struct scx_sched, rcu_work); 6027 struct rhashtable_iter rht_iter; 6028 struct scx_dispatch_q *dsq; 6029 int cpu, node; 6030 6031 irq_work_sync(&sch->propagate_exit_irq_work); 6032 irq_work_sync(&sch->disable_irq_work); 6033 kthread_destroy_worker(sch->helper); 6034 timer_shutdown_sync(&sch->bypass_lb_timer); 6035 free_cpumask_var(sch->bypass_lb_donee_cpumask); 6036 free_cpumask_var(sch->bypass_lb_resched_cpumask); 6037 free_cpumask_var(sch->stall_cpus); 6038 6039 #ifdef CONFIG_EXT_SUB_SCHED 6040 kfree(sch->cgrp_path); 6041 if (sch_cgroup(sch)) 6042 cgroup_put(sch_cgroup(sch)); 6043 if (sch->sub_kset) 6044 kobject_put(&sch->sub_kset->kobj); 6045 if (scx_parent(sch)) 6046 kobject_put(&scx_parent(sch)->kobj); 6047 #endif /* CONFIG_EXT_SUB_SCHED */ 6048 6049 for_each_possible_cpu(cpu) { 6050 struct scx_sched_pcpu *pcpu = per_cpu_ptr(sch->pcpu, cpu); 6051 6052 /* 6053 * $sch would have entered bypass mode before the RCU grace 6054 * period. As that blocks new deferrals, all 6055 * deferred_reenq_local_node's must be off-list by now. 6056 */ 6057 WARN_ON_ONCE(!list_empty(&pcpu->deferred_reenq_local.node)); 6058 6059 /* remove the queued ecaps sync so the pcpu can be freed */ 6060 scx_discard_ecaps_to_sync(cpu, pcpu); 6061 6062 /* 6063 * Bypass blocks new kicks. Flush the kick irq_work so this 6064 * pcpu's to_kick_node is off the list before it is freed. 6065 */ 6066 irq_work_sync(&cpu_rq(cpu)->scx.kick_cpus_irq_work); 6067 WARN_ON_ONCE(!list_empty(&pcpu->to_kick_node)); 6068 free_cpumask_var(pcpu->cpus_to_kick); 6069 free_cpumask_var(pcpu->cpus_to_kick_if_idle); 6070 free_cpumask_var(pcpu->cpus_to_preempt); 6071 free_cpumask_var(pcpu->cpus_to_preempt_lazy); 6072 free_cpumask_var(pcpu->cpus_to_wait); 6073 6074 exit_dsq(scx_bypass_dsq(sch, cpu)); 6075 } 6076 6077 free_percpu(sch->pcpu); 6078 6079 for_each_node_state(node, N_POSSIBLE) 6080 free_pnode(sch->pnode[node]); 6081 kfree(sch->pnode); 6082 6083 scx_free_pshards(sch); 6084 6085 rhashtable_walk_enter(&sch->dsq_hash, &rht_iter); 6086 do { 6087 rhashtable_walk_start(&rht_iter); 6088 6089 while (!IS_ERR_OR_NULL((dsq = rhashtable_walk_next(&rht_iter)))) 6090 destroy_dsq(sch, dsq->id); 6091 6092 rhashtable_walk_stop(&rht_iter); 6093 } while (dsq == ERR_PTR(-EAGAIN)); 6094 rhashtable_walk_exit(&rht_iter); 6095 6096 rhashtable_free_and_destroy(&sch->dsq_hash, NULL, NULL); 6097 free_exit_info(sch->exit_info); 6098 scx_free_kern_arena_objs(sch); 6099 scx_arena_pool_destroy(sch); 6100 if (sch->arena_map) 6101 bpf_map_put(sch->arena_map); 6102 6103 /* @sch is completely inactive by now */ 6104 scx_dec_has_subs(sch); 6105 6106 kfree(sch); 6107 } 6108 6109 static void scx_kobj_release(struct kobject *kobj) 6110 { 6111 struct scx_sched *sch = container_of(kobj, struct scx_sched, kobj); 6112 6113 INIT_RCU_WORK(&sch->rcu_work, scx_sched_free_rcu_work); 6114 queue_rcu_work(system_dfl_wq, &sch->rcu_work); 6115 } 6116 6117 static ssize_t scx_attr_ops_show(struct kobject *kobj, 6118 struct kobj_attribute *ka, char *buf) 6119 { 6120 struct scx_sched *sch = container_of(kobj, struct scx_sched, kobj); 6121 6122 return sysfs_emit(buf, "%s\n", sch->ops.name); 6123 } 6124 SCX_ATTR(ops); 6125 6126 #define scx_attr_event_show(buf, at, events, kind) ({ \ 6127 sysfs_emit_at(buf, at, "%s %llu\n", #kind, (events)->kind); \ 6128 }) 6129 6130 static ssize_t scx_attr_events_show(struct kobject *kobj, 6131 struct kobj_attribute *ka, char *buf) 6132 { 6133 struct scx_sched *sch = container_of(kobj, struct scx_sched, kobj); 6134 struct scx_event_stats events; 6135 int at = 0; 6136 6137 scx_read_events(sch, &events); 6138 #define SCX_EVENT(name) (at += scx_attr_event_show(buf, at, &events, name)) 6139 SCX_EVENTS_LIST(SCX_EVENT); 6140 #undef SCX_EVENT 6141 return at; 6142 } 6143 SCX_ATTR(events); 6144 6145 #ifdef CONFIG_EXT_SUB_SCHED 6146 static const char *scx_cap_names[__SCX_NR_CAPS] = { 6147 [__SCX_CAP_ENQ_IMMED] = "enq_immed", 6148 [__SCX_CAP_ENQ] = "enq", 6149 [__SCX_CAP_PREEMPT] = "preempt", 6150 [__SCX_CAP_PERF] = "perf", 6151 }; 6152 6153 static ssize_t scx_attr_caps_show(struct kobject *kobj, 6154 struct kobj_attribute *ka, char *buf) 6155 { 6156 struct scx_sched *sch = container_of(kobj, struct scx_sched, kobj); 6157 u32 npossible = num_possible_cpus(); 6158 struct scx_cmask *agg __free(kfree) = 6159 kzalloc_flex(*agg, bits, SCX_CMASK_NR_WORDS(npossible)); 6160 unsigned long *agg_bm __free(bitmap) = bitmap_zalloc(npossible, GFP_KERNEL); 6161 ssize_t count = 0; 6162 s32 cap, si; 6163 6164 if (!agg || !agg_bm) 6165 return -ENOMEM; 6166 6167 for (cap = 0; cap < __SCX_NR_CAPS; cap++) { 6168 SCX_CMASK_DEFINE(snap, 0, SCX_CID_SHARD_MAX_CPUS); 6169 6170 scx_cmask_init(agg, 0, npossible); 6171 for (si = 0; si < sch->nr_pshards; si++) { 6172 struct scx_cmask *cm = &sch->pshard[si]->caps[cap].cmask; 6173 6174 scx_cmask_reframe(snap, cm->base, cm->nr_cids); 6175 scx_cmask_copy(snap, cm); 6176 scx_cmask_or(agg, snap); 6177 } 6178 /* %*pbl takes unsigned long bitmap layout, convert from u64 */ 6179 bitmap_from_arr64(agg_bm, agg->bits, npossible); 6180 count += sysfs_emit_at(buf, count, "%s: %*pbl\n", 6181 scx_cap_names[cap], npossible, agg_bm); 6182 } 6183 return count; 6184 } 6185 SCX_ATTR(caps); 6186 #endif /* CONFIG_EXT_SUB_SCHED */ 6187 6188 static struct attribute *scx_sched_attrs[] = { 6189 &scx_attr_ops.attr, 6190 &scx_attr_events.attr, 6191 #ifdef CONFIG_EXT_SUB_SCHED 6192 &scx_attr_caps.attr, 6193 #endif 6194 NULL, 6195 }; 6196 ATTRIBUTE_GROUPS(scx_sched); 6197 6198 static const struct kobj_type scx_ktype = { 6199 .release = scx_kobj_release, 6200 .sysfs_ops = &kobj_sysfs_ops, 6201 .default_groups = scx_sched_groups, 6202 }; 6203 6204 static int scx_uevent(const struct kobject *kobj, struct kobj_uevent_env *env) 6205 { 6206 const struct scx_sched *sch; 6207 6208 /* 6209 * scx_uevent() can be reached by both scx_sched kobjects (scx_ktype) 6210 * and sub-scheduler kset kobjects (kset_ktype) through the parent 6211 * chain walk. Filter out the latter to avoid invalid casts. 6212 */ 6213 if (kobj->ktype != &scx_ktype) 6214 return 0; 6215 6216 sch = container_of(kobj, struct scx_sched, kobj); 6217 6218 return add_uevent_var(env, "SCXOPS=%s", sch->ops.name); 6219 } 6220 6221 static const struct kset_uevent_ops scx_uevent_ops = { 6222 .uevent = scx_uevent, 6223 }; 6224 6225 /* 6226 * Used by sched_fork() and __setscheduler_class() to pick the matching 6227 * sched_class. dl/rt are already handled. 6228 */ 6229 bool task_should_scx(int policy) 6230 { 6231 /* if disabled, nothing should be on it */ 6232 if (!scx_enabled()) 6233 return false; 6234 6235 /* scx is taking over all SCHED_OTHER and SCHED_EXT tasks */ 6236 if (READ_ONCE(scx_switching_all)) 6237 return true; 6238 6239 /* 6240 * scx is tearing down - keep new SCHED_EXT tasks out. 6241 * 6242 * Must come after scx_switching_all test, which serves as a proxy 6243 * for __scx_switched_all. While __scx_switched_all is set, we must 6244 * return true via the branch above: a fork routed to fair would 6245 * stall because next_active_class() skips fair. 6246 * 6247 * This can develop into a deadlock - scx holds scx_enable_mutex across 6248 * kthread_create() in scx_alloc_and_add_sched(); if the new kthread is 6249 * the stalled task, the disable path can never grab the mutex to clear 6250 * scx_switching_all. 6251 */ 6252 if (unlikely(scx_enable_state() == SCX_DISABLING)) 6253 return false; 6254 6255 return policy == SCHED_EXT; 6256 } 6257 6258 bool scx_allow_ttwu_queue(const struct task_struct *p) 6259 { 6260 struct scx_sched *sch; 6261 6262 if (!scx_enabled()) 6263 return true; 6264 6265 sch = scx_task_sched(p); 6266 if (unlikely(!sch)) 6267 return true; 6268 6269 if (sch->ops.flags & SCX_OPS_ALLOW_QUEUED_WAKEUP) 6270 return true; 6271 6272 if (unlikely(p->sched_class != &ext_sched_class)) 6273 return true; 6274 6275 return false; 6276 } 6277 6278 /** 6279 * handle_lockup - sched_ext common lockup handler 6280 * @exit_cpu: CPU to record in exit_info. Pass the stalled/hung CPU, not current. 6281 * @fmt: format string 6282 * 6283 * Called on system stall or lockup condition and initiates abort of sched_ext 6284 * if enabled, which may resolve the reported lockup. 6285 * 6286 * Returns %true if sched_ext is enabled and abort was initiated, which may 6287 * resolve the lockup. %false if sched_ext is not enabled or abort was already 6288 * initiated by someone else. 6289 */ 6290 static __printf(2, 3) bool handle_lockup(int exit_cpu, const char *fmt, ...) 6291 { 6292 struct scx_sched *sch; 6293 va_list args; 6294 bool ret; 6295 6296 guard(rcu)(); 6297 6298 sch = rcu_dereference(scx_root); 6299 if (unlikely(!sch)) 6300 return false; 6301 6302 switch (scx_enable_state()) { 6303 case SCX_ENABLING: 6304 case SCX_ENABLED: 6305 va_start(args, fmt); 6306 ret = scx_vexit(sch, SCX_EXIT_ERROR, 0, exit_cpu, fmt, args); 6307 va_end(args); 6308 return ret; 6309 default: 6310 return false; 6311 } 6312 } 6313 6314 /** 6315 * scx_rcu_cpu_stall - sched_ext RCU CPU stall handler 6316 * @stalled_mask: bit mask of stalled CPUs 6317 * 6318 * While there are various reasons why RCU CPU stalls can occur on a system 6319 * that may not be caused by the current BPF scheduler, try kicking out the 6320 * current scheduler in an attempt to recover the system to a good state before 6321 * issuing panics. 6322 * 6323 * Returns %true if sched_ext is enabled and abort was initiated, which may 6324 * resolve the reported RCU stall. %false if sched_ext is not enabled or someone 6325 * else already initiated abort. 6326 */ 6327 bool scx_rcu_cpu_stall(const struct cpumask *stalled_mask) 6328 { 6329 struct scx_sched *sch; 6330 struct scx_exit_info *ei; 6331 int exit_cpu; 6332 6333 guard(rcu)(); 6334 6335 sch = rcu_dereference(scx_root); 6336 if (unlikely(!sch)) 6337 return false; 6338 6339 switch (scx_enable_state()) { 6340 case SCX_ENABLING: 6341 case SCX_ENABLED: 6342 break; 6343 default: 6344 return false; 6345 } 6346 6347 exit_cpu = cpumask_empty(stalled_mask) ? -1 : (int)cpumask_first(stalled_mask); 6348 ei = sch->exit_info; 6349 6350 guard(preempt)(); 6351 6352 if (!scx_claim_exit(sch, SCX_EXIT_ERROR)) 6353 return false; 6354 6355 #ifdef CONFIG_STACKTRACE 6356 ei->bt_len = stack_trace_save(ei->bt, SCX_EXIT_BT_LEN, 1); 6357 #endif 6358 scnprintf(ei->msg, SCX_EXIT_MSG_LEN, "RCU CPU stall on CPUs (%*pbl)", 6359 cpumask_pr_args(stalled_mask)); 6360 ei->kind = SCX_EXIT_ERROR; 6361 ei->reason = scx_exit_reason(SCX_EXIT_ERROR); 6362 ei->exit_cpu = exit_cpu; 6363 cpumask_copy(sch->stall_cpus, stalled_mask); 6364 6365 irq_work_queue(&sch->disable_irq_work); 6366 return true; 6367 } 6368 6369 /** 6370 * scx_softlockup - sched_ext softlockup handler 6371 * @dur_s: number of seconds of CPU stuck due to soft lockup 6372 * 6373 * On some multi-socket setups (e.g. 2x Intel 8480c), the BPF scheduler can 6374 * live-lock the system by making many CPUs target the same DSQ to the point 6375 * where soft-lockup detection triggers. This function is called from 6376 * soft-lockup watchdog when the triggering point is close and tries to unjam 6377 * the system and aborting the BPF scheduler. 6378 */ 6379 void scx_softlockup(u32 dur_s) 6380 { 6381 int cpu = smp_processor_id(); 6382 6383 if (!handle_lockup(cpu, "soft lockup - CPU %d stuck for %us", cpu, dur_s)) 6384 return; 6385 6386 printk_deferred(KERN_ERR "sched_ext: Soft lockup - CPU %d stuck for %us, disabling BPF scheduler\n", 6387 cpu, dur_s); 6388 } 6389 6390 /** 6391 * scx_hardlockup - sched_ext hardlockup handler 6392 * @cpu: the target CPU 6393 * 6394 * A poorly behaving BPF scheduler can trigger hard lockup by e.g. putting 6395 * numerous affinitized tasks in a single queue and directing all CPUs at it. 6396 * Try kicking out the current scheduler in an attempt to recover the system to 6397 * a good state before taking more drastic actions. 6398 * 6399 * Called from NMI. Aborting the scheduler sets ->aborting throughout the 6400 * hierarchy before returning, which is what breaks the dispatch-path live-locks 6401 * that can hard-lock CPUs. 6402 * 6403 * Returns %true if sched_ext is enabled and abort was initiated, which may 6404 * resolve the lockup. %false if sched_ext is not enabled or abort was already 6405 * initiated by someone else. 6406 */ 6407 bool scx_hardlockup(int cpu) 6408 { 6409 if (!handle_lockup(cpu, "hard lockup - CPU %d", cpu)) 6410 return false; 6411 6412 printk_deferred(KERN_ERR "sched_ext: Hard lockup - CPU %d, disabling BPF scheduler\n", 6413 cpu); 6414 return true; 6415 } 6416 6417 static u32 bypass_lb_cpu(struct scx_sched *sch, s32 donor, 6418 struct cpumask *donee_mask, struct cpumask *resched_mask, 6419 u32 nr_donor_target, u32 nr_donee_target) 6420 { 6421 struct rq *donor_rq = cpu_rq(donor); 6422 struct scx_dispatch_q *donor_dsq = scx_bypass_dsq(sch, donor); 6423 struct task_struct *p, *n; 6424 struct scx_dsq_list_node cursor = INIT_DSQ_LIST_CURSOR(cursor, donor_dsq, 0); 6425 s32 delta = READ_ONCE(donor_dsq->nr) - nr_donor_target; 6426 u32 nr_balanced = 0, min_delta_us; 6427 6428 /* 6429 * All we want to guarantee is reasonable forward progress. No reason to 6430 * fine tune. Assuming every task on @donor_dsq runs their full slice, 6431 * consider offloading iff the total queued duration is over the 6432 * threshold. 6433 */ 6434 min_delta_us = READ_ONCE(scx_bypass_lb_intv_us) / SCX_BYPASS_LB_MIN_DELTA_DIV; 6435 if (delta < DIV_ROUND_UP(min_delta_us, READ_ONCE(scx_slice_bypass_us))) 6436 return 0; 6437 6438 raw_spin_rq_lock_irq(donor_rq); 6439 raw_spin_lock(&donor_dsq->lock); 6440 list_add(&cursor.node, &donor_dsq->list); 6441 resume: 6442 n = container_of(&cursor, struct task_struct, scx.dsq_list); 6443 n = nldsq_next_task(donor_dsq, n, false); 6444 6445 while ((p = n)) { 6446 struct scx_dispatch_q *donee_dsq; 6447 int donee; 6448 6449 n = nldsq_next_task(donor_dsq, n, false); 6450 6451 if (donor_dsq->nr <= nr_donor_target) 6452 break; 6453 6454 if (cpumask_empty(donee_mask)) 6455 break; 6456 6457 /* 6458 * If an earlier pass placed @p on @donor_dsq from a different 6459 * CPU and the donee hasn't consumed it yet, @p is still on the 6460 * previous CPU and task_rq(@p) != @donor_rq. @p can't be moved 6461 * without its rq locked. Skip. 6462 */ 6463 if (task_rq(p) != donor_rq) 6464 continue; 6465 6466 donee = cpumask_any_and_distribute(donee_mask, p->cpus_ptr); 6467 if (donee >= nr_cpu_ids) 6468 continue; 6469 6470 donee_dsq = scx_bypass_dsq(sch, donee); 6471 6472 /* 6473 * $p's rq is not locked but $p's DSQ lock protects its 6474 * scheduling properties making this test safe. 6475 */ 6476 if (!task_can_run_on_remote_rq(sch, p, cpu_rq(donee), false)) 6477 continue; 6478 6479 /* 6480 * Moving $p from one non-local DSQ to another. The source rq 6481 * and DSQ are already locked. Do an abbreviated dequeue and 6482 * then perform enqueue without unlocking $donor_dsq. 6483 * 6484 * We don't want to drop and reacquire the lock on each 6485 * iteration as @donor_dsq can be very long and potentially 6486 * highly contended. Donee DSQs are less likely to be contended. 6487 * The nested locking is safe as only this LB moves tasks 6488 * between bypass DSQs. 6489 */ 6490 dispatch_dequeue_locked(p, donor_dsq); 6491 scx_dispatch_enqueue(sch, cpu_rq(donee), donee_dsq, p, 0, 0, SCX_ENQ_NESTED); 6492 6493 /* 6494 * $donee might have been idle and need to be woken up. No need 6495 * to be clever. Kick every CPU that receives tasks. 6496 */ 6497 cpumask_set_cpu(donee, resched_mask); 6498 6499 if (READ_ONCE(donee_dsq->nr) >= nr_donee_target) 6500 cpumask_clear_cpu(donee, donee_mask); 6501 6502 nr_balanced++; 6503 if (!(nr_balanced % SCX_BYPASS_LB_BATCH) && n) { 6504 list_move_tail(&cursor.node, &n->scx.dsq_list.node); 6505 raw_spin_unlock(&donor_dsq->lock); 6506 scx_rq_lock_drop(donor_rq); 6507 raw_spin_rq_unlock_irq(donor_rq); 6508 cpu_relax(); 6509 raw_spin_rq_lock_irq(donor_rq); 6510 raw_spin_lock(&donor_dsq->lock); 6511 goto resume; 6512 } 6513 } 6514 6515 list_del_init(&cursor.node); 6516 raw_spin_unlock(&donor_dsq->lock); 6517 scx_rq_lock_drop(donor_rq); 6518 raw_spin_rq_unlock_irq(donor_rq); 6519 6520 return nr_balanced; 6521 } 6522 6523 static void bypass_lb_node(struct scx_sched *sch, int node) 6524 { 6525 const struct cpumask *node_mask = cpumask_of_node(node); 6526 struct cpumask *donee_mask = sch->bypass_lb_donee_cpumask; 6527 struct cpumask *resched_mask = sch->bypass_lb_resched_cpumask; 6528 u32 nr_tasks = 0, nr_cpus = 0, nr_balanced = 0; 6529 u32 nr_target, nr_donor_target; 6530 u32 before_min = U32_MAX, before_max = 0; 6531 u32 after_min = U32_MAX, after_max = 0; 6532 int cpu; 6533 6534 /* count the target tasks and CPUs */ 6535 for_each_cpu_and(cpu, cpu_online_mask, node_mask) { 6536 u32 nr = READ_ONCE(scx_bypass_dsq(sch, cpu)->nr); 6537 6538 nr_tasks += nr; 6539 nr_cpus++; 6540 6541 before_min = min(nr, before_min); 6542 before_max = max(nr, before_max); 6543 } 6544 6545 if (!nr_cpus) 6546 return; 6547 6548 /* 6549 * We don't want CPUs to have more than $nr_donor_target tasks and 6550 * balancing to fill donee CPUs up to $nr_target. Once targets are 6551 * calculated, find the donee CPUs. 6552 */ 6553 nr_target = DIV_ROUND_UP(nr_tasks, nr_cpus); 6554 nr_donor_target = DIV_ROUND_UP(nr_target * SCX_BYPASS_LB_DONOR_PCT, 100); 6555 6556 cpumask_clear(donee_mask); 6557 for_each_cpu_and(cpu, cpu_online_mask, node_mask) { 6558 if (READ_ONCE(scx_bypass_dsq(sch, cpu)->nr) < nr_target) 6559 cpumask_set_cpu(cpu, donee_mask); 6560 } 6561 6562 /* iterate !donee CPUs and see if they should be offloaded */ 6563 cpumask_clear(resched_mask); 6564 for_each_cpu_and(cpu, cpu_online_mask, node_mask) { 6565 if (cpumask_empty(donee_mask)) 6566 break; 6567 if (cpumask_test_cpu(cpu, donee_mask)) 6568 continue; 6569 if (READ_ONCE(scx_bypass_dsq(sch, cpu)->nr) <= nr_donor_target) 6570 continue; 6571 6572 nr_balanced += bypass_lb_cpu(sch, cpu, donee_mask, resched_mask, 6573 nr_donor_target, nr_target); 6574 } 6575 6576 for_each_cpu(cpu, resched_mask) 6577 resched_cpu(cpu); 6578 6579 for_each_cpu_and(cpu, cpu_online_mask, node_mask) { 6580 u32 nr = READ_ONCE(scx_bypass_dsq(sch, cpu)->nr); 6581 6582 after_min = min(nr, after_min); 6583 after_max = max(nr, after_max); 6584 6585 } 6586 6587 trace_sched_ext_bypass_lb(node, nr_cpus, nr_tasks, nr_balanced, 6588 before_min, before_max, after_min, after_max); 6589 } 6590 6591 /* 6592 * In bypass mode, all tasks are put on the per-CPU bypass DSQs. If the machine 6593 * is over-saturated and the BPF scheduler skewed tasks into few CPUs, some 6594 * bypass DSQs can be overloaded. If there are enough tasks to saturate other 6595 * lightly loaded CPUs, such imbalance can lead to very high execution latency 6596 * on the overloaded CPUs and thus to hung tasks and RCU stalls. To avoid such 6597 * outcomes, a simple load balancing mechanism is implemented by the following 6598 * timer which runs periodically while bypass mode is in effect. 6599 */ 6600 static void scx_bypass_lb_timerfn(struct timer_list *timer) 6601 { 6602 struct scx_sched *sch = container_of(timer, struct scx_sched, bypass_lb_timer); 6603 int node; 6604 u32 intv_us; 6605 6606 if (!scx_bypass_dsp_enabled(sch)) 6607 return; 6608 6609 for_each_node_with_cpus(node) 6610 bypass_lb_node(sch, node); 6611 6612 intv_us = READ_ONCE(scx_bypass_lb_intv_us); 6613 if (intv_us) 6614 mod_timer(timer, jiffies + usecs_to_jiffies(intv_us)); 6615 } 6616 6617 static bool inc_bypass_depth(struct scx_sched *sch) 6618 { 6619 lockdep_assert_held(&scx_bypass_lock); 6620 6621 WARN_ON_ONCE(sch->bypass_depth < 0); 6622 WRITE_ONCE(sch->bypass_depth, sch->bypass_depth + 1); 6623 if (sch->bypass_depth != 1) 6624 return false; 6625 6626 WRITE_ONCE(sch->slice_dfl, READ_ONCE(scx_slice_bypass_us) * NSEC_PER_USEC); 6627 sch->bypass_timestamp = ktime_get_ns(); 6628 scx_add_event(sch, SCX_EV_BYPASS_ACTIVATE, 1); 6629 return true; 6630 } 6631 6632 static bool dec_bypass_depth(struct scx_sched *sch) 6633 { 6634 lockdep_assert_held(&scx_bypass_lock); 6635 6636 WARN_ON_ONCE(sch->bypass_depth < 1); 6637 WRITE_ONCE(sch->bypass_depth, sch->bypass_depth - 1); 6638 if (sch->bypass_depth != 0) 6639 return false; 6640 6641 WRITE_ONCE(sch->slice_dfl, SCX_SLICE_DFL); 6642 scx_add_event(sch, SCX_EV_BYPASS_DURATION, 6643 ktime_get_ns() - sch->bypass_timestamp); 6644 return true; 6645 } 6646 6647 static void enable_bypass_dsp(struct scx_sched *sch) 6648 { 6649 struct scx_sched *host = scx_parent(sch) ?: sch; 6650 u32 intv_us = READ_ONCE(scx_bypass_lb_intv_us); 6651 s32 ret; 6652 6653 /* 6654 * @sch->bypass_depth transitioning from 0 to 1 triggers enabling. 6655 * Shouldn't stagger. 6656 */ 6657 if (WARN_ON_ONCE(test_and_set_bit(0, &sch->bypass_dsp_claim))) 6658 return; 6659 6660 /* 6661 * When a sub-sched bypasses, its tasks are queued on the bypass DSQs of 6662 * the nearest non-bypassing ancestor or root. The parent hosts them 6663 * unless it is bypassing too. Then they sit further up and the parent 6664 * consumes only its own bypass DSQs, empty until it leaves bypass and 6665 * becomes the host. Either way the nearest non-bypassing ancestor or 6666 * root has bypass dispatch enabled while a descendant is bypassing, 6667 * which is all that's required. 6668 * 6669 * scx_bypass_dsp_enabled() test is used to determine whether to enter 6670 * the bypass dispatch handling path from both bypassing and hosting 6671 * scheds. Bump enable depth on both @sch and bypass dispatch host. 6672 */ 6673 ret = atomic_inc_return(&sch->bypass_dsp_enable_depth); 6674 WARN_ON_ONCE(ret <= 0); 6675 6676 if (host != sch) { 6677 ret = atomic_inc_return(&host->bypass_dsp_enable_depth); 6678 WARN_ON_ONCE(ret <= 0); 6679 } 6680 6681 /* 6682 * The LB timer will stop running if bypass dispatch is disabled. Start 6683 * after enabling bypass dispatch. 6684 */ 6685 if (intv_us && !timer_pending(&host->bypass_lb_timer)) 6686 mod_timer(&host->bypass_lb_timer, 6687 jiffies + usecs_to_jiffies(intv_us)); 6688 } 6689 6690 /* may be called without holding scx_bypass_lock */ 6691 void scx_disable_bypass_dsp(struct scx_sched *sch) 6692 { 6693 s32 ret; 6694 6695 if (!test_and_clear_bit(0, &sch->bypass_dsp_claim)) 6696 return; 6697 6698 ret = atomic_dec_return(&sch->bypass_dsp_enable_depth); 6699 WARN_ON_ONCE(ret < 0); 6700 6701 if (scx_parent(sch)) { 6702 ret = atomic_dec_return(&scx_parent(sch)->bypass_dsp_enable_depth); 6703 WARN_ON_ONCE(ret < 0); 6704 } 6705 } 6706 6707 /** 6708 * unbypass_renotify_idle - Arm an idle re-notify for a sched leaving bypass 6709 * @rq: rq of the cpu leaving bypass 6710 * @pos: scheduler that just left bypass on @rq's cpu 6711 * @pcpu: @pos's per-cpu state for @rq's cpu 6712 * 6713 * A sched leaving bypass is owed the ops.update_idle() calls suppressed while 6714 * bypassing. A cpu that goes idle during the bypass window and stays idle won't 6715 * produce a notification. Arm a re-notify that scx_bypass()'s resched flushes 6716 * on the next idle pick. 6717 * 6718 * An acute case is ops.sub_attach(). If the parent grants the child cids while 6719 * attaching, when attach is complete and bypass is lifted, the child may hold 6720 * idle cids it never saw go idle. 6721 * 6722 * The root is no exception as bypass suppresses its notifications the same way. 6723 * However, the root uses a separate per-rq flag so its re-notify keeps working 6724 * even when !CONFIG_EXT_SUB_SCHED. 6725 */ 6726 static void unbypass_renotify_idle(struct rq *rq, struct scx_sched *pos, 6727 struct scx_sched_pcpu *pcpu) 6728 { 6729 if (!pos->level) { 6730 rq->scx.flags |= SCX_RQ_ROOT_IDLE_RENOTIFY; 6731 return; 6732 } 6733 #ifdef CONFIG_EXT_SUB_SCHED 6734 pcpu->idle_renotify = true; 6735 rq->scx.flags |= SCX_RQ_SUB_IDLE_RENOTIFY; 6736 #endif 6737 } 6738 6739 /** 6740 * scx_bypass - [Un]bypass scx_ops and guarantee forward progress 6741 * @sch: sched to bypass 6742 * @bypass: true for bypass, false for unbypass 6743 * 6744 * Bypassing guarantees that all runnable tasks make forward progress without 6745 * trusting the BPF scheduler. We can't grab any mutexes or rwsems as they might 6746 * be held by tasks that the BPF scheduler is forgetting to run, which 6747 * unfortunately also excludes toggling the static branches. 6748 * 6749 * Let's work around by overriding a couple ops and modifying behaviors based on 6750 * the DISABLING state and then cycling the queued tasks through dequeue/enqueue 6751 * to force global FIFO scheduling. 6752 * 6753 * - ops.select_cpu() is ignored and the default select_cpu() is used. 6754 * 6755 * - ops.enqueue() is ignored and tasks are queued in simple global FIFO order. 6756 * %SCX_OPS_ENQ_LAST is also ignored. 6757 * 6758 * - ops.dispatch() is ignored. 6759 * 6760 * - dispatch_one() does not report %SCX_DSP_PREV on non-zero slice as slice 6761 * can't be trusted. Whenever a tick triggers, the running task is rotated to 6762 * the tail of the queue. 6763 * 6764 * - pick_next_task() suppresses zero slice warning. 6765 * 6766 * - scx_kick_cpu() is disabled to avoid irq_work malfunction during PM 6767 * operations. 6768 * 6769 * - scx_prio_less() reverts to the default runnable_at order. 6770 */ 6771 void scx_bypass(struct scx_sched *sch, bool bypass) 6772 { 6773 struct scx_sched *pos; 6774 unsigned long flags; 6775 int cpu; 6776 bool changed; 6777 6778 raw_spin_lock_irqsave(&scx_bypass_lock, flags); 6779 6780 if (bypass) { 6781 changed = inc_bypass_depth(sch); 6782 if (changed) 6783 enable_bypass_dsp(sch); 6784 } else { 6785 changed = dec_bypass_depth(sch); 6786 } 6787 6788 /* 6789 * Bypass state is propagated to all descendants - an scx_sched bypasses 6790 * if itself or any of its ancestors are in bypass mode. A descendant's 6791 * depth is the sum of its own bypasses and its ancestors', so every 6792 * call propagates whether or not @sch changed state. The descendants' 6793 * claims are released below with @sch's, after their tasks have moved. 6794 */ 6795 raw_spin_lock(&scx_sched_lock); 6796 scx_for_each_descendant_pre(pos, sch) { 6797 if (pos == sch) 6798 continue; 6799 if (bypass) { 6800 if (inc_bypass_depth(pos)) 6801 enable_bypass_dsp(pos); 6802 } else { 6803 dec_bypass_depth(pos); 6804 } 6805 } 6806 raw_spin_unlock(&scx_sched_lock); 6807 6808 /* 6809 * A descendant's depth is at least @sch's, so no bypass state changed 6810 * unless @sch's did. 6811 */ 6812 if (!changed) 6813 goto unlock; 6814 6815 /* 6816 * No task property is changing. We just need to make sure all currently 6817 * queued tasks are re-queued according to the new scx_bypassing() 6818 * state. As an optimization, walk each rq's runnable_list instead of 6819 * the scx_tasks list. 6820 * 6821 * This function can't trust the scheduler and thus can't use 6822 * cpus_read_lock(). Walk all possible CPUs instead of online. 6823 */ 6824 for_each_possible_cpu(cpu) { 6825 struct rq *rq = cpu_rq(cpu); 6826 struct task_struct *p, *n; 6827 6828 raw_spin_rq_lock(rq); 6829 raw_spin_lock(&scx_sched_lock); 6830 6831 scx_for_each_descendant_pre(pos, sch) { 6832 struct scx_sched_pcpu *pcpu = per_cpu_ptr(pos->pcpu, cpu); 6833 bool was_bypassing = pcpu->flags & SCX_SCHED_PCPU_BYPASSING; 6834 6835 if (pos->bypass_depth) { 6836 pcpu->flags |= SCX_SCHED_PCPU_BYPASSING; 6837 } else { 6838 pcpu->flags &= ~SCX_SCHED_PCPU_BYPASSING; 6839 if (was_bypassing) { 6840 unbypass_renotify_idle(rq, pos, pcpu); 6841 scx_unbypass_replay_ecaps(rq, pos); 6842 } 6843 } 6844 } 6845 6846 raw_spin_unlock(&scx_sched_lock); 6847 6848 /* 6849 * We need to guarantee that no tasks are on the BPF scheduler 6850 * while bypassing. Either we see enabled or the enable path 6851 * sees scx_bypassing() before moving tasks to SCX. 6852 */ 6853 if (!scx_enabled()) { 6854 scx_rq_lock_drop(rq); 6855 raw_spin_rq_unlock(rq); 6856 continue; 6857 } 6858 6859 /* 6860 * Bypass trumps protection. Cycling the queued tasks below 6861 * clears theirs. The current donor isn't on the runnable list, 6862 * so strip its protection here. 6863 * 6864 * When bypass lifts, the current donor keeps running on its 6865 * slice without a cap check. Evict it if it can't stay on the 6866 * cpu. 6867 */ 6868 p = rq->donor; 6869 if (p->sched_class == &ext_sched_class && 6870 scx_is_descendant(scx_task_sched(p), sch)) { 6871 if (bypass) 6872 scx_task_slice_ended(rq, p); 6873 else if (!scx_task_can_stay_on_cpu(rq, p)) 6874 scx_set_task_slice(p, 0); 6875 } 6876 6877 /* 6878 * The use of list_for_each_entry_safe_reverse() is required 6879 * because each task is going to be removed from and added back 6880 * to the runnable_list during iteration. Because they're added 6881 * to the tail of the list, safe reverse iteration can still 6882 * visit all nodes. 6883 */ 6884 list_for_each_entry_safe_reverse(p, n, &rq->scx.runnable_list, 6885 scx.runnable_node) { 6886 if (!scx_is_descendant(scx_task_sched(p), sch)) 6887 continue; 6888 6889 /* cycling deq/enq is enough, see the function comment */ 6890 scoped_guard (sched_change, p, DEQUEUE_SAVE | DEQUEUE_MOVE) { 6891 /* nothing */ ; 6892 } 6893 } 6894 6895 /* resched to restore ticks and idle state */ 6896 if (cpu_online(cpu) || cpu == smp_processor_id()) 6897 resched_curr(rq); 6898 6899 scx_rq_lock_drop(rq); 6900 raw_spin_rq_unlock(rq); 6901 } 6902 6903 /* disarming must come after moving all tasks out of the bypass DSQs */ 6904 if (!bypass) { 6905 guard(raw_spinlock)(&scx_sched_lock); 6906 scx_for_each_descendant_pre(pos, sch) 6907 if (!pos->bypass_depth) 6908 scx_disable_bypass_dsp(pos); 6909 } 6910 unlock: 6911 raw_spin_unlock_irqrestore(&scx_bypass_lock, flags); 6912 } 6913 6914 static void free_exit_info(struct scx_exit_info *ei) 6915 { 6916 kvfree(ei->dump); 6917 kfree(ei->msg); 6918 kfree(ei->bt); 6919 kfree(ei); 6920 } 6921 6922 static struct scx_exit_info *alloc_exit_info(size_t exit_dump_len) 6923 { 6924 struct scx_exit_info *ei; 6925 6926 ei = kzalloc_obj(*ei); 6927 if (!ei) 6928 return NULL; 6929 6930 ei->exit_cpu = -1; 6931 ei->bt = kzalloc_objs(ei->bt[0], SCX_EXIT_BT_LEN); 6932 ei->msg = kzalloc(SCX_EXIT_MSG_LEN, GFP_KERNEL); 6933 ei->dump = kvzalloc(exit_dump_len, GFP_KERNEL); 6934 6935 if (!ei->bt || !ei->msg || !ei->dump) { 6936 free_exit_info(ei); 6937 return NULL; 6938 } 6939 6940 return ei; 6941 } 6942 6943 static const char *scx_exit_reason(enum scx_exit_kind kind) 6944 { 6945 switch (kind) { 6946 case SCX_EXIT_UNREG: 6947 return "unregistered from user space"; 6948 case SCX_EXIT_UNREG_BPF: 6949 return "unregistered from BPF"; 6950 case SCX_EXIT_UNREG_KERN: 6951 return "unregistered from the main kernel"; 6952 case SCX_EXIT_SYSRQ: 6953 return "disabled by sysrq-S"; 6954 case SCX_EXIT_PARENT: 6955 return "parent exiting"; 6956 case SCX_EXIT_PARENT_KILL: 6957 return "killed by parent scheduler"; 6958 case SCX_EXIT_ERROR: 6959 return "runtime error"; 6960 case SCX_EXIT_ERROR_BPF: 6961 return "scx_bpf_error"; 6962 case SCX_EXIT_ERROR_STALL: 6963 return "runnable task stall"; 6964 case SCX_EXIT_ERROR_REENQ: 6965 return "reenqueue limit"; 6966 case SCX_EXIT_ERROR_RESCUE: 6967 return "rescue bandwidth overload"; 6968 default: 6969 return "<UNKNOWN>"; 6970 } 6971 } 6972 6973 static void free_kick_syncs(void) 6974 { 6975 int cpu; 6976 6977 for_each_possible_cpu(cpu) { 6978 struct scx_kick_syncs __rcu **ksyncs = per_cpu_ptr(&scx_kick_syncs, cpu); 6979 struct scx_kick_syncs *to_free; 6980 6981 /* flush the pending kick before freeing @ksyncs */ 6982 irq_work_sync(&cpu_rq(cpu)->scx.kick_cpus_irq_work); 6983 to_free = rcu_replace_pointer(*ksyncs, NULL, true); 6984 if (to_free) 6985 kvfree_rcu(to_free, rcu); 6986 } 6987 } 6988 6989 static void refresh_watchdog(void) 6990 { 6991 struct scx_sched *sch; 6992 unsigned long intv = ULONG_MAX; 6993 6994 /* take the shortest timeout and use its half for watchdog interval */ 6995 rcu_read_lock(); 6996 list_for_each_entry_rcu(sch, &scx_sched_all, all) 6997 intv = max(min(intv, sch->watchdog_timeout / 2), 1); 6998 rcu_read_unlock(); 6999 7000 WRITE_ONCE(scx_watchdog_timestamp, jiffies); 7001 WRITE_ONCE(scx_watchdog_interval, intv); 7002 7003 if (intv < ULONG_MAX) 7004 mod_delayed_work(system_dfl_wq, &scx_watchdog_work, intv); 7005 else 7006 cancel_delayed_work_sync(&scx_watchdog_work); 7007 } 7008 7009 s32 scx_link_sched(struct scx_sched *sch) 7010 { 7011 scoped_guard(raw_spinlock_irqsave, &scx_bypass_lock) /* for the parent bypass check */ 7012 scoped_guard(raw_spinlock, &scx_sched_lock) { 7013 #ifdef CONFIG_EXT_SUB_SCHED 7014 struct scx_sched *parent = scx_parent(sch); 7015 7016 if (parent) { 7017 s32 ret; 7018 7019 /* 7020 * Bypass state is spread across per-cpu flags and a 7021 * depth count, so inheriting it is tricky and has no 7022 * valid use case. Refuse it. 7023 */ 7024 if (READ_ONCE(parent->bypass_depth)) { 7025 scx_error(sch, "parent bypassing (%d)", -EBUSY); 7026 return -EBUSY; 7027 } 7028 7029 ret = rhashtable_lookup_insert_fast(&scx_sched_hash, 7030 &sch->hash_node, scx_sched_hash_params); 7031 if (ret) { 7032 scx_error(sch, "failed to insert into scx_sched_hash (%d)", 7033 ret); 7034 return ret; 7035 } 7036 7037 list_add_tail_rcu(&sch->sibling, &parent->children); 7038 7039 /* 7040 * Pairs with the mb after the ->aborting assertion in 7041 * scx_claim_exit(). Either we see ->aborting and back 7042 * out, or the exit path sees us and exits us. 7043 */ 7044 smp_mb(); 7045 if (unlikely(READ_ONCE(parent->aborting))) { 7046 rhashtable_remove_fast(&scx_sched_hash, &sch->hash_node, 7047 scx_sched_hash_params); 7048 list_del_rcu(&sch->sibling); 7049 scx_error(sch, "parent disabled (%d)", -ENOENT); 7050 return -ENOENT; 7051 } 7052 7053 sch->linked = true; 7054 } 7055 #endif /* CONFIG_EXT_SUB_SCHED */ 7056 7057 list_add_tail_rcu(&sch->all, &scx_sched_all); 7058 } 7059 7060 refresh_watchdog(); 7061 return 0; 7062 } 7063 7064 void scx_unlink_sched(struct scx_sched *sch) 7065 { 7066 scoped_guard(raw_spinlock_irq, &scx_sched_lock) { 7067 #ifdef CONFIG_EXT_SUB_SCHED 7068 if (sch->linked) { 7069 rhashtable_remove_fast(&scx_sched_hash, &sch->hash_node, 7070 scx_sched_hash_params); 7071 list_del_rcu(&sch->sibling); 7072 sch->linked = false; 7073 } 7074 #endif /* CONFIG_EXT_SUB_SCHED */ 7075 list_del_rcu(&sch->all); 7076 } 7077 7078 refresh_watchdog(); 7079 } 7080 7081 /* 7082 * Called to disable future dumps and wait for in-progress one while disabling 7083 * @sch. Once @sch becomes empty during disable, there's no point in dumping it. 7084 * This prevents calling dump ops on a dead sch. 7085 */ 7086 void scx_disable_dump(struct scx_sched *sch) 7087 { 7088 guard(raw_spinlock_irqsave)(&scx_dump_lock); 7089 sch->dump_disabled = true; 7090 } 7091 7092 void scx_log_sched_disable(struct scx_sched *sch) 7093 { 7094 struct scx_exit_info *ei = sch->exit_info; 7095 const char *type = scx_parent(sch) ? "sub-scheduler" : "scheduler"; 7096 7097 if (ei->kind >= SCX_EXIT_ERROR) { 7098 pr_err("sched_ext: BPF %s \"%s\" disabled (%s)\n", type, 7099 sch->ops.name, ei->reason); 7100 7101 if (ei->msg[0] != '\0') 7102 pr_err("sched_ext: %s: %s\n", sch->ops.name, ei->msg); 7103 #ifdef CONFIG_STACKTRACE 7104 stack_trace_print(ei->bt, ei->bt_len, 2); 7105 #endif 7106 } else { 7107 pr_info("sched_ext: BPF %s \"%s\" disabled (%s)\n", type, 7108 sch->ops.name, ei->reason); 7109 } 7110 } 7111 7112 static void scx_root_disable(struct scx_sched *sch) 7113 { 7114 struct scx_task_iter sti; 7115 struct task_struct *p; 7116 bool was_switched_all; 7117 int cpu; 7118 7119 /* guarantee forward progress and wait for descendants to be disabled */ 7120 scx_bypass(sch, true); 7121 drain_descendants(sch); 7122 7123 switch (scx_set_enable_state(SCX_DISABLING)) { 7124 case SCX_DISABLING: 7125 WARN_ONCE(true, "sched_ext: duplicate disabling instance?"); 7126 break; 7127 case SCX_DISABLED: 7128 pr_warn("sched_ext: ops error detected without ops (%s)\n", 7129 sch->exit_info->msg); 7130 WARN_ON_ONCE(scx_set_enable_state(SCX_DISABLED) != SCX_DISABLING); 7131 goto done; 7132 default: 7133 break; 7134 } 7135 7136 /* 7137 * Here, every runnable task is guaranteed to make forward progress and 7138 * we can safely use blocking synchronization constructs. Actually 7139 * disable ops. 7140 */ 7141 mutex_lock(&scx_enable_mutex); 7142 7143 was_switched_all = scx_switched_all(); 7144 7145 static_branch_disable(&__scx_switched_all); 7146 WRITE_ONCE(scx_switching_all, false); 7147 7148 /* 7149 * Shut down cgroup support before tasks so that the cgroup attach and 7150 * migration paths don't race against scx_disable_and_exit_task(). 7151 */ 7152 scx_cgroup_lock(); 7153 scx_cgroup_enabled = false; 7154 scx_cgroup_exit(sch); 7155 scx_cgroup_unlock(); 7156 7157 /* 7158 * The BPF scheduler is going away. All tasks including %TASK_DEAD ones 7159 * must be switched out and exited synchronously. 7160 */ 7161 percpu_down_write(&scx_fork_rwsem); 7162 7163 scx_init_task_enabled = false; 7164 7165 scx_task_iter_start(&sti, NULL); 7166 while ((p = scx_task_iter_next_locked(&sti))) { 7167 unsigned int queue_flags = DEQUEUE_SAVE | DEQUEUE_MOVE | DEQUEUE_NOCLOCK; 7168 const struct sched_class *old_class = p->sched_class; 7169 const struct sched_class *new_class = scx_setscheduler_class(p); 7170 7171 update_rq_clock(task_rq(p)); 7172 7173 if (old_class != new_class) 7174 queue_flags |= DEQUEUE_CLASS; 7175 7176 scoped_guard (sched_change, p, queue_flags) { 7177 p->sched_class = new_class; 7178 } 7179 7180 scx_disable_and_exit_task(scx_task_sched(p), p); 7181 } 7182 scx_task_iter_stop(&sti); 7183 7184 scx_disable_dump(sch); 7185 7186 scx_cgroup_lock(); 7187 set_cgroup_sched(sch_cgroup(sch), NULL); 7188 scx_cgroup_unlock(); 7189 7190 percpu_up_write(&scx_fork_rwsem); 7191 7192 /* 7193 * Re-balance the dl_server bandwidth reservations: detach ext_server 7194 * (no more sched_ext tasks) and reinstate fair_server if it was 7195 * previously detached because we were running in full mode. 7196 * 7197 * Unlike the enable path, this runs on a recovery path that cannot 7198 * fail, so we use dl_server_swap_bw() to atomically free ext_server's 7199 * bandwidth and reclaim it for fair_server under the same dl_b lock. 7200 * 7201 * The swap can still fail with -EBUSY if someone bumped ext_server's 7202 * runtime via debugfs between enable and disable; in that narrow case 7203 * both servers end up detached and we just WARN. 7204 */ 7205 for_each_possible_cpu(cpu) { 7206 struct rq *rq = cpu_rq(cpu); 7207 7208 scoped_guard(rq_lock_irqsave, rq) { 7209 update_rq_clock(rq); 7210 if (was_switched_all) { 7211 if (WARN_ON_ONCE(dl_server_swap_bw(&rq->ext_server, 7212 &rq->fair_server))) 7213 pr_warn("failed to re-attach fair_server on CPU %d\n", cpu); 7214 } else { 7215 dl_server_detach_bw(&rq->ext_server); 7216 } 7217 } 7218 } 7219 7220 scx_ops_cid_sched_updated_disable(sch); 7221 7222 /* no task is on scx, turn off all the switches and flush in-progress calls */ 7223 static_branch_disable(&__scx_enabled); 7224 static_branch_disable(&__scx_is_cid_type); 7225 if (sch->ops.flags & SCX_OPS_TID_TO_TASK) 7226 static_branch_disable(&__scx_tid_to_task_enabled); 7227 bitmap_zero(sch->has_op, SCX_OPI_END); 7228 scx_idle_disable(); 7229 synchronize_rcu(); 7230 if (sch->ops.flags & SCX_OPS_TID_TO_TASK) 7231 rhashtable_free_and_destroy(&scx_tid_hash, NULL, NULL); 7232 7233 scx_log_sched_disable(sch); 7234 7235 if (sch->ops.exit) 7236 SCX_CALL_OP(sch, exit, NULL, sch->exit_info); 7237 7238 /* 7239 * @sch's non-ops programs such as timers and tracers can fire after 7240 * ops.exit(). Now that exit is complete, stop scx_prog_sched() from 7241 * resolving to @sch and drain in-flight resolvers. 7242 */ 7243 WRITE_ONCE(sch->dead, true); 7244 synchronize_rcu(); 7245 7246 scx_unlink_sched(sch); 7247 7248 /* 7249 * scx_root clearing and cid table retirement must be inside 7250 * cpus_read_lock(). See handle_hotplug(). 7251 */ 7252 cpus_read_lock(); 7253 RCU_INIT_POINTER(scx_root, NULL); 7254 scx_cid_retire_tables(); 7255 cpus_read_unlock(); 7256 7257 /* 7258 * Delete the kobject from the hierarchy synchronously. Otherwise, sysfs 7259 * could observe an object of the same name still in the hierarchy when 7260 * the next scheduler is loaded. 7261 */ 7262 #ifdef CONFIG_EXT_SUB_SCHED 7263 if (sch->sub_kset) 7264 kobject_del(&sch->sub_kset->kobj); 7265 #endif 7266 /* not added if enable failed before scx_sched_sysfs_add() */ 7267 if (sch->kobj.state_in_sysfs) 7268 kobject_del(&sch->kobj); 7269 7270 free_kick_syncs(); 7271 7272 mutex_unlock(&scx_enable_mutex); 7273 7274 WARN_ON_ONCE(scx_set_enable_state(SCX_DISABLED) != SCX_DISABLING); 7275 done: 7276 scx_bypass(sch, false); 7277 } 7278 7279 /** 7280 * scx_propagate_exit_irq_workfn - Claim SCX_EXIT_PARENT on the exiting subtree 7281 * @irq_work: &scx_sched.propagate_exit_irq_work 7282 * 7283 * Queued by scx_claim_exit() after a non-PARENT claim. Claims SCX_EXIT_PARENT 7284 * on each descendant, giving every one its own disable work - most of disabling 7285 * is serialized but ops.exit() can take arbitrarily long and running them in 7286 * separate helper kthreads parallelizes it. No recursion as only non-PARENT 7287 * claims propagate. 7288 */ 7289 static void scx_propagate_exit_irq_workfn(struct irq_work *irq_work) 7290 { 7291 struct scx_sched *sch = container_of(irq_work, struct scx_sched, 7292 propagate_exit_irq_work); 7293 struct scx_sched *pos; 7294 7295 scoped_guard (raw_spinlock_irqsave, &scx_sched_lock) { 7296 scx_for_each_descendant_pre(pos, sch) 7297 scx_disable(pos, SCX_EXIT_PARENT); 7298 } 7299 } 7300 7301 /* 7302 * Claim the exit on @sch. The caller must ensure that the helper kthread work 7303 * is kicked before the current task can be preempted. Once exit_kind is 7304 * claimed, scx_error() can no longer trigger, so if the current task gets 7305 * preempted and the BPF scheduler fails to schedule it back, the helper work 7306 * will never be kicked and the whole system can wedge. 7307 * 7308 * Lock-free and safe to call from any context including NMI. 7309 */ 7310 static bool scx_claim_exit(struct scx_sched *sch, enum scx_exit_kind kind) 7311 { 7312 int none = SCX_EXIT_NONE; 7313 7314 lockdep_assert_preemption_disabled(); 7315 7316 if (WARN_ON_ONCE(kind == SCX_EXIT_NONE || kind == SCX_EXIT_DONE)) 7317 kind = SCX_EXIT_ERROR; 7318 7319 if (!atomic_try_cmpxchg(&sch->exit_kind, &none, kind)) 7320 return false; 7321 7322 if (kind == SCX_EXIT_PARENT) { 7323 /* an ancestor is already sweeping the subtree */ 7324 WRITE_ONCE(sch->aborting, true); 7325 } else { 7326 struct scx_sched *pos; 7327 7328 /* 7329 * CPUs may be live-locked in the dispatch paths of @sch or its 7330 * descendants, which ->aborting breaks. Sweep the subtree 7331 * locklessly so that this works from NMI. smp_store_mb() orders 7332 * each node's ->aborting store before its children are walked - 7333 * either we see a racing scx_link_sched() on ->children or it 7334 * sees ->aborting. 7335 */ 7336 scoped_guard (rcu) { 7337 scx_for_each_descendant_pre(pos, sch) 7338 smp_store_mb(pos->aborting, true); 7339 } 7340 7341 irq_work_queue(&sch->propagate_exit_irq_work); 7342 } 7343 7344 /* fired after ->aborting is set so callbacks can't delay recovery */ 7345 trace_sched_ext_exit(sch, kind); 7346 7347 return true; 7348 } 7349 7350 static void scx_disable_workfn(struct kthread_work *work) 7351 { 7352 struct scx_sched *sch = container_of(work, struct scx_sched, disable_work); 7353 struct scx_exit_info *ei = sch->exit_info; 7354 int kind; 7355 7356 kind = atomic_read(&sch->exit_kind); 7357 while (true) { 7358 if (kind == SCX_EXIT_DONE) /* already disabled? */ 7359 return; 7360 WARN_ON_ONCE(kind == SCX_EXIT_NONE); 7361 if (atomic_try_cmpxchg(&sch->exit_kind, &kind, SCX_EXIT_DONE)) 7362 break; 7363 } 7364 ei->kind = kind; 7365 ei->reason = scx_exit_reason(ei->kind); 7366 7367 if (scx_parent(sch)) 7368 scx_sub_disable(sch); 7369 else 7370 scx_root_disable(sch); 7371 } 7372 7373 static void scx_disable(struct scx_sched *sch, enum scx_exit_kind kind) 7374 { 7375 guard(preempt)(); 7376 if (scx_claim_exit(sch, kind)) 7377 irq_work_queue(&sch->disable_irq_work); 7378 } 7379 7380 /** 7381 * scx_flush_disable_work - flush the disable work and wait for it to finish 7382 * @sch: the scheduler 7383 * 7384 * sch->disable_work might still not queued, causing kthread_flush_work() 7385 * as a noop. Syncing the irq_work first is required to guarantee the 7386 * kthread work has been queued before waiting for it. 7387 */ 7388 void scx_flush_disable_work(struct scx_sched *sch) 7389 { 7390 int kind; 7391 7392 do { 7393 irq_work_sync(&sch->disable_irq_work); 7394 kthread_flush_work(&sch->disable_work); 7395 kind = atomic_read(&sch->exit_kind); 7396 } while (kind != SCX_EXIT_NONE && kind != SCX_EXIT_DONE); 7397 } 7398 7399 static void dump_newline(struct seq_buf *s) 7400 { 7401 trace_sched_ext_dump(""); 7402 7403 /* @s may be zero sized and seq_buf triggers WARN if so */ 7404 if (s->size) 7405 seq_buf_putc(s, '\n'); 7406 } 7407 7408 __printf(2, 3) void scx_dump_line(struct seq_buf *s, const char *fmt, ...) 7409 { 7410 va_list args; 7411 7412 #ifdef CONFIG_TRACEPOINTS 7413 if (trace_sched_ext_dump_enabled()) { 7414 /* protected by scx_dump_lock */ 7415 static char line_buf[SCX_EXIT_MSG_LEN]; 7416 7417 va_start(args, fmt); 7418 vscnprintf(line_buf, sizeof(line_buf), fmt, args); 7419 va_end(args); 7420 7421 trace_call__sched_ext_dump(line_buf); 7422 } 7423 #endif 7424 /* @s may be zero sized and seq_buf triggers WARN if so */ 7425 if (s->size) { 7426 va_start(args, fmt); 7427 seq_buf_vprintf(s, fmt, args); 7428 va_end(args); 7429 7430 seq_buf_putc(s, '\n'); 7431 } 7432 } 7433 7434 static void dump_stack_trace(struct seq_buf *s, const char *prefix, 7435 const unsigned long *bt, unsigned int len) 7436 { 7437 unsigned int i; 7438 7439 for (i = 0; i < len; i++) 7440 scx_dump_line(s, "%s%pS", prefix, (void *)bt[i]); 7441 } 7442 7443 static void ops_dump_init(struct seq_buf *s, const char *prefix) 7444 { 7445 struct scx_dump_data *dd = &scx_dump_data; 7446 7447 lockdep_assert_irqs_disabled(); 7448 7449 dd->cpu = smp_processor_id(); /* allow scx_bpf_dump() */ 7450 dd->first = true; 7451 dd->cursor = 0; 7452 dd->s = s; 7453 dd->prefix = prefix; 7454 } 7455 7456 static void ops_dump_flush(void) 7457 { 7458 struct scx_dump_data *dd = &scx_dump_data; 7459 char *line = dd->buf.line; 7460 7461 if (!dd->cursor) 7462 return; 7463 7464 /* 7465 * There's something to flush and this is the first line. Insert a blank 7466 * line to distinguish ops dump. 7467 */ 7468 if (dd->first) { 7469 dump_newline(dd->s); 7470 dd->first = false; 7471 } 7472 7473 /* 7474 * There may be multiple lines in $line. Scan and emit each line 7475 * separately. 7476 */ 7477 while (true) { 7478 char *end = line; 7479 char c; 7480 7481 while (*end != '\n' && *end != '\0') 7482 end++; 7483 7484 /* 7485 * If $line overflowed, it may not have newline at the end. 7486 * Always emit with a newline. 7487 */ 7488 c = *end; 7489 *end = '\0'; 7490 scx_dump_line(dd->s, "%s%s", dd->prefix, line); 7491 if (c == '\0') 7492 break; 7493 7494 /* move to the next line */ 7495 end++; 7496 if (*end == '\0') 7497 break; 7498 line = end; 7499 } 7500 7501 dd->cursor = 0; 7502 } 7503 7504 static void ops_dump_exit(void) 7505 { 7506 ops_dump_flush(); 7507 scx_dump_data.cpu = -1; 7508 } 7509 7510 static void scx_dump_task(struct scx_sched *sch, struct seq_buf *s, struct scx_dump_ctx *dctx, 7511 struct rq *rq, struct task_struct *p, char marker) 7512 { 7513 static unsigned long bt[SCX_EXIT_BT_LEN]; 7514 struct scx_sched *task_sch = scx_task_sched(p); 7515 const char *own_marker; 7516 char sch_id_buf[32]; 7517 char dsq_id_buf[19] = "(n/a)"; 7518 unsigned long ops_state = atomic_long_read(&p->scx.ops_state); 7519 unsigned int bt_len = 0; 7520 7521 own_marker = task_sch == sch ? "*" : ""; 7522 7523 if (task_sch->level == 0) 7524 scnprintf(sch_id_buf, sizeof(sch_id_buf), "root"); 7525 else 7526 scnprintf(sch_id_buf, sizeof(sch_id_buf), "sub%d-%llu", 7527 task_sch->level, task_sch->ops.sub_cgroup_id); 7528 7529 if (p->scx.dsq) 7530 scnprintf(dsq_id_buf, sizeof(dsq_id_buf), "0x%llx", 7531 (unsigned long long)p->scx.dsq->id); 7532 7533 dump_newline(s); 7534 scx_dump_line(s, " %c%c %s[%d] %s%s %+ldms", 7535 marker, task_state_to_char(p), p->comm, p->pid, own_marker, sch_id_buf, 7536 jiffies_delta_msecs(p->scx.runnable_at, dctx->at_jiffies)); 7537 scx_dump_line(s, " scx_state/flags=%u/0x%x dsq_flags=0x%x ops_state/qseq=%lu/%lu", 7538 scx_get_task_state(p) >> SCX_TASK_STATE_SHIFT, 7539 p->scx.flags & ~SCX_TASK_STATE_MASK, p->scx.dsq_flags, 7540 ops_state & SCX_OPSS_STATE_MASK, ops_state >> SCX_OPSS_QSEQ_SHIFT); 7541 scx_dump_line(s, " sticky/holding_cpu=%d/%d dsq_id=%s", 7542 p->scx.sticky_cpu, p->scx.holding_cpu, dsq_id_buf); 7543 scx_dump_line(s, " dsq_vtime=%llu slice=%llu weight=%u", 7544 p->scx.dsq_vtime, p->scx.slice, p->scx.weight); 7545 scx_dump_line(s, " cpus=%*pb no_mig=%u", cpumask_pr_args(p->cpus_ptr), 7546 p->migration_disabled); 7547 7548 if (SCX_HAS_OP(sch, dump_task)) { 7549 ops_dump_init(s, " "); 7550 SCX_CALL_OP(sch, dump_task, rq, dctx, p); 7551 ops_dump_exit(); 7552 } 7553 7554 #ifdef CONFIG_STACKTRACE 7555 bt_len = stack_trace_save_tsk(p, bt, SCX_EXIT_BT_LEN, 1); 7556 #endif 7557 if (bt_len) { 7558 dump_newline(s); 7559 dump_stack_trace(s, " ", bt, bt_len); 7560 } 7561 } 7562 7563 static void scx_dump_cpu(struct scx_sched *sch, struct seq_buf *s, 7564 struct scx_dump_ctx *dctx, int cpu, 7565 bool dump_all_tasks) 7566 { 7567 struct rq *rq = cpu_rq(cpu); 7568 struct scx_sched_pcpu *pcpu = per_cpu_ptr(sch->pcpu, cpu); 7569 struct rq_flags rf; 7570 struct task_struct *p; 7571 struct seq_buf ns; 7572 size_t avail, used; 7573 char *buf; 7574 bool idle; 7575 7576 rq_lock_irqsave(rq, &rf); 7577 7578 idle = list_empty(&rq->scx.runnable_list) && 7579 rq->curr->sched_class == &idle_sched_class; 7580 7581 if (idle && !SCX_HAS_OP(sch, dump_cpu)) 7582 goto next; 7583 7584 /* 7585 * We don't yet know whether ops.dump_cpu() will produce output 7586 * and we may want to skip the default CPU dump if it doesn't. 7587 * Use a nested seq_buf to generate the standard dump so that we 7588 * can decide whether to commit later. 7589 */ 7590 avail = seq_buf_get_buf(s, &buf); 7591 seq_buf_init(&ns, buf, avail); 7592 7593 dump_newline(&ns); 7594 scx_dump_line(&ns, "CPU %-4d: nr_run=%u flags=0x%x cpu_rel=%d ksync=%lu", 7595 cpu, rq->scx.nr_running, rq->scx.flags, rq->scx.cpu_released, 7596 rq->scx.kick_sync); 7597 scx_rescue_dump(&ns, rq); 7598 scx_dump_line(&ns, " curr=%s[%d] class=%ps", 7599 rq->curr->comm, rq->curr->pid, rq->curr->sched_class); 7600 scx_dump_line(&ns, " donor=%s[%d] class=%ps", 7601 rq->donor->comm, rq->donor->pid, rq->donor->sched_class); 7602 if (!cpumask_empty(pcpu->cpus_to_kick)) 7603 scx_dump_line(&ns, " cpus_to_kick : %*pb", 7604 cpumask_pr_args(pcpu->cpus_to_kick)); 7605 if (!cpumask_empty(pcpu->cpus_to_kick_if_idle)) 7606 scx_dump_line(&ns, " idle_to_kick : %*pb", 7607 cpumask_pr_args(pcpu->cpus_to_kick_if_idle)); 7608 if (!cpumask_empty(pcpu->cpus_to_preempt)) 7609 scx_dump_line(&ns, " cpus_to_preempt: %*pb", 7610 cpumask_pr_args(pcpu->cpus_to_preempt)); 7611 if (!cpumask_empty(pcpu->cpus_to_preempt_lazy)) 7612 scx_dump_line(&ns, " preempt_lazy : %*pb", 7613 cpumask_pr_args(pcpu->cpus_to_preempt_lazy)); 7614 if (!cpumask_empty(pcpu->cpus_to_wait)) 7615 scx_dump_line(&ns, " cpus_to_wait : %*pb", 7616 cpumask_pr_args(pcpu->cpus_to_wait)); 7617 if (!cpumask_empty(rq->scx.cpus_to_sync)) 7618 scx_dump_line(&ns, " cpus_to_sync : %*pb", 7619 cpumask_pr_args(rq->scx.cpus_to_sync)); 7620 7621 used = seq_buf_used(&ns); 7622 if (SCX_HAS_OP(sch, dump_cpu)) { 7623 ops_dump_init(&ns, " "); 7624 SCX_CALL_OP(sch, dump_cpu, rq, dctx, scx_cpu_arg(cpu), idle); 7625 ops_dump_exit(); 7626 } 7627 7628 /* 7629 * If idle && nothing generated by ops.dump_cpu(), there's 7630 * nothing interesting. Skip. 7631 */ 7632 if (idle && used == seq_buf_used(&ns)) 7633 goto next; 7634 7635 /* 7636 * $s may already have overflowed when $ns was created. If so, 7637 * calling commit on it will trigger BUG. 7638 */ 7639 if (avail) { 7640 seq_buf_commit(s, seq_buf_used(&ns)); 7641 if (seq_buf_has_overflowed(&ns)) 7642 seq_buf_set_overflow(s); 7643 } 7644 7645 if (rq->curr->sched_class == &ext_sched_class && 7646 (dump_all_tasks || scx_task_on_sched(sch, rq->curr))) 7647 scx_dump_task(sch, s, dctx, rq, rq->curr, '*'); 7648 if (rq->donor != rq->curr && 7649 rq->donor->sched_class == &ext_sched_class && 7650 (dump_all_tasks || scx_task_on_sched(sch, rq->donor))) 7651 scx_dump_task(sch, s, dctx, rq, rq->donor, ' '); 7652 7653 list_for_each_entry(p, &rq->scx.runnable_list, scx.runnable_node) 7654 if (dump_all_tasks || scx_task_on_sched(sch, p)) 7655 scx_dump_task(sch, s, dctx, rq, p, ' '); 7656 next: 7657 rq_unlock_irqrestore(rq, &rf); 7658 } 7659 7660 /* 7661 * Dump scheduler state. If @dump_all_tasks is true, dump all tasks regardless 7662 * of which scheduler they belong to. If false, only dump tasks owned by @sch. 7663 * For SysRq-D dumps, @dump_all_tasks=false since all schedulers are dumped 7664 * separately. For error dumps, @dump_all_tasks=true since only the failing 7665 * scheduler is dumped. 7666 */ 7667 static void scx_dump_state(struct scx_sched *sch, struct scx_exit_info *ei, 7668 size_t dump_len, bool dump_all_tasks) 7669 { 7670 static const char trunc_marker[] = "\n\n~~~~ TRUNCATED ~~~~\n"; 7671 struct scx_dump_ctx dctx = { 7672 .kind = ei->kind, 7673 .exit_code = ei->exit_code, 7674 .reason = ei->reason, 7675 .at_ns = ktime_get_ns(), 7676 .at_jiffies = jiffies, 7677 }; 7678 struct seq_buf s; 7679 struct scx_event_stats events; 7680 int cpu; 7681 7682 guard(raw_spinlock_irqsave)(&scx_dump_lock); 7683 7684 if (sch->dump_disabled) 7685 return; 7686 7687 seq_buf_init(&s, ei->dump, dump_len); 7688 7689 #ifdef CONFIG_EXT_SUB_SCHED 7690 if (sch->level == 0) 7691 scx_dump_line(&s, "%s: root", sch->ops.name); 7692 else 7693 scx_dump_line(&s, "%s: sub%d-%llu %s", 7694 sch->ops.name, sch->level, sch->ops.sub_cgroup_id, 7695 sch->cgrp_path); 7696 #endif 7697 if (ei->kind == SCX_EXIT_NONE) { 7698 scx_dump_line(&s, "Debug dump triggered by %s", ei->reason); 7699 } else { 7700 if (ei->exit_cpu >= 0) 7701 scx_dump_line(&s, "%s[%d] triggered exit kind %d on CPU %d:", 7702 current->comm, current->pid, ei->kind, 7703 ei->exit_cpu); 7704 else 7705 scx_dump_line(&s, "%s[%d] triggered exit kind %d:", 7706 current->comm, current->pid, ei->kind); 7707 scx_dump_line(&s, " %s (%s)", ei->reason, ei->msg); 7708 dump_newline(&s); 7709 scx_dump_line(&s, "Backtrace:"); 7710 dump_stack_trace(&s, " ", ei->bt, ei->bt_len); 7711 } 7712 7713 if (SCX_HAS_OP(sch, dump)) { 7714 ops_dump_init(&s, ""); 7715 SCX_CALL_OP(sch, dump, NULL, &dctx); 7716 ops_dump_exit(); 7717 } 7718 7719 dump_newline(&s); 7720 scx_dump_line(&s, "CPU states"); 7721 scx_dump_line(&s, "----------"); 7722 7723 /* 7724 * Dump stalled CPUs first so they aren't lost to dump truncation, then 7725 * walk the rest in order. Fall back to exit_cpu if no stall mask set. 7726 */ 7727 if (!cpumask_empty(sch->stall_cpus)) { 7728 for_each_cpu(cpu, sch->stall_cpus) 7729 scx_dump_cpu(sch, &s, &dctx, cpu, dump_all_tasks); 7730 for_each_possible_cpu(cpu) { 7731 if (!cpumask_test_cpu(cpu, sch->stall_cpus)) 7732 scx_dump_cpu(sch, &s, &dctx, cpu, dump_all_tasks); 7733 } 7734 } else { 7735 if (ei->exit_cpu >= 0) 7736 scx_dump_cpu(sch, &s, &dctx, ei->exit_cpu, dump_all_tasks); 7737 for_each_possible_cpu(cpu) { 7738 if (cpu != ei->exit_cpu) 7739 scx_dump_cpu(sch, &s, &dctx, cpu, dump_all_tasks); 7740 } 7741 } 7742 7743 dump_newline(&s); 7744 scx_dump_line(&s, "Event counters"); 7745 scx_dump_line(&s, "--------------"); 7746 7747 scx_read_events(sch, &events); 7748 #define SCX_EVENT(name) scx_dump_event(s, &events, name) 7749 SCX_EVENTS_LIST(SCX_EVENT); 7750 #undef SCX_EVENT 7751 7752 if (seq_buf_has_overflowed(&s) && dump_len >= sizeof(trunc_marker)) 7753 memcpy(ei->dump + dump_len - sizeof(trunc_marker), 7754 trunc_marker, sizeof(trunc_marker)); 7755 } 7756 7757 static void scx_disable_irq_workfn(struct irq_work *irq_work) 7758 { 7759 struct scx_sched *sch = container_of(irq_work, struct scx_sched, disable_irq_work); 7760 struct scx_exit_info *ei = sch->exit_info; 7761 7762 if (ei->kind >= SCX_EXIT_ERROR) 7763 scx_dump_state(sch, ei, sch->ops.exit_dump_len, true); 7764 7765 kthread_queue_work(sch->helper, &sch->disable_work); 7766 } 7767 7768 /* finish exit_info and kick the disable work, ei->msg must already be set */ 7769 static void scx_finish_exit(struct scx_sched *sch, enum scx_exit_kind kind, 7770 s64 exit_code, s32 exit_cpu) 7771 { 7772 struct scx_exit_info *ei = sch->exit_info; 7773 7774 ei->exit_code = exit_code; 7775 #ifdef CONFIG_STACKTRACE 7776 /* 7777 * stack_trace_save()'s NMI-safety is arch-dependent and undocumented. 7778 * Skip the backtrace when exiting from NMI. 7779 */ 7780 if (kind >= SCX_EXIT_ERROR && !in_nmi()) 7781 ei->bt_len = stack_trace_save(ei->bt, SCX_EXIT_BT_LEN, 1); 7782 #endif 7783 /* 7784 * Set ei->kind and ->reason for scx_dump_state(). They'll be set again 7785 * in scx_disable_workfn(). 7786 */ 7787 ei->kind = kind; 7788 ei->reason = scx_exit_reason(ei->kind); 7789 ei->exit_cpu = exit_cpu; 7790 7791 irq_work_queue(&sch->disable_irq_work); 7792 } 7793 7794 bool scx_vexit(struct scx_sched *sch, 7795 enum scx_exit_kind kind, s64 exit_code, s32 exit_cpu, 7796 const char *fmt, va_list args) 7797 { 7798 struct scx_exit_info *ei = sch->exit_info; 7799 7800 guard(preempt)(); 7801 7802 if (!scx_claim_exit(sch, kind)) 7803 return false; 7804 7805 vscnprintf(ei->msg, SCX_EXIT_MSG_LEN, fmt, args); 7806 7807 scx_finish_exit(sch, kind, exit_code, exit_cpu); 7808 return true; 7809 } 7810 7811 static int alloc_kick_syncs(void) 7812 { 7813 int cpu; 7814 7815 /* 7816 * Allocate per-CPU arrays sized by nr_cpu_ids. Use kvzalloc as size 7817 * can exceed percpu allocator limits on large machines. 7818 */ 7819 for_each_possible_cpu(cpu) { 7820 struct scx_kick_syncs __rcu **ksyncs = per_cpu_ptr(&scx_kick_syncs, cpu); 7821 struct scx_kick_syncs *new_ksyncs; 7822 7823 WARN_ON_ONCE(rcu_access_pointer(*ksyncs)); 7824 7825 new_ksyncs = kvzalloc_node(struct_size(new_ksyncs, syncs, nr_cpu_ids), 7826 GFP_KERNEL, cpu_to_node(cpu)); 7827 if (!new_ksyncs) { 7828 free_kick_syncs(); 7829 return -ENOMEM; 7830 } 7831 7832 rcu_assign_pointer(*ksyncs, new_ksyncs); 7833 } 7834 7835 return 0; 7836 } 7837 7838 static void free_pnode(struct scx_sched_pnode *pnode) 7839 { 7840 if (!pnode) 7841 return; 7842 exit_dsq(&pnode->global_dsq); 7843 kfree(pnode); 7844 } 7845 7846 static struct scx_sched_pnode *alloc_pnode(struct scx_sched *sch, int node) 7847 { 7848 struct scx_sched_pnode *pnode; 7849 7850 pnode = kzalloc_node(sizeof(*pnode), GFP_KERNEL, node); 7851 if (!pnode) 7852 return NULL; 7853 7854 if (scx_init_dsq(&pnode->global_dsq, SCX_DSQ_GLOBAL, sch)) { 7855 kfree(pnode); 7856 return NULL; 7857 } 7858 7859 return pnode; 7860 } 7861 7862 /* 7863 * Allocate and initialize a new scx_sched. @cgrp's reference is always 7864 * consumed whether the function succeeds or fails. 7865 */ 7866 struct scx_sched *scx_alloc_and_add_sched(struct scx_enable_cmd *cmd, 7867 struct cgroup *cgrp, 7868 struct scx_sched *parent) 7869 { 7870 struct sched_ext_ops *ops = cmd->ops; 7871 struct scx_sched *sch; 7872 s32 level = parent ? parent->level + 1 : 0; 7873 s32 node, cpu, ret, bypass_fail_cpu = nr_cpu_ids; 7874 7875 sch = kzalloc_flex(*sch, ancestors, level + 1); 7876 if (!sch) { 7877 ret = -ENOMEM; 7878 goto err_put_cgrp; 7879 } 7880 7881 sch->exit_info = alloc_exit_info(ops->exit_dump_len); 7882 if (!sch->exit_info) { 7883 ret = -ENOMEM; 7884 goto err_free_sch; 7885 } 7886 7887 ret = rhashtable_init(&sch->dsq_hash, &dsq_hash_params); 7888 if (ret < 0) 7889 goto err_free_ei; 7890 7891 sch->pnode = kzalloc_objs(sch->pnode[0], nr_node_ids); 7892 if (!sch->pnode) { 7893 ret = -ENOMEM; 7894 goto err_free_hash; 7895 } 7896 7897 for_each_node_state(node, N_POSSIBLE) { 7898 sch->pnode[node] = alloc_pnode(sch, node); 7899 if (!sch->pnode[node]) { 7900 ret = -ENOMEM; 7901 goto err_free_pnode; 7902 } 7903 } 7904 7905 sch->dsp_max_batch = ops->dispatch_max_batch ?: SCX_DSP_DFL_MAX_BATCH; 7906 sch->pcpu = __alloc_percpu(struct_size_t(struct scx_sched_pcpu, 7907 dsp_ctx.buf, sch->dsp_max_batch), 7908 __alignof__(struct scx_sched_pcpu)); 7909 if (!sch->pcpu) { 7910 ret = -ENOMEM; 7911 goto err_free_pnode; 7912 } 7913 7914 for_each_possible_cpu(cpu) { 7915 ret = scx_init_dsq(scx_bypass_dsq(sch, cpu), SCX_DSQ_BYPASS, sch); 7916 if (ret) { 7917 bypass_fail_cpu = cpu; 7918 goto err_free_pcpu; 7919 } 7920 } 7921 7922 for_each_possible_cpu(cpu) { 7923 struct scx_sched_pcpu *pcpu = per_cpu_ptr(sch->pcpu, cpu); 7924 7925 node = cpu_to_node(cpu); 7926 pcpu->sch = sch; 7927 INIT_LIST_HEAD(&pcpu->deferred_reenq_local.node); 7928 #ifdef CONFIG_EXT_SUB_SCHED 7929 init_llist_node(&pcpu->ecaps_to_sync_node); 7930 #endif 7931 INIT_LIST_HEAD(&pcpu->to_kick_node); 7932 if (!zalloc_cpumask_var_node(&pcpu->cpus_to_kick, GFP_KERNEL, node) || 7933 !zalloc_cpumask_var_node(&pcpu->cpus_to_kick_if_idle, GFP_KERNEL, node) || 7934 !zalloc_cpumask_var_node(&pcpu->cpus_to_preempt, GFP_KERNEL, node) || 7935 !zalloc_cpumask_var_node(&pcpu->cpus_to_preempt_lazy, GFP_KERNEL, node) || 7936 !zalloc_cpumask_var_node(&pcpu->cpus_to_wait, GFP_KERNEL, node)) { 7937 ret = -ENOMEM; 7938 goto err_free_pcpu; 7939 } 7940 } 7941 7942 sch->helper = kthread_run_worker(0, "sched_ext_helper"); 7943 if (IS_ERR(sch->helper)) { 7944 ret = PTR_ERR(sch->helper); 7945 goto err_free_pcpu; 7946 } 7947 7948 sched_set_fifo(sch->helper->task); 7949 7950 if (parent) 7951 memcpy(sch->ancestors, parent->ancestors, 7952 level * sizeof(parent->ancestors[0])); 7953 sch->ancestors[level] = sch; 7954 sch->level = level; 7955 sch->id = atomic64_inc_return(&scx_sched_id_cursor); 7956 7957 if (ops->timeout_ms) 7958 sch->watchdog_timeout = msecs_to_jiffies(ops->timeout_ms); 7959 else 7960 sch->watchdog_timeout = SCX_WATCHDOG_MAX_TIMEOUT; 7961 7962 sch->slice_dfl = SCX_SLICE_DFL; 7963 atomic_set(&sch->exit_kind, SCX_EXIT_NONE); 7964 sch->disable_irq_work = IRQ_WORK_INIT_HARD(scx_disable_irq_workfn); 7965 sch->propagate_exit_irq_work = IRQ_WORK_INIT_HARD(scx_propagate_exit_irq_workfn); 7966 kthread_init_work(&sch->disable_work, scx_disable_workfn); 7967 timer_setup(&sch->bypass_lb_timer, scx_bypass_lb_timerfn, 0); 7968 7969 if (!alloc_cpumask_var(&sch->bypass_lb_donee_cpumask, GFP_KERNEL)) { 7970 ret = -ENOMEM; 7971 goto err_stop_helper; 7972 } 7973 if (!alloc_cpumask_var(&sch->bypass_lb_resched_cpumask, GFP_KERNEL)) { 7974 ret = -ENOMEM; 7975 goto err_free_lb_cpumask; 7976 } 7977 if (!zalloc_cpumask_var(&sch->stall_cpus, GFP_KERNEL)) { 7978 ret = -ENOMEM; 7979 goto err_free_lb_resched_cpumask; 7980 } 7981 /* 7982 * Copy ops through the right union view. For cid-form the source is 7983 * struct sched_ext_ops_cid which lacks the trailing cpu_acquire/ 7984 * cpu_release; those stay zero from kzalloc. 7985 */ 7986 if (cmd->is_cid_type) { 7987 sch->ops_cid = *cmd->ops_cid; 7988 sch->is_cid_type = true; 7989 } else { 7990 sch->ops = *cmd->ops; 7991 } 7992 7993 #ifdef CONFIG_EXT_SUB_SCHED 7994 char *buf = kzalloc(PATH_MAX, GFP_KERNEL); 7995 if (!buf) { 7996 ret = -ENOMEM; 7997 goto err_free_lb_resched; 7998 } 7999 cgroup_path(cgrp, buf, PATH_MAX); 8000 sch->cgrp_path = kstrdup(buf, GFP_KERNEL); 8001 kfree(buf); 8002 if (!sch->cgrp_path) { 8003 ret = -ENOMEM; 8004 goto err_free_lb_resched; 8005 } 8006 8007 sch->cgrp = cgrp; 8008 INIT_LIST_HEAD(&sch->children); 8009 INIT_LIST_HEAD(&sch->sibling); 8010 #endif /* CONFIG_EXT_SUB_SCHED */ 8011 8012 /* 8013 * Publishing makes @sch visible to scx_prog_sched() readers. Failure 8014 * paths after this point must free @sch through kobject_put() whose 8015 * release path defers the actual freeing by an RCU grace period. 8016 */ 8017 rcu_assign_pointer(ops->priv, sch); 8018 8019 sch->kobj.kset = scx_kset; 8020 INIT_LIST_HEAD(&sch->all); 8021 8022 #ifdef CONFIG_EXT_SUB_SCHED 8023 if (parent) { 8024 /* 8025 * Pin @parent for @sch's lifetime. The kobject hierarchy pins 8026 * it only via @parent->sub_kset, which is dropped during 8027 * disable. Released in scx_sched_free_rcu_work(). 8028 */ 8029 kobject_get(&parent->kobj); 8030 } 8031 #endif /* CONFIG_EXT_SUB_SCHED */ 8032 8033 /* 8034 * Init the kobj but don't add to sysfs yet. The enable path calls 8035 * scx_sched_sysfs_add() once @sch's sysfs-visible state is initialized. 8036 */ 8037 kobject_init(&sch->kobj, &scx_ktype); 8038 8039 /* 8040 * Consume the arena_map ref bpf_scx_reg_cid() took. Defer to here so 8041 * earlier failure paths leave cmd->arena_map set and bpf_scx_reg_cid 8042 * drops the ref. After this point, sch owns the ref and any cleanup 8043 * runs through scx_sched_free_rcu_work() which puts it. 8044 */ 8045 sch->arena_map = cmd->arena_map; 8046 /* BPF arena is only available on MMU && 64BIT */ 8047 #if defined(CONFIG_MMU) && defined(CONFIG_64BIT) 8048 if (sch->arena_map) 8049 sch->arena_kern_base = bpf_arena_map_kern_vm_start(sch->arena_map); 8050 #endif 8051 cmd->arena_map = NULL; 8052 return sch; 8053 8054 #ifdef CONFIG_EXT_SUB_SCHED 8055 err_free_lb_resched: 8056 free_cpumask_var(sch->stall_cpus); 8057 #endif 8058 err_free_lb_resched_cpumask: 8059 free_cpumask_var(sch->bypass_lb_resched_cpumask); 8060 err_free_lb_cpumask: 8061 free_cpumask_var(sch->bypass_lb_donee_cpumask); 8062 err_stop_helper: 8063 kthread_destroy_worker(sch->helper); 8064 err_free_pcpu: 8065 for_each_possible_cpu(cpu) { 8066 struct scx_sched_pcpu *pcpu = per_cpu_ptr(sch->pcpu, cpu); 8067 8068 free_cpumask_var(pcpu->cpus_to_kick); 8069 free_cpumask_var(pcpu->cpus_to_kick_if_idle); 8070 free_cpumask_var(pcpu->cpus_to_preempt); 8071 free_cpumask_var(pcpu->cpus_to_preempt_lazy); 8072 free_cpumask_var(pcpu->cpus_to_wait); 8073 } 8074 for_each_possible_cpu(cpu) { 8075 if (cpu == bypass_fail_cpu) 8076 break; 8077 exit_dsq(scx_bypass_dsq(sch, cpu)); 8078 } 8079 free_percpu(sch->pcpu); 8080 err_free_pnode: 8081 for_each_node_state(node, N_POSSIBLE) 8082 free_pnode(sch->pnode[node]); 8083 kfree(sch->pnode); 8084 err_free_hash: 8085 rhashtable_free_and_destroy(&sch->dsq_hash, NULL, NULL); 8086 err_free_ei: 8087 free_exit_info(sch->exit_info); 8088 err_free_sch: 8089 kfree(sch); 8090 err_put_cgrp: 8091 #ifdef CONFIG_EXT_SUB_SCHED 8092 cgroup_put(cgrp); 8093 #endif 8094 return ERR_PTR(ret); 8095 } 8096 8097 /* 8098 * Add @sch's kobject to sysfs, and create its sub_kset if the scheduler 8099 * implements ops.sub_attach. Called by the enable workfns once @sch's 8100 * sysfs-visible state is initialized. 8101 */ 8102 int scx_sched_sysfs_add(struct scx_sched *sch) 8103 { 8104 #ifdef CONFIG_EXT_SUB_SCHED 8105 struct scx_sched *parent = scx_parent(sch); 8106 int ret; 8107 8108 if (parent) 8109 ret = kobject_add(&sch->kobj, &parent->sub_kset->kobj, 8110 "sub-%llu", cgroup_id(sch_cgroup(sch))); 8111 else 8112 ret = kobject_add(&sch->kobj, NULL, "root"); 8113 if (ret < 0) 8114 return ret; 8115 8116 if (sch->ops.sub_attach) { 8117 sch->sub_kset = kset_create_and_add("sub", NULL, &sch->kobj); 8118 if (!sch->sub_kset) 8119 return -ENOMEM; 8120 } 8121 return 0; 8122 #else 8123 return kobject_add(&sch->kobj, NULL, "root"); 8124 #endif 8125 } 8126 8127 static int check_hotplug_seq(struct scx_sched *sch, 8128 const struct sched_ext_ops *ops) 8129 { 8130 unsigned long long global_hotplug_seq; 8131 8132 /* 8133 * If a hotplug event has occurred between when a scheduler was 8134 * initialized, and when we were able to attach, exit and notify user 8135 * space about it. 8136 */ 8137 if (ops->hotplug_seq) { 8138 global_hotplug_seq = atomic_long_read(&scx_hotplug_seq); 8139 if (ops->hotplug_seq != global_hotplug_seq) { 8140 scx_exit(sch, SCX_EXIT_UNREG_KERN, 8141 SCX_ECODE_ACT_RESTART | SCX_ECODE_RSN_HOTPLUG, 8142 "expected hotplug seq %llu did not match actual %llu", 8143 ops->hotplug_seq, global_hotplug_seq); 8144 return -EBUSY; 8145 } 8146 } 8147 8148 return 0; 8149 } 8150 8151 int scx_validate_ops(struct scx_sched *sch, const struct sched_ext_ops *ops) 8152 { 8153 /* 8154 * It doesn't make sense to specify the SCX_OPS_ENQ_LAST flag if the 8155 * ops.enqueue() callback isn't implemented. 8156 */ 8157 if ((ops->flags & SCX_OPS_ENQ_LAST) && !ops->enqueue) { 8158 scx_error(sch, "SCX_OPS_ENQ_LAST requires ops.enqueue() to be implemented"); 8159 return -EINVAL; 8160 } 8161 8162 if ((ops->flags & SCX_OPS_ENQ_BLOCKED) && !ops->enqueue) { 8163 scx_error(sch, "SCX_OPS_ENQ_BLOCKED requires ops.enqueue() to be implemented"); 8164 return -EINVAL; 8165 } 8166 8167 /* 8168 * SCX_OPS_TID_TO_TASK is enabled by the root scheduler. A sub-sched 8169 * may set it to declare a dependency; reject if the root hasn't 8170 * enabled it. 8171 */ 8172 if ((ops->flags & SCX_OPS_TID_TO_TASK) && scx_parent(sch) && 8173 !(sch->ancestors[0]->ops.flags & SCX_OPS_TID_TO_TASK)) { 8174 scx_error(sch, "SCX_OPS_TID_TO_TASK requires root scheduler to enable it"); 8175 return -EINVAL; 8176 } 8177 8178 /* 8179 * SCX_OPS_BUILTIN_IDLE_PER_NODE requires built-in CPU idle 8180 * selection policy to be enabled. 8181 */ 8182 if ((ops->flags & SCX_OPS_BUILTIN_IDLE_PER_NODE) && 8183 (ops->update_idle && !(ops->flags & SCX_OPS_KEEP_BUILTIN_IDLE))) { 8184 scx_error(sch, "SCX_OPS_BUILTIN_IDLE_PER_NODE requires CPU idle selection enabled"); 8185 return -EINVAL; 8186 } 8187 8188 /* 8189 * cid-form's struct is shorter and doesn't include the cpu_acquire / 8190 * cpu_release tail; reading those fields off a cid-form @ops would 8191 * run past the BPF allocation. Skip for cid-form. 8192 */ 8193 if (!sch->is_cid_type && (ops->cpu_acquire || ops->cpu_release)) 8194 pr_warn_ratelimited("ops->cpu_acquire/release() are deprecated, use sched_switch TP instead\n"); 8195 8196 /* 8197 * Sub-scheduler support is tied to the cid-form struct_ops. A sub-sched 8198 * attaches through a cid-form-only interface (sub_attach/sub_detach), 8199 * and a root that accepts sub-scheds must expose cid-form state to 8200 * them. Reject cpu-form schedulers on either side. 8201 */ 8202 if (!sch->is_cid_type) { 8203 if (scx_parent(sch)) { 8204 scx_error(sch, "sub-sched requires cid-form struct_ops"); 8205 return -EINVAL; 8206 } 8207 if (ops->sub_attach || ops->sub_detach) { 8208 scx_error(sch, "sub_attach/sub_detach requires cid-form struct_ops"); 8209 return -EINVAL; 8210 } 8211 } 8212 8213 return 0; 8214 } 8215 8216 static void scx_root_enable_workfn(struct kthread_work *work) 8217 { 8218 struct scx_enable_cmd *cmd = container_of(work, struct scx_enable_cmd, work); 8219 struct sched_ext_ops *ops = cmd->ops; 8220 struct cgroup *cgrp = root_cgroup(); 8221 struct scx_sched *sch; 8222 struct scx_task_iter sti; 8223 struct task_struct *p; 8224 int i, cpu, ret; 8225 8226 mutex_lock(&scx_enable_mutex); 8227 8228 if (scx_enable_state() != SCX_DISABLED) { 8229 ret = -EBUSY; 8230 goto err_unlock; 8231 } 8232 8233 /* 8234 * @ops->priv binds @ops to its scx_sched instance. It is set here by 8235 * scx_alloc_and_add_sched() and cleared at the tail of bpf_scx_unreg(), 8236 * which runs after scx_root_disable() has dropped scx_enable_mutex. If 8237 * it's still non-NULL here, a previous attachment on @ops has not 8238 * finished tearing down; proceeding would let the in-flight unreg's 8239 * RCU_INIT_POINTER(NULL) clobber the @ops->priv we are about to assign. 8240 */ 8241 if (rcu_access_pointer(ops->priv)) { 8242 ret = -EBUSY; 8243 goto err_unlock; 8244 } 8245 8246 ret = alloc_kick_syncs(); 8247 if (ret) 8248 goto err_unlock; 8249 8250 if (ops->flags & SCX_OPS_TID_TO_TASK) { 8251 ret = rhashtable_init(&scx_tid_hash, &scx_tid_hash_params); 8252 if (ret) 8253 goto err_free_ksyncs; 8254 } 8255 8256 #ifdef CONFIG_EXT_SUB_SCHED 8257 cgroup_get(cgrp); 8258 #endif 8259 /* 8260 * Transition to ENABLING to arm the disable path. Allocation failure 8261 * still unwinds locally. Full disabling on failure applies only after 8262 * scx_alloc_and_add_sched() succeeds. 8263 */ 8264 WARN_ON_ONCE(scx_set_enable_state(SCX_ENABLING) != SCX_DISABLED); 8265 WARN_ON_ONCE(scx_root); 8266 8267 sch = scx_alloc_and_add_sched(cmd, cgrp, NULL); 8268 if (IS_ERR(sch)) { 8269 ret = PTR_ERR(sch); 8270 WARN_ON_ONCE(scx_set_enable_state(SCX_DISABLED) != SCX_ENABLING); 8271 goto err_free_tid_hash; 8272 } 8273 8274 if (sch->is_cid_type) 8275 static_branch_enable(&__scx_is_cid_type); 8276 8277 atomic_long_set(&scx_nr_rejected, 0); 8278 8279 for_each_possible_cpu(cpu) { 8280 struct rq *rq = cpu_rq(cpu); 8281 8282 rq->scx.local_dsq.sched = sch; 8283 rq->scx.cpuperf_target = SCX_CPUPERF_ONE; 8284 } 8285 8286 scx_discard_stale_ecaps_syncs(); 8287 scx_rescue_set_knobs(sch); 8288 8289 /* 8290 * Keep CPUs stable during enable so that the BPF scheduler can track 8291 * online CPUs by watching ->on/offline_cpu() after ->init(). 8292 */ 8293 cpus_read_lock(); 8294 8295 /* 8296 * Build the cid mapping into a private under-construction set. It 8297 * becomes visible to readers only through scx_cid_publish_tables() once 8298 * ops.init_cids() has finalized the layout. 8299 */ 8300 ret = scx_cid_init(sch); 8301 if (ret) { 8302 cpus_read_unlock(); 8303 goto err_disable; 8304 } 8305 8306 /* 8307 * Make the scheduler instance visible. Must be inside cpus_read_lock(). 8308 * See handle_hotplug(). 8309 */ 8310 rcu_assign_pointer(scx_root, sch); 8311 8312 ret = scx_link_sched(sch); 8313 if (ret) { 8314 cpus_read_unlock(); 8315 goto err_disable; 8316 } 8317 8318 scx_idle_enable(ops); 8319 8320 /* 8321 * A cid-form scheduler finalizes its cid layout in ops.init_cids(), 8322 * which may call scx_bpf_cid_override(). Run it before the caps and 8323 * shard state are built so the final layout is in effect. 8324 */ 8325 if (sch->is_cid_type && sch->ops_cid.init_cids) { 8326 ret = SCX_CALL_OP_RET(sch, init_cids, NULL); 8327 if (ret) { 8328 ret = scx_ops_sanitize_err(sch, "init_cids", ret); 8329 cpus_read_unlock(); 8330 scx_error(sch, "ops.init_cids() failed (%d)", ret); 8331 goto err_disable; 8332 } 8333 } 8334 8335 /* the cid layout is final, expose it to readers */ 8336 scx_cid_publish_tables(); 8337 8338 ret = scx_arena_pool_init(sch); 8339 if (ret) { 8340 cpus_read_unlock(); 8341 goto err_disable; 8342 } 8343 8344 ret = scx_alloc_kern_arena_objs(sch); 8345 if (ret) { 8346 cpus_read_unlock(); 8347 goto err_disable; 8348 } 8349 8350 ret = scx_alloc_pshards(sch); 8351 if (ret) { 8352 cpus_read_unlock(); 8353 goto err_disable; 8354 } 8355 8356 scx_init_root_caps(sch); 8357 8358 /* the cid caps and shards are live now, so ops.init() can query them */ 8359 if (sch->ops.init) { 8360 ret = SCX_CALL_OP_RET(sch, init, NULL); 8361 if (ret) { 8362 ret = scx_ops_sanitize_err(sch, "init", ret); 8363 cpus_read_unlock(); 8364 scx_error(sch, "ops.init() failed (%d)", ret); 8365 goto err_disable; 8366 } 8367 sch->exit_info->flags |= SCX_EFLAG_INITIALIZED; 8368 } 8369 8370 ret = scx_sched_sysfs_add(sch); 8371 if (ret) { 8372 cpus_read_unlock(); 8373 goto err_disable; 8374 } 8375 8376 for (i = SCX_OPI_CPU_HOTPLUG_BEGIN; i < SCX_OPI_CPU_HOTPLUG_END; i++) 8377 if (((void (**)(void))ops)[i]) 8378 set_bit(i, sch->has_op); 8379 8380 ret = check_hotplug_seq(sch, ops); 8381 if (ret) { 8382 cpus_read_unlock(); 8383 goto err_disable; 8384 } 8385 scx_idle_update_selcpu_topology(ops); 8386 8387 cpus_read_unlock(); 8388 8389 ret = scx_validate_ops(sch, ops); 8390 if (ret) 8391 goto err_disable; 8392 8393 /* 8394 * Attach the ext_server bandwidth reservation before anything is 8395 * committed so that we can fail the enable if the root domain cannot 8396 * accommodate it. The matching fair_server detach is deferred to the 8397 * tail of this function, after the switch is fully committed and can no 8398 * longer fail. 8399 * 8400 * On failure, err_disable funnels into scx_root_disable() which 8401 * detaches ext_server, so partially-attached state is cleaned up 8402 * automatically. 8403 */ 8404 for_each_possible_cpu(cpu) { 8405 struct rq *rq = cpu_rq(cpu); 8406 8407 scoped_guard(rq_lock_irqsave, rq) { 8408 update_rq_clock(rq); 8409 ret = dl_server_attach_bw(&rq->ext_server); 8410 } 8411 if (ret) { 8412 pr_warn("sched_ext: failed to attach ext_server on CPU %d (%d)\n", 8413 cpu, ret); 8414 goto err_disable; 8415 } 8416 } 8417 8418 /* 8419 * Once __scx_enabled is set, %current can be switched to SCX anytime. 8420 * This can lead to stalls as some BPF schedulers (e.g. userspace 8421 * scheduling) may not function correctly before all tasks are switched. 8422 * Init in bypass mode to guarantee forward progress. 8423 */ 8424 scx_bypass(sch, true); 8425 8426 for (i = SCX_OPI_NORMAL_BEGIN; i < SCX_OPI_NORMAL_END; i++) 8427 if (((void (**)(void))ops)[i]) 8428 set_bit(i, sch->has_op); 8429 8430 scx_ops_cid_sched_updated_enable(sch); 8431 8432 if (sch->ops.cpu_acquire || sch->ops.cpu_release) 8433 sch->ops.flags |= SCX_OPS_HAS_CPU_PREEMPT; 8434 8435 /* 8436 * Lock out forks, cgroup on/offlining and moves before opening the 8437 * floodgate so that they don't wander into the operations prematurely. 8438 */ 8439 percpu_down_write(&scx_fork_rwsem); 8440 8441 WARN_ON_ONCE(scx_init_task_enabled); 8442 scx_init_task_enabled = true; 8443 8444 /* flip under fork_rwsem; the iter below covers existing tasks */ 8445 if (ops->flags & SCX_OPS_TID_TO_TASK) 8446 static_branch_enable(&__scx_tid_to_task_enabled); 8447 8448 /* 8449 * Enable ops for every task. Fork is excluded by scx_fork_rwsem 8450 * preventing new tasks from being added. No need to exclude tasks 8451 * leaving as sched_ext_dead() can handle both prepped and enabled 8452 * tasks. Prep all tasks first and then enable them with preemption 8453 * disabled. 8454 * 8455 * All cgroups should be initialized before scx_init_task() so that the 8456 * BPF scheduler can reliably track each task's cgroup membership from 8457 * scx_init_task(). Lock out cgroup on/offlining and task migrations 8458 * while tasks are being initialized so that scx_cgroup_can_attach() 8459 * never sees uninitialized tasks. 8460 */ 8461 scx_cgroup_lock(); 8462 set_cgroup_sched(sch_cgroup(sch), sch); 8463 ret = scx_cgroup_init(sch); 8464 if (ret) 8465 goto err_disable_unlock_all; 8466 8467 WARN_ON_ONCE(scx_cgroup_enabled); 8468 scx_cgroup_enabled = true; 8469 8470 scx_task_iter_start(&sti, NULL); 8471 while ((p = scx_task_iter_next_locked(&sti))) { 8472 /* 8473 * @p is in scx_tasks under scx_tasks_lock, and SCX_TASK_DEAD 8474 * tasks are filtered by scx_task_iter_next_locked(). 8475 * sched_ext_dead() removes @p from scx_tasks under the same 8476 * lock before put_task_struct_rcu_user() runs, so @p->usage 8477 * is guaranteed > 0 here. 8478 */ 8479 get_task_struct(p); 8480 8481 /* 8482 * Set %INIT_BEGIN under the iter's rq lock so that a concurrent 8483 * sched_ext_dead() does not call ops.exit_task() on @p while 8484 * ops.init_task() is running. If sched_ext_dead() runs before 8485 * this store, it has already removed @p from scx_tasks and the 8486 * iter won't visit @p; if it runs after, it observes 8487 * %INIT_BEGIN and transitions to %DEAD without calling ops, 8488 * leaving the post-init recheck below to unwind. 8489 */ 8490 scx_set_task_state(p, SCX_TASK_INIT_BEGIN); 8491 scx_task_iter_unlock(&sti); 8492 8493 ret = __scx_init_task(sch, p, NULL, false); 8494 8495 scx_task_iter_relock(&sti, p); 8496 8497 if (unlikely(ret)) { 8498 if (scx_get_task_state(p) != SCX_TASK_DEAD) 8499 scx_set_task_state(p, SCX_TASK_NONE); 8500 scx_task_iter_stop(&sti); 8501 scx_error(sch, "ops.init_task() failed (%d) for %s[%d]", 8502 ret, p->comm, p->pid); 8503 put_task_struct(p); 8504 goto err_disable_unlock_all; 8505 } 8506 8507 if (scx_get_task_state(p) == SCX_TASK_DEAD) { 8508 /* 8509 * sched_ext_dead() observed %INIT_BEGIN and set %DEAD. 8510 * ops.exit_task() is owed to the sched __scx_init_task() 8511 * ran against; call it now. 8512 */ 8513 scx_sub_init_cancel_task(sch, p); 8514 } else { 8515 scx_set_task_state(p, SCX_TASK_INIT); 8516 scx_set_task_sched(p, sch); 8517 scx_set_task_state(p, SCX_TASK_READY); 8518 } 8519 8520 /* 8521 * Insert into the tid hash. scx_tasks_lock is held by the iter; 8522 * list_empty() guards against sched_ext_dead() having taken @p 8523 * off the list while init ran unlocked. 8524 */ 8525 if (scx_tid_to_task_enabled() && !list_empty(&p->scx.tasks_node)) 8526 scx_tid_hash_insert(p); 8527 8528 put_task_struct(p); 8529 } 8530 scx_task_iter_stop(&sti); 8531 scx_cgroup_unlock(); 8532 percpu_up_write(&scx_fork_rwsem); 8533 8534 /* 8535 * All tasks are READY. It's safe to turn on scx_enabled() and switch 8536 * all eligible tasks. 8537 */ 8538 WRITE_ONCE(scx_switching_all, !(ops->flags & SCX_OPS_SWITCH_PARTIAL)); 8539 static_branch_enable(&__scx_enabled); 8540 8541 /* 8542 * We're fully committed and can't fail. The task READY -> ENABLED 8543 * transitions here are synchronized against sched_ext_dead() through 8544 * scx_tasks_lock. 8545 */ 8546 percpu_down_write(&scx_fork_rwsem); 8547 scx_task_iter_start(&sti, NULL); 8548 while ((p = scx_task_iter_next_locked(&sti))) { 8549 unsigned int queue_flags = DEQUEUE_SAVE | DEQUEUE_MOVE; 8550 const struct sched_class *old_class = p->sched_class; 8551 const struct sched_class *new_class = scx_setscheduler_class(p); 8552 8553 if (scx_get_task_state(p) != SCX_TASK_READY) 8554 continue; 8555 8556 if (old_class != new_class) 8557 queue_flags |= DEQUEUE_CLASS; 8558 if (new_class == &ext_sched_class) { 8559 scx_prepare_task_sched_change(p); 8560 queue_flags |= DEQUEUE_NOCLOCK; 8561 } 8562 8563 scoped_guard (sched_change, p, queue_flags) { 8564 scx_set_task_slice(p, READ_ONCE(sch->slice_dfl)); 8565 p->sched_class = new_class; 8566 } 8567 } 8568 scx_task_iter_stop(&sti); 8569 percpu_up_write(&scx_fork_rwsem); 8570 8571 scx_bypass(sch, false); 8572 8573 if (!scx_tryset_enable_state(SCX_ENABLED, SCX_ENABLING)) { 8574 WARN_ON_ONCE(atomic_read(&sch->exit_kind) == SCX_EXIT_NONE); 8575 ret = -EBUSY; 8576 goto err_disable; 8577 } 8578 8579 if (!(ops->flags & SCX_OPS_SWITCH_PARTIAL)) 8580 static_branch_enable(&__scx_switched_all); 8581 8582 /* 8583 * Detach the fair_server bandwidth reservation now that the switch 8584 * is fully committed. In full mode (!SCX_OPS_SWITCH_PARTIAL) no 8585 * task will ever run in the fair class, so give that bandwidth 8586 * back to the RT class. The matching ext_server attach already 8587 * happened earlier; this only releases bandwidth and cannot fail. 8588 * 8589 * In partial mode keep fair_server attached. 8590 */ 8591 if (scx_switched_all()) { 8592 for_each_possible_cpu(cpu) { 8593 struct rq *rq = cpu_rq(cpu); 8594 8595 guard(rq_lock_irqsave)(rq); 8596 update_rq_clock(rq); 8597 dl_server_detach_bw(&rq->fair_server); 8598 } 8599 } 8600 8601 pr_info("sched_ext: BPF scheduler \"%s\" enabled%s\n", 8602 sch->ops.name, scx_switched_all() ? "" : " (partial)"); 8603 kobject_uevent(&sch->kobj, KOBJ_ADD); 8604 mutex_unlock(&scx_enable_mutex); 8605 8606 atomic_long_inc(&scx_enable_seq); 8607 8608 cmd->ret = 0; 8609 return; 8610 8611 err_free_tid_hash: 8612 if (ops->flags & SCX_OPS_TID_TO_TASK) 8613 rhashtable_free_and_destroy(&scx_tid_hash, NULL, NULL); 8614 err_free_ksyncs: 8615 free_kick_syncs(); 8616 err_unlock: 8617 mutex_unlock(&scx_enable_mutex); 8618 cmd->ret = ret; 8619 return; 8620 8621 err_disable_unlock_all: 8622 scx_cgroup_unlock(); 8623 percpu_up_write(&scx_fork_rwsem); 8624 /* we'll soon enter disable path, keep bypass on */ 8625 err_disable: 8626 mutex_unlock(&scx_enable_mutex); 8627 /* 8628 * Returning an error code here would not pass all the error information 8629 * to userspace. Record errno using scx_error() for cases scx_error() 8630 * wasn't already invoked and exit indicating success so that the error 8631 * is notified through ops.exit() with all the details. 8632 * 8633 * Flush scx_disable_work to ensure that error is reported before init 8634 * completion. sch's base reference will be put by bpf_scx_unreg(). 8635 */ 8636 scx_error(sch, "scx_root_enable() failed (%d)", ret); 8637 scx_flush_disable_work(sch); 8638 cmd->ret = 0; 8639 } 8640 8641 static s32 scx_enable(struct scx_enable_cmd *cmd, struct bpf_link *link) 8642 { 8643 static struct kthread_worker *helper; 8644 static DEFINE_MUTEX(helper_mutex); 8645 8646 if (housekeeping_enabled(HK_TYPE_DOMAIN_BOOT)) { 8647 pr_err("sched_ext: Not compatible with \"isolcpus=\" domain isolation\n"); 8648 return -EINVAL; 8649 } 8650 8651 if (!READ_ONCE(helper)) { 8652 mutex_lock(&helper_mutex); 8653 if (!helper) { 8654 struct kthread_worker *w = 8655 kthread_run_worker(0, "scx_enable_helper"); 8656 if (IS_ERR_OR_NULL(w)) { 8657 mutex_unlock(&helper_mutex); 8658 return -ENOMEM; 8659 } 8660 sched_set_fifo(w->task); 8661 WRITE_ONCE(helper, w); 8662 } 8663 mutex_unlock(&helper_mutex); 8664 } 8665 8666 #ifdef CONFIG_EXT_SUB_SCHED 8667 if (cmd->ops->sub_cgroup_id > 1) 8668 kthread_init_work(&cmd->work, scx_sub_enable_workfn); 8669 else 8670 #endif /* CONFIG_EXT_SUB_SCHED */ 8671 kthread_init_work(&cmd->work, scx_root_enable_workfn); 8672 8673 kthread_queue_work(READ_ONCE(helper), &cmd->work); 8674 kthread_flush_work(&cmd->work); 8675 return cmd->ret; 8676 } 8677 8678 8679 /******************************************************************************** 8680 * bpf_struct_ops plumbing. 8681 */ 8682 #include <linux/bpf_verifier.h> 8683 #include <linux/bpf.h> 8684 #include <linux/btf.h> 8685 8686 static const struct btf_type *task_struct_type; 8687 8688 static bool bpf_scx_is_valid_access(int off, int size, 8689 enum bpf_access_type type, 8690 const struct bpf_prog *prog, 8691 struct bpf_insn_access_aux *info) 8692 { 8693 if (type != BPF_READ) 8694 return false; 8695 if (off < 0 || off >= sizeof(__u64) * MAX_BPF_FUNC_ARGS) 8696 return false; 8697 if (off % size != 0) 8698 return false; 8699 8700 return btf_ctx_access(off, size, type, prog, info); 8701 } 8702 8703 /* common to both forms: only scx.disallow is writable */ 8704 static int bpf_scx_btf_struct_access_common(const struct bpf_reg_state *reg, 8705 int off, int size) 8706 { 8707 const struct btf_type *t; 8708 8709 t = btf_type_by_id(reg->btf, reg->btf_id); 8710 if (t == task_struct_type && 8711 off >= offsetof(struct task_struct, scx.disallow) && 8712 off + size <= offsetofend(struct task_struct, scx.disallow)) 8713 return SCALAR_VALUE; 8714 8715 return -EACCES; 8716 } 8717 8718 static int bpf_scx_btf_struct_access(struct bpf_verifier_log *log, 8719 const struct bpf_reg_state *reg, int off, 8720 int size) 8721 { 8722 const struct btf_type *t; 8723 8724 t = btf_type_by_id(reg->btf, reg->btf_id); 8725 if (t == task_struct_type) { 8726 if ((off >= offsetof(struct task_struct, scx.slice) && 8727 off + size <= offsetofend(struct task_struct, scx.slice)) || 8728 (off >= offsetof(struct task_struct, scx.dsq_vtime) && 8729 off + size <= offsetofend(struct task_struct, scx.dsq_vtime))) 8730 return SCALAR_VALUE; 8731 } 8732 8733 return bpf_scx_btf_struct_access_common(reg, off, size); 8734 } 8735 8736 /* cid-form rejects direct slice and dsq_vtime writes in favor of the kfuncs */ 8737 static int bpf_scx_cid_btf_struct_access(struct bpf_verifier_log *log, 8738 const struct bpf_reg_state *reg, int off, 8739 int size) 8740 { 8741 return bpf_scx_btf_struct_access_common(reg, off, size); 8742 } 8743 8744 static const struct bpf_verifier_ops bpf_scx_verifier_ops = { 8745 .get_func_proto = bpf_base_func_proto, 8746 .is_valid_access = bpf_scx_is_valid_access, 8747 .btf_struct_access = bpf_scx_btf_struct_access, 8748 }; 8749 8750 static const struct bpf_verifier_ops bpf_scx_cid_verifier_ops = { 8751 .get_func_proto = bpf_base_func_proto, 8752 .is_valid_access = bpf_scx_is_valid_access, 8753 .btf_struct_access = bpf_scx_cid_btf_struct_access, 8754 }; 8755 8756 static int bpf_scx_init_member(const struct btf_type *t, 8757 const struct btf_member *member, 8758 void *kdata, const void *udata) 8759 { 8760 const struct sched_ext_ops *uops = udata; 8761 struct sched_ext_ops *ops = kdata; 8762 u32 moff = __btf_member_bit_offset(t, member) / 8; 8763 int ret; 8764 8765 switch (moff) { 8766 case offsetof(struct sched_ext_ops, dispatch_max_batch): 8767 if (*(u32 *)(udata + moff) > INT_MAX) 8768 return -E2BIG; 8769 ops->dispatch_max_batch = *(u32 *)(udata + moff); 8770 return 1; 8771 case offsetof(struct sched_ext_ops, flags): 8772 if (*(u64 *)(udata + moff) & ~SCX_OPS_ALL_FLAGS) 8773 return -EINVAL; 8774 ops->flags = *(u64 *)(udata + moff); 8775 return 1; 8776 case offsetof(struct sched_ext_ops, name): 8777 ret = bpf_obj_name_cpy(ops->name, uops->name, 8778 sizeof(ops->name)); 8779 if (ret < 0) 8780 return ret; 8781 if (ret == 0) 8782 return -EINVAL; 8783 return 1; 8784 case offsetof(struct sched_ext_ops, timeout_ms): 8785 if (msecs_to_jiffies(*(u32 *)(udata + moff)) > 8786 SCX_WATCHDOG_MAX_TIMEOUT) 8787 return -E2BIG; 8788 ops->timeout_ms = *(u32 *)(udata + moff); 8789 return 1; 8790 case offsetof(struct sched_ext_ops, exit_dump_len): 8791 ops->exit_dump_len = 8792 *(u32 *)(udata + moff) ?: SCX_EXIT_DUMP_DFL_LEN; 8793 return 1; 8794 case offsetof(struct sched_ext_ops, hotplug_seq): 8795 ops->hotplug_seq = *(u64 *)(udata + moff); 8796 return 1; 8797 case offsetof(struct sched_ext_ops, cid_shard_size): 8798 ops->cid_shard_size = *(u32 *)(udata + moff); 8799 return 1; 8800 case offsetof(struct sched_ext_ops, rescue_bandwidth_ppt): { 8801 u32 bw_ppt = *(u32 *)(udata + moff); 8802 8803 if (bw_ppt > SCX_RESCUE_MAX_BW_PPT && bw_ppt != SCX_RESCUE_DISABLE) 8804 return -E2BIG; 8805 ops->rescue_bandwidth_ppt = bw_ppt; 8806 return 1; 8807 } 8808 case offsetof(struct sched_ext_ops, rescue_quantum_us): { 8809 u32 quantum_us = *(u32 *)(udata + moff); 8810 8811 if (quantum_us > SCX_RESCUE_MAX_QUANTUM_US) 8812 return -E2BIG; 8813 if (quantum_us && quantum_us < SCX_RESCUE_MIN_QUANTUM_US) 8814 return -EINVAL; 8815 ops->rescue_quantum_us = quantum_us; 8816 return 1; 8817 } 8818 #ifdef CONFIG_EXT_SUB_SCHED 8819 case offsetof(struct sched_ext_ops, sub_cgroup_id): 8820 ops->sub_cgroup_id = *(u64 *)(udata + moff); 8821 return 1; 8822 #endif /* CONFIG_EXT_SUB_SCHED */ 8823 } 8824 8825 return 0; 8826 } 8827 8828 static int bpf_scx_check_member(const struct btf_type *t, 8829 const struct btf_member *member, 8830 const struct bpf_prog *prog) 8831 { 8832 u32 moff = __btf_member_bit_offset(t, member) / 8; 8833 8834 switch (moff) { 8835 case offsetof(struct sched_ext_ops, init_task): 8836 #ifdef CONFIG_EXT_GROUP_SCHED 8837 case offsetof(struct sched_ext_ops, cgroup_init): 8838 case offsetof(struct sched_ext_ops, cgroup_exit): 8839 case offsetof(struct sched_ext_ops, cgroup_prep_move): 8840 case offsetof(struct sched_ext_ops, cgroup_set_bandwidth): 8841 #endif 8842 case offsetof(struct sched_ext_ops, cpu_online): 8843 case offsetof(struct sched_ext_ops, cpu_offline): 8844 case offsetof(struct sched_ext_ops, init_cids): 8845 case offsetof(struct sched_ext_ops, init): 8846 case offsetof(struct sched_ext_ops, exit): 8847 case offsetof(struct sched_ext_ops, sub_attach): 8848 case offsetof(struct sched_ext_ops, sub_detach): 8849 break; 8850 default: 8851 if (prog->sleepable) 8852 return -EINVAL; 8853 } 8854 8855 #ifdef CONFIG_EXT_SUB_SCHED 8856 /* 8857 * Enable private stack for operations that can nest along the 8858 * hierarchy. 8859 * 8860 * XXX - Ideally, we should only do this for scheds that allow 8861 * sub-scheds and sub-scheds themselves but I don't know how to access 8862 * struct_ops from here. 8863 */ 8864 switch (moff) { 8865 case offsetof(struct sched_ext_ops, dispatch): 8866 prog->aux->priv_stack_requested = true; 8867 prog->aux->recursion_detected = scx_pstack_recursion_on_dispatch; 8868 break; 8869 case offsetof(struct sched_ext_ops, sub_caps_updated): 8870 prog->aux->priv_stack_requested = true; 8871 prog->aux->recursion_detected = scx_pstack_recursion_on_caps_updated; 8872 break; 8873 } 8874 #endif /* CONFIG_EXT_SUB_SCHED */ 8875 8876 return 0; 8877 } 8878 8879 static int bpf_scx_reg(void *kdata, struct bpf_link *link) 8880 { 8881 struct scx_enable_cmd cmd = { .ops = kdata }; 8882 8883 return scx_enable(&cmd, link); 8884 } 8885 8886 struct scx_arena_scan { 8887 struct bpf_map *arena; 8888 int err; 8889 }; 8890 8891 /* 8892 * The verifier enforces one arena per BPF program, so each struct_ops 8893 * member prog contributes at most one arena via bpf_prog_arena(). 8894 * Require all non-NULL contributions to match. 8895 */ 8896 static int scx_arena_scan_prog(struct bpf_prog *prog, void *data) 8897 { 8898 struct scx_arena_scan *s = data; 8899 struct bpf_map *arena = NULL; 8900 8901 /* arena.o, which defines these, is built only on MMU && 64BIT */ 8902 #if defined(CONFIG_MMU) && defined(CONFIG_64BIT) 8903 arena = bpf_prog_arena(prog); 8904 #endif 8905 if (!arena) 8906 return 0; 8907 if (s->arena && s->arena != arena) { 8908 s->err = -EINVAL; 8909 return 1; 8910 } 8911 s->arena = arena; 8912 return 0; 8913 } 8914 8915 static int bpf_scx_reg_cid(void *kdata, struct bpf_link *link) 8916 { 8917 struct scx_enable_cmd cmd = { .ops_cid = kdata, .is_cid_type = true }; 8918 struct scx_arena_scan scan = {}; 8919 int ret; 8920 8921 bpf_struct_ops_for_each_prog(kdata, scx_arena_scan_prog, &scan); 8922 if (scan.err) { 8923 pr_err("sched_ext: cid-form scheduler uses multiple arena maps\n"); 8924 return scan.err; 8925 } 8926 if (!scan.arena) { 8927 pr_err("sched_ext: cid-form scheduler must use a BPF arena map\n"); 8928 return -EINVAL; 8929 } 8930 8931 bpf_map_inc(scan.arena); 8932 cmd.arena_map = scan.arena; 8933 ret = scx_enable(&cmd, link); 8934 if (cmd.arena_map) /* not consumed by scx_alloc_and_add_sched() */ 8935 bpf_map_put(cmd.arena_map); 8936 return ret; 8937 } 8938 8939 static void bpf_scx_unreg(void *kdata, struct bpf_link *link) 8940 { 8941 struct sched_ext_ops *ops = kdata; 8942 struct scx_sched *sch = rcu_dereference_protected(ops->priv, true); 8943 8944 scx_disable(sch, SCX_EXIT_UNREG); 8945 scx_flush_disable_work(sch); 8946 RCU_INIT_POINTER(ops->priv, NULL); 8947 kobject_put(&sch->kobj); 8948 } 8949 8950 static int bpf_scx_init(struct btf *btf) 8951 { 8952 task_struct_type = btf_type_by_id(btf, btf_tracing_ids[BTF_TRACING_TYPE_TASK]); 8953 8954 return 0; 8955 } 8956 8957 static int bpf_scx_update(void *kdata, void *old_kdata, struct bpf_link *link) 8958 { 8959 /* 8960 * sched_ext does not support updating the actively-loaded BPF 8961 * scheduler, as registering a BPF scheduler can always fail if the 8962 * scheduler returns an error code for e.g. ops.init(), ops.init_task(), 8963 * etc. Similarly, we can always race with unregistration happening 8964 * elsewhere, such as with sysrq. 8965 */ 8966 return -EOPNOTSUPP; 8967 } 8968 8969 static int bpf_scx_validate(void *kdata) 8970 { 8971 return 0; 8972 } 8973 8974 static s32 sched_ext_ops__select_cpu(struct task_struct *p, s32 prev_cpu, u64 wake_flags) { return -EINVAL; } 8975 static void sched_ext_ops__enqueue(struct task_struct *p, u64 enq_flags) {} 8976 static void sched_ext_ops__dequeue(struct task_struct *p, u64 enq_flags) {} 8977 static void sched_ext_ops__dispatch(s32 prev_cpu, struct task_struct *prev__nullable) {} 8978 static void sched_ext_ops__tick(struct task_struct *p) {} 8979 static void sched_ext_ops__runnable(struct task_struct *p, u64 enq_flags) {} 8980 static void sched_ext_ops__running(struct task_struct *p) {} 8981 static void sched_ext_ops__stopping(struct task_struct *p, bool runnable) {} 8982 static void sched_ext_ops__quiescent(struct task_struct *p, u64 deq_flags) {} 8983 static bool sched_ext_ops__yield(struct task_struct *from, struct task_struct *to__nullable) { return false; } 8984 static bool sched_ext_ops__core_sched_before(struct task_struct *a, struct task_struct *b) { return false; } 8985 static void sched_ext_ops__set_weight(struct task_struct *p, u32 weight) {} 8986 static void sched_ext_ops__set_cpumask(struct task_struct *p, const struct cpumask *mask) {} 8987 static void sched_ext_ops__update_idle(s32 cpu, bool idle) {} 8988 static void sched_ext_ops__cpu_acquire(s32 cpu, struct scx_cpu_acquire_args *args) {} 8989 static void sched_ext_ops__cpu_release(s32 cpu, struct scx_cpu_release_args *args) {} 8990 static s32 sched_ext_ops__init_task(struct task_struct *p, struct scx_init_task_args *args) { return -EINVAL; } 8991 static void sched_ext_ops__exit_task(struct task_struct *p, struct scx_exit_task_args *args) {} 8992 static void sched_ext_ops__enable(struct task_struct *p) {} 8993 static void sched_ext_ops__disable(struct task_struct *p) {} 8994 #ifdef CONFIG_EXT_GROUP_SCHED 8995 static s32 sched_ext_ops__cgroup_init(struct cgroup *cgrp, struct scx_cgroup_init_args *args) { return -EINVAL; } 8996 static void sched_ext_ops__cgroup_exit(struct cgroup *cgrp) {} 8997 static s32 sched_ext_ops__cgroup_prep_move(struct task_struct *p, struct cgroup *from, struct cgroup *to) { return -EINVAL; } 8998 static void sched_ext_ops__cgroup_move(struct task_struct *p, struct cgroup *from, struct cgroup *to) {} 8999 static void sched_ext_ops__cgroup_cancel_move(struct task_struct *p, struct cgroup *from, struct cgroup *to) {} 9000 static void sched_ext_ops__cgroup_set_weight(struct cgroup *cgrp, u32 weight) {} 9001 static void sched_ext_ops__cgroup_set_bandwidth(struct cgroup *cgrp, u64 period_us, u64 quota_us, u64 burst_us) {} 9002 static void sched_ext_ops__cgroup_set_idle(struct cgroup *cgrp, bool idle) {} 9003 #endif /* CONFIG_EXT_GROUP_SCHED */ 9004 static s32 sched_ext_ops__sub_attach(struct scx_sub_attach_args *args) { return -EINVAL; } 9005 static void sched_ext_ops__sub_detach(struct scx_sub_detach_args *args) {} 9006 static void sched_ext_ops__cpu_online(s32 cpu) {} 9007 static void sched_ext_ops__cpu_offline(s32 cpu) {} 9008 static s32 sched_ext_ops__init_cids(void) { return -EINVAL; } 9009 static s32 sched_ext_ops__init(void) { return -EINVAL; } 9010 static void sched_ext_ops__exit(struct scx_exit_info *info) {} 9011 static void sched_ext_ops__dump(struct scx_dump_ctx *ctx) {} 9012 static void sched_ext_ops__dump_cpu(struct scx_dump_ctx *ctx, s32 cpu, bool idle) {} 9013 static void sched_ext_ops__dump_task(struct scx_dump_ctx *ctx, struct task_struct *p) {} 9014 9015 static struct sched_ext_ops __bpf_ops_sched_ext_ops = { 9016 .select_cpu = sched_ext_ops__select_cpu, 9017 .enqueue = sched_ext_ops__enqueue, 9018 .dequeue = sched_ext_ops__dequeue, 9019 .dispatch = sched_ext_ops__dispatch, 9020 .tick = sched_ext_ops__tick, 9021 .runnable = sched_ext_ops__runnable, 9022 .running = sched_ext_ops__running, 9023 .stopping = sched_ext_ops__stopping, 9024 .quiescent = sched_ext_ops__quiescent, 9025 .yield = sched_ext_ops__yield, 9026 .core_sched_before = sched_ext_ops__core_sched_before, 9027 .set_weight = sched_ext_ops__set_weight, 9028 .set_cpumask = sched_ext_ops__set_cpumask, 9029 .update_idle = sched_ext_ops__update_idle, 9030 .cpu_acquire = sched_ext_ops__cpu_acquire, 9031 .cpu_release = sched_ext_ops__cpu_release, 9032 .init_task = sched_ext_ops__init_task, 9033 .exit_task = sched_ext_ops__exit_task, 9034 .enable = sched_ext_ops__enable, 9035 .disable = sched_ext_ops__disable, 9036 #ifdef CONFIG_EXT_GROUP_SCHED 9037 .cgroup_init = sched_ext_ops__cgroup_init, 9038 .cgroup_exit = sched_ext_ops__cgroup_exit, 9039 .cgroup_prep_move = sched_ext_ops__cgroup_prep_move, 9040 .cgroup_move = sched_ext_ops__cgroup_move, 9041 .cgroup_cancel_move = sched_ext_ops__cgroup_cancel_move, 9042 .cgroup_set_weight = sched_ext_ops__cgroup_set_weight, 9043 .cgroup_set_bandwidth = sched_ext_ops__cgroup_set_bandwidth, 9044 .cgroup_set_idle = sched_ext_ops__cgroup_set_idle, 9045 #endif 9046 .sub_attach = sched_ext_ops__sub_attach, 9047 .sub_detach = sched_ext_ops__sub_detach, 9048 .cpu_online = sched_ext_ops__cpu_online, 9049 .cpu_offline = sched_ext_ops__cpu_offline, 9050 .init_cids = sched_ext_ops__init_cids, 9051 .init = sched_ext_ops__init, 9052 .exit = sched_ext_ops__exit, 9053 .dump = sched_ext_ops__dump, 9054 .dump_cpu = sched_ext_ops__dump_cpu, 9055 .dump_task = sched_ext_ops__dump_task, 9056 }; 9057 9058 static struct bpf_struct_ops bpf_sched_ext_ops = { 9059 .verifier_ops = &bpf_scx_verifier_ops, 9060 .reg = bpf_scx_reg, 9061 .unreg = bpf_scx_unreg, 9062 .check_member = bpf_scx_check_member, 9063 .init_member = bpf_scx_init_member, 9064 .init = bpf_scx_init, 9065 .update = bpf_scx_update, 9066 .validate = bpf_scx_validate, 9067 .name = "sched_ext_ops", 9068 .owner = THIS_MODULE, 9069 .cfi_stubs = &__bpf_ops_sched_ext_ops 9070 }; 9071 9072 /* 9073 * cid-form cfi stubs. Stubs whose signatures match the cpu-form (param types 9074 * identical, only param names differ across structs) are reused. Some need 9075 * fresh stubs, set_cmask and enable due to argument differences and the 9076 * sub-sched notifiers because no cpu-form stub exists to reuse. 9077 */ 9078 static void sched_ext_ops_cid__set_cmask(struct task_struct *p, const struct scx_cmask *cmask__arena) {} 9079 static void sched_ext_ops_cid__enable(struct task_struct *p, struct scx_enable_args *args) {} 9080 static void sched_ext_ops__sub_caps_updated(const struct scx_cmask *cmask__arena, u64 caps) {} 9081 static void sched_ext_ops__sub_ecaps_updated(s32 cid, u64 before, u64 after) {} 9082 static void sched_ext_ops__sub_cid_sched_updated(s32 cid, u64 sched) {} 9083 static void sched_ext_ops__sub_child_ecaps_updated(u64 cgroup_id, s32 cid, u64 before, u64 after) {} 9084 9085 static struct sched_ext_ops_cid __bpf_ops_sched_ext_ops_cid = { 9086 .select_cid = sched_ext_ops__select_cpu, 9087 .enqueue = sched_ext_ops__enqueue, 9088 .dequeue = sched_ext_ops__dequeue, 9089 .dispatch = sched_ext_ops__dispatch, 9090 .tick = sched_ext_ops__tick, 9091 .runnable = sched_ext_ops__runnable, 9092 .running = sched_ext_ops__running, 9093 .stopping = sched_ext_ops__stopping, 9094 .quiescent = sched_ext_ops__quiescent, 9095 .yield = sched_ext_ops__yield, 9096 .core_sched_before = sched_ext_ops__core_sched_before, 9097 .set_weight = sched_ext_ops__set_weight, 9098 .set_cmask = sched_ext_ops_cid__set_cmask, 9099 .update_idle = sched_ext_ops__update_idle, 9100 .init_task = sched_ext_ops__init_task, 9101 .exit_task = sched_ext_ops__exit_task, 9102 .enable = sched_ext_ops_cid__enable, 9103 .disable = sched_ext_ops__disable, 9104 #ifdef CONFIG_EXT_GROUP_SCHED 9105 .cpuctl_init = sched_ext_ops__cgroup_init, 9106 .cpuctl_exit = sched_ext_ops__cgroup_exit, 9107 .cpuctl_prep_move = sched_ext_ops__cgroup_prep_move, 9108 .cpuctl_move = sched_ext_ops__cgroup_move, 9109 .cpuctl_cancel_move = sched_ext_ops__cgroup_cancel_move, 9110 .cpuctl_set_weight = sched_ext_ops__cgroup_set_weight, 9111 .cpuctl_set_bandwidth = sched_ext_ops__cgroup_set_bandwidth, 9112 .cpuctl_set_idle = sched_ext_ops__cgroup_set_idle, 9113 #endif 9114 .sub_attach = sched_ext_ops__sub_attach, 9115 .sub_detach = sched_ext_ops__sub_detach, 9116 .sub_caps_updated = sched_ext_ops__sub_caps_updated, 9117 .sub_ecaps_updated = sched_ext_ops__sub_ecaps_updated, 9118 .sub_cid_sched_updated = sched_ext_ops__sub_cid_sched_updated, 9119 .sub_child_ecaps_updated = sched_ext_ops__sub_child_ecaps_updated, 9120 .cid_online = sched_ext_ops__cpu_online, 9121 .cid_offline = sched_ext_ops__cpu_offline, 9122 .init_cids = sched_ext_ops__init_cids, 9123 .init = sched_ext_ops__init, 9124 .exit = sched_ext_ops__exit, 9125 .dump = sched_ext_ops__dump, 9126 .dump_cid = sched_ext_ops__dump_cpu, 9127 .dump_task = sched_ext_ops__dump_task, 9128 }; 9129 9130 /* 9131 * The cid-form struct_ops shares all bpf_struct_ops hooks with the cpu form. 9132 * init_member, check_member, reg, unreg, etc. process kdata as the byte block 9133 * verified to match by the BUILD_BUG_ON checks in scx_init(). 9134 */ 9135 static struct bpf_struct_ops bpf_sched_ext_ops_cid = { 9136 .verifier_ops = &bpf_scx_cid_verifier_ops, 9137 .reg = bpf_scx_reg_cid, 9138 .unreg = bpf_scx_unreg, 9139 .check_member = bpf_scx_check_member, 9140 .init_member = bpf_scx_init_member, 9141 .init = bpf_scx_init, 9142 .update = bpf_scx_update, 9143 .validate = bpf_scx_validate, 9144 .name = "sched_ext_ops_cid", 9145 .owner = THIS_MODULE, 9146 .cfi_stubs = &__bpf_ops_sched_ext_ops_cid 9147 }; 9148 9149 9150 /******************************************************************************** 9151 * System integration and init. 9152 */ 9153 9154 static void sysrq_handle_sched_ext_reset(u8 key) 9155 { 9156 struct scx_sched *sch; 9157 9158 sch = rcu_dereference(scx_root); 9159 if (likely(sch)) 9160 scx_disable(sch, SCX_EXIT_SYSRQ); 9161 else 9162 pr_info("sched_ext: BPF schedulers not loaded\n"); 9163 } 9164 9165 static const struct sysrq_key_op sysrq_sched_ext_reset_op = { 9166 .handler = sysrq_handle_sched_ext_reset, 9167 .help_msg = "reset-sched-ext(S)", 9168 .action_msg = "Disable sched_ext and revert all tasks to CFS", 9169 .enable_mask = SYSRQ_ENABLE_RTNICE, 9170 }; 9171 9172 static void sysrq_handle_sched_ext_dump(u8 key) 9173 { 9174 struct scx_exit_info ei = { 9175 .kind = SCX_EXIT_NONE, 9176 .exit_cpu = -1, 9177 .reason = "SysRq-D", 9178 }; 9179 struct scx_sched *sch; 9180 9181 list_for_each_entry_rcu(sch, &scx_sched_all, all) 9182 scx_dump_state(sch, &ei, 0, false); 9183 } 9184 9185 static const struct sysrq_key_op sysrq_sched_ext_dump_op = { 9186 .handler = sysrq_handle_sched_ext_dump, 9187 .help_msg = "dump-sched-ext(D)", 9188 .action_msg = "Trigger sched_ext debug dump", 9189 .enable_mask = SYSRQ_ENABLE_RTNICE, 9190 }; 9191 9192 static bool can_skip_idle_kick(struct rq *rq) 9193 { 9194 lockdep_assert_rq_held(rq); 9195 9196 /* 9197 * We can skip idle kicking if @rq is going to go through at least one 9198 * full SCX scheduling cycle before going idle. Just checking whether 9199 * curr is not idle is insufficient because we could be racing 9200 * dispatch_one() trying to pull the next task from a remote rq, which 9201 * may fail, and @rq may become idle afterwards. 9202 * 9203 * The race window is small and we don't and can't guarantee that @rq is 9204 * only kicked while idle anyway. Skip only when sure. 9205 */ 9206 return !is_idle_task(rq->curr) && !(rq->scx.flags & SCX_RQ_IN_DISPATCH); 9207 } 9208 9209 static bool kick_one_cpu(s32 cpu, struct scx_sched_pcpu *pcpu, struct rq *this_rq, 9210 unsigned long *ksyncs) 9211 { 9212 struct rq *rq = cpu_rq(cpu); 9213 struct scx_rq *this_scx = &this_rq->scx; 9214 struct rq_flags rf; 9215 const struct sched_class *cur_class; 9216 bool should_wait = false; 9217 bool kickable; 9218 bool preempt, preempt_lazy, wait, immediate; 9219 9220 rq_lock_irqsave(rq, &rf); 9221 cur_class = rq->donor->sched_class; 9222 preempt = cpumask_test_cpu(cpu, pcpu->cpus_to_preempt); 9223 preempt_lazy = cpumask_test_cpu(cpu, pcpu->cpus_to_preempt_lazy); 9224 wait = cpumask_test_cpu(cpu, pcpu->cpus_to_wait); 9225 /* 9226 * Immediate preemption, waiting and a plain kick take precedence over 9227 * lazy preemption. The lazy request still clears the slice, so all 9228 * accumulated requests are served. 9229 */ 9230 immediate = preempt || wait || cpumask_test_cpu(cpu, pcpu->cpus_to_kick); 9231 9232 /* 9233 * During CPU hotplug, a CPU may depend on kicking itself to make 9234 * forward progress. Allow kicking self regardless of online state. If 9235 * @cpu is running a higher class task, we have no control over @cpu. 9236 * Skip kicking. A sub-sched lacking baseline access on @cid has no 9237 * business forcing a reschedule there - skip. This is the authoritative 9238 * cap check: ecaps is read here under @rq's lock. 9239 */ 9240 kickable = (cpu_online(cpu) || cpu == cpu_of(this_rq)) && 9241 !sched_class_above(cur_class, &ext_sched_class); 9242 9243 if (kickable && !scx_missing_caps(pcpu->sch, cpu, SCX_CAP_BASE)) { 9244 if (preempt || preempt_lazy) { 9245 if (cur_class == &ext_sched_class) { 9246 u64 caps = scx_caps_for_preempt(pcpu->sch, rq, 0); 9247 9248 if (unlikely(scx_missing_caps(pcpu->sch, cpu, caps))) { 9249 __scx_add_event(pcpu->sch, SCX_EV_SUB_PREEMPT_DENIED, 1); 9250 /* degrade to a plain, immediate kick */ 9251 immediate = true; 9252 } else if (unlikely(!scx_set_task_slice(rq->donor, 0))) { 9253 __scx_add_event(pcpu->sch, SCX_EV_SLICE_DENIED, 1); 9254 } 9255 } 9256 cpumask_clear_cpu(cpu, pcpu->cpus_to_preempt); 9257 cpumask_clear_cpu(cpu, pcpu->cpus_to_preempt_lazy); 9258 } 9259 9260 if (wait) { 9261 if (cur_class == &ext_sched_class) { 9262 cpumask_set_cpu(cpu, this_scx->cpus_to_sync); 9263 ksyncs[cpu] = rq->scx.kick_sync; 9264 should_wait = true; 9265 } 9266 cpumask_clear_cpu(cpu, pcpu->cpus_to_wait); 9267 } 9268 9269 if (immediate) 9270 resched_curr(rq); 9271 else 9272 scx_resched_curr_lazy(rq); 9273 } else { 9274 /* a kickable cpu was skipped solely for the missing caps */ 9275 if (kickable) 9276 __scx_add_event(pcpu->sch, SCX_EV_SUB_KICK_DENIED, 1); 9277 cpumask_clear_cpu(cpu, pcpu->cpus_to_preempt); 9278 cpumask_clear_cpu(cpu, pcpu->cpus_to_preempt_lazy); 9279 cpumask_clear_cpu(cpu, pcpu->cpus_to_wait); 9280 } 9281 9282 scx_rq_lock_drop(rq); 9283 rq_unlock_irqrestore(rq, &rf); 9284 9285 return should_wait; 9286 } 9287 9288 static void kick_one_cpu_if_idle(s32 cpu, struct scx_sched_pcpu *pcpu, 9289 struct rq *this_rq) 9290 { 9291 struct rq *rq = cpu_rq(cpu); 9292 unsigned long flags; 9293 9294 raw_spin_rq_lock_irqsave(rq, flags); 9295 9296 /* idle kicks need baseline access too, see kick_one_cpu() */ 9297 if (!can_skip_idle_kick(rq) && 9298 (cpu_online(cpu) || cpu == cpu_of(this_rq))) { 9299 if (likely(!scx_missing_caps(pcpu->sch, cpu, SCX_CAP_BASE))) 9300 resched_curr(rq); 9301 else 9302 __scx_add_event(pcpu->sch, SCX_EV_SUB_KICK_DENIED, 1); 9303 } 9304 9305 scx_rq_lock_drop(rq); 9306 raw_spin_rq_unlock_irqrestore(rq, flags); 9307 } 9308 9309 static void kick_cpus_irq_workfn(struct irq_work *irq_work) 9310 { 9311 struct rq *this_rq = this_rq(); 9312 struct scx_rq *this_scx = &this_rq->scx; 9313 struct scx_kick_syncs __rcu *ksyncs_pcpu = __this_cpu_read(scx_kick_syncs); 9314 struct scx_sched_pcpu *pcpu, *tmp; 9315 bool should_wait = false; 9316 unsigned long *ksyncs; 9317 s32 cpu; 9318 9319 /* can race with free_kick_syncs() during scheduler disable */ 9320 if (unlikely(!ksyncs_pcpu)) 9321 return; 9322 9323 ksyncs = rcu_dereference_bh(ksyncs_pcpu)->syncs; 9324 9325 /* 9326 * Walk scheds with pending kicks on this cpu. scx_kick_cpu() adds to 9327 * the list under local_irq_save() and only this irq_work consumes it. 9328 * A plain list without locking is sufficient. 9329 */ 9330 list_for_each_entry_safe(pcpu, tmp, &this_scx->sched_pcpus_to_kick, to_kick_node) { 9331 list_del_init(&pcpu->to_kick_node); 9332 9333 for_each_cpu_or(cpu, pcpu->cpus_to_kick, pcpu->cpus_to_preempt_lazy) { 9334 should_wait |= kick_one_cpu(cpu, pcpu, this_rq, ksyncs); 9335 cpumask_clear_cpu(cpu, pcpu->cpus_to_kick); 9336 cpumask_clear_cpu(cpu, pcpu->cpus_to_kick_if_idle); 9337 } 9338 9339 for_each_cpu(cpu, pcpu->cpus_to_kick_if_idle) { 9340 kick_one_cpu_if_idle(cpu, pcpu, this_rq); 9341 cpumask_clear_cpu(cpu, pcpu->cpus_to_kick_if_idle); 9342 } 9343 } 9344 9345 /* 9346 * Can't wait in hardirq — kick_sync can't advance, deadlocking if 9347 * CPUs wait for each other. Defer to kick_sync_wait_bal_cb(). 9348 */ 9349 if (should_wait) { 9350 raw_spin_rq_lock(this_rq); 9351 this_scx->kick_sync_pending = true; 9352 resched_curr(this_rq); 9353 scx_rq_lock_drop(this_rq); 9354 raw_spin_rq_unlock(this_rq); 9355 } 9356 } 9357 9358 /** 9359 * print_scx_info - print out sched_ext scheduler state 9360 * @log_lvl: the log level to use when printing 9361 * @p: target task 9362 * 9363 * If a sched_ext scheduler is enabled, print the name and state of the 9364 * scheduler. If @p is on sched_ext, print further information about the task. 9365 * 9366 * This function can be safely called on any task as long as the task_struct 9367 * itself is accessible. While safe, this function isn't synchronized and may 9368 * print out mixups or garbages of limited length. 9369 */ 9370 void print_scx_info(const char *log_lvl, struct task_struct *p) 9371 { 9372 struct scx_sched *sch; 9373 enum scx_enable_state state = scx_enable_state(); 9374 const char *all = READ_ONCE(scx_switching_all) ? "+all" : ""; 9375 char runnable_at_buf[22] = "?"; 9376 struct sched_class *class; 9377 unsigned long runnable_at; 9378 9379 guard(rcu)(); 9380 9381 sch = scx_task_sched_rcu(p); 9382 9383 if (!sch) 9384 return; 9385 9386 /* 9387 * Carefully check if the task was running on sched_ext, and then 9388 * carefully copy the time it's been runnable, and its state. 9389 */ 9390 if (copy_from_kernel_nofault(&class, &p->sched_class, sizeof(class)) || 9391 class != &ext_sched_class) { 9392 printk("%sSched_ext: %s (%s%s)", log_lvl, sch->ops.name, 9393 scx_enable_state_str[state], all); 9394 return; 9395 } 9396 9397 if (!copy_from_kernel_nofault(&runnable_at, &p->scx.runnable_at, 9398 sizeof(runnable_at))) 9399 scnprintf(runnable_at_buf, sizeof(runnable_at_buf), "%+ldms", 9400 jiffies_delta_msecs(runnable_at, jiffies)); 9401 9402 /* print everything onto one line to conserve console space */ 9403 printk("%sSched_ext: %s (%s%s), task: runnable_at=%s", 9404 log_lvl, sch->ops.name, scx_enable_state_str[state], all, 9405 runnable_at_buf); 9406 } 9407 9408 static int scx_pm_handler(struct notifier_block *nb, unsigned long event, void *ptr) 9409 { 9410 struct scx_sched *sch; 9411 9412 guard(rcu)(); 9413 9414 sch = rcu_dereference(scx_root); 9415 if (!sch) 9416 return NOTIFY_OK; 9417 9418 /* 9419 * SCX schedulers often have userspace components which are sometimes 9420 * involved in critial scheduling paths. PM operations involve freezing 9421 * userspace which can lead to scheduling misbehaviors including stalls. 9422 * Let's bypass while PM operations are in progress. 9423 */ 9424 switch (event) { 9425 case PM_HIBERNATION_PREPARE: 9426 case PM_SUSPEND_PREPARE: 9427 case PM_RESTORE_PREPARE: 9428 scx_bypass(sch, true); 9429 break; 9430 case PM_POST_HIBERNATION: 9431 case PM_POST_SUSPEND: 9432 case PM_POST_RESTORE: 9433 scx_bypass(sch, false); 9434 break; 9435 } 9436 9437 return NOTIFY_OK; 9438 } 9439 9440 static struct notifier_block scx_pm_notifier = { 9441 .notifier_call = scx_pm_handler, 9442 }; 9443 9444 void __init init_sched_ext_class(void) 9445 { 9446 s32 cpu, v; 9447 9448 /* 9449 * The following is to prevent the compiler from optimizing out the enum 9450 * definitions so that BPF scheduler implementations can use them 9451 * through the generated vmlinux.h. 9452 */ 9453 WRITE_ONCE(v, SCX_ENQ_WAKEUP | SCX_DEQ_SLEEP | SCX_KICK_PREEMPT | 9454 SCX_TG_ONLINE); 9455 9456 scx_idle_init_masks(); 9457 9458 for_each_possible_cpu(cpu) { 9459 struct rq *rq = cpu_rq(cpu); 9460 int n = cpu_to_node(cpu); 9461 9462 /* local_dsq's sch will be set during scx_root_enable() */ 9463 BUG_ON(scx_init_dsq(&rq->scx.local_dsq, SCX_DSQ_LOCAL, NULL)); 9464 BUG_ON(scx_init_dsq(&rq->scx.reject_dsq, SCX_DSQ_REJECT, NULL)); 9465 #ifdef CONFIG_EXT_SUB_SCHED 9466 scx_rescue_init(rq); 9467 #endif 9468 9469 INIT_LIST_HEAD(&rq->scx.runnable_list); 9470 INIT_LIST_HEAD(&rq->scx.ddsp_deferred_locals); 9471 9472 BUG_ON(!zalloc_cpumask_var_node(&rq->scx.cpus_to_sync, GFP_KERNEL, n)); 9473 INIT_LIST_HEAD(&rq->scx.sched_pcpus_to_kick); 9474 raw_spin_lock_init(&rq->scx.deferred_reenq_lock); 9475 INIT_LIST_HEAD(&rq->scx.deferred_reenq_locals); 9476 INIT_LIST_HEAD(&rq->scx.deferred_reenq_users); 9477 rq->scx.deferred_irq_work = IRQ_WORK_INIT_HARD(deferred_irq_workfn); 9478 rq->scx.kick_cpus_irq_work = IRQ_WORK_INIT_HARD(kick_cpus_irq_workfn); 9479 9480 if (cpu_online(cpu)) 9481 cpu_rq(cpu)->scx.flags |= SCX_RQ_ONLINE; 9482 } 9483 9484 register_sysrq_key('S', &sysrq_sched_ext_reset_op); 9485 register_sysrq_key('D', &sysrq_sched_ext_dump_op); 9486 INIT_DELAYED_WORK(&scx_watchdog_work, scx_watchdog_workfn); 9487 9488 #ifdef CONFIG_EXT_SUB_SCHED 9489 BUG_ON(rhashtable_init(&scx_sched_hash, &scx_sched_hash_params)); 9490 #endif /* CONFIG_EXT_SUB_SCHED */ 9491 } 9492 9493 9494 /******************************************************************************** 9495 * Helpers that can be called from the BPF scheduler. 9496 */ 9497 static bool scx_vet_enq_flags(struct scx_sched *sch, u64 dsq_id, u64 *enq_flags) 9498 { 9499 bool is_local = dsq_id == SCX_DSQ_LOCAL || 9500 (dsq_id & SCX_DSQ_LOCAL_ON) == SCX_DSQ_LOCAL_ON; 9501 9502 if (unlikely(*enq_flags & __SCX_ENQ_INTERNAL_MASK)) { 9503 scx_error(sch, "invalid enq_flags 0x%llx", *enq_flags); 9504 return false; 9505 } 9506 9507 if (*enq_flags & SCX_ENQ_IMMED) { 9508 if (unlikely(!is_local)) { 9509 scx_error(sch, "SCX_ENQ_IMMED on a non-local DSQ 0x%llx", dsq_id); 9510 return false; 9511 } 9512 } else if ((sch->ops.flags & SCX_OPS_ALWAYS_ENQ_IMMED) && is_local) { 9513 *enq_flags |= SCX_ENQ_IMMED; 9514 } 9515 9516 if (unlikely((*enq_flags & SCX_ENQ_RESCUE) && !is_local)) { 9517 scx_error(sch, "SCX_ENQ_RESCUE on a non-local DSQ 0x%llx", dsq_id); 9518 return false; 9519 } 9520 9521 return true; 9522 } 9523 9524 static bool scx_dsq_insert_preamble(struct scx_sched *sch, struct task_struct *p, 9525 u64 dsq_id, u64 *enq_flags) 9526 { 9527 lockdep_assert_irqs_disabled(); 9528 9529 if (unlikely(!p)) { 9530 scx_error(sch, "called with NULL task"); 9531 return false; 9532 } 9533 9534 /* see SCX_EV_INSERT_NOT_OWNED definition */ 9535 if (unlikely(!scx_task_on_sched(sch, p))) { 9536 __scx_add_event(sch, SCX_EV_INSERT_NOT_OWNED, 1); 9537 return false; 9538 } 9539 9540 if (!scx_vet_enq_flags(sch, dsq_id, enq_flags)) 9541 return false; 9542 9543 return true; 9544 } 9545 9546 static void scx_dsq_insert_commit(struct scx_sched *sch, struct task_struct *p, 9547 u64 dsq_id, u64 slice, u64 vtime, u64 enq_flags) 9548 { 9549 struct scx_dsp_ctx *dspc = &this_cpu_ptr(sch->pcpu)->dsp_ctx; 9550 struct task_struct *ddsp_task; 9551 9552 ddsp_task = __this_cpu_read(direct_dispatch_task); 9553 if (ddsp_task) { 9554 mark_direct_dispatch(sch, ddsp_task, p, dsq_id, slice, vtime, enq_flags); 9555 return; 9556 } 9557 9558 if (unlikely(dspc->cursor >= sch->dsp_max_batch)) { 9559 scx_error(sch, "dispatch buffer overflow"); 9560 return; 9561 } 9562 9563 dspc->buf[dspc->cursor++] = (struct scx_dsp_buf_ent){ 9564 .task = p, 9565 .qseq = atomic_long_read(&p->scx.ops_state) & SCX_OPSS_QSEQ_MASK, 9566 .dsq_id = dsq_id, 9567 .slice = slice, 9568 .vtime = vtime, 9569 .enq_flags = enq_flags, 9570 }; 9571 } 9572 9573 __bpf_kfunc_start_defs(); 9574 9575 /** 9576 * scx_bpf_dsq_insert___v2 - Insert a task into the FIFO queue of a DSQ 9577 * @p: task_struct to insert 9578 * @dsq_id: DSQ to insert into 9579 * @slice: duration @p can run for in nsecs, 0 to keep the current value 9580 * @enq_flags: SCX_ENQ_* 9581 * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs 9582 * 9583 * Insert @p into the FIFO queue of the DSQ identified by @dsq_id. It is safe to 9584 * call this function spuriously. Can be called from ops.enqueue(), 9585 * ops.select_cpu(), and ops.dispatch(). 9586 * 9587 * When called from ops.select_cpu() or ops.enqueue(), it's for direct dispatch 9588 * and @p must match the task being enqueued. 9589 * 9590 * When called from ops.select_cpu(), @enq_flags and @dsq_id are stored, and @p 9591 * will be directly inserted into the corresponding dispatch queue after 9592 * ops.select_cpu() returns. If @p is inserted into SCX_DSQ_LOCAL, it will be 9593 * inserted into the local DSQ of the CPU returned by ops.select_cpu(). 9594 * @enq_flags are OR'd with the enqueue flags on the enqueue path before the 9595 * task is inserted. 9596 * 9597 * When called from ops.dispatch(), there are no restrictions on @p or @dsq_id 9598 * and this function can be called up to ops.dispatch_max_batch times to insert 9599 * multiple tasks. scx_bpf_dispatch_nr_slots() returns the number of the 9600 * remaining slots. scx_bpf_dsq_move_to_local() flushes the batch and resets the 9601 * counter. 9602 * 9603 * This function doesn't have any locking restrictions and may be called under 9604 * BPF locks (in the future when BPF introduces more flexible locking). 9605 * 9606 * @p is allowed to run for @slice. The scheduling path is triggered on slice 9607 * exhaustion. If zero, the current residual slice is maintained. If 9608 * %SCX_SLICE_INF, @p never expires and the BPF scheduler must kick the CPU with 9609 * scx_bpf_kick_cpu() to trigger scheduling. 9610 * 9611 * Returns %true on successful insertion, %false on failure. On the root 9612 * scheduler, %false return triggers scheduler abort and the caller doesn't need 9613 * to check the return value. 9614 */ 9615 __bpf_kfunc bool scx_bpf_dsq_insert___v2(struct task_struct *p, u64 dsq_id, 9616 u64 slice, u64 enq_flags, 9617 const struct bpf_prog_aux *aux) 9618 { 9619 struct scx_sched *sch; 9620 9621 guard(rcu)(); 9622 sch = scx_prog_sched(aux); 9623 if (unlikely(!sch)) 9624 return false; 9625 9626 if (!scx_dsq_insert_preamble(sch, p, dsq_id, &enq_flags)) 9627 return false; 9628 9629 scx_dsq_insert_commit(sch, p, dsq_id, slice, 0, enq_flags); 9630 9631 return true; 9632 } 9633 9634 /* 9635 * COMPAT: Will be removed in v6.23 along with the ___v2 suffix. 9636 */ 9637 __bpf_kfunc void scx_bpf_dsq_insert(struct task_struct *p, u64 dsq_id, 9638 u64 slice, u64 enq_flags, 9639 const struct bpf_prog_aux *aux) 9640 { 9641 scx_bpf_dsq_insert___v2(p, dsq_id, slice, enq_flags, aux); 9642 } 9643 9644 static bool scx_dsq_insert_vtime(struct scx_sched *sch, struct task_struct *p, 9645 u64 dsq_id, u64 slice, u64 vtime, u64 enq_flags) 9646 { 9647 if (!scx_dsq_insert_preamble(sch, p, dsq_id, &enq_flags)) 9648 return false; 9649 9650 scx_dsq_insert_commit(sch, p, dsq_id, slice, vtime, enq_flags | SCX_ENQ_DSQ_PRIQ); 9651 9652 return true; 9653 } 9654 9655 struct scx_bpf_dsq_insert_vtime_args { 9656 /* @p can't be packed together as KF_RCU is not transitive */ 9657 u64 dsq_id; 9658 u64 slice; 9659 u64 vtime; 9660 u64 enq_flags; 9661 }; 9662 9663 /** 9664 * __scx_bpf_dsq_insert_vtime - Arg-wrapped vtime DSQ insertion 9665 * @p: task_struct to insert 9666 * @args: struct containing the rest of the arguments 9667 * @args->dsq_id: DSQ to insert into 9668 * @args->slice: duration @p can run for in nsecs, 0 to keep the current value 9669 * @args->vtime: @p's ordering inside the vtime-sorted queue of the target DSQ 9670 * @args->enq_flags: SCX_ENQ_* 9671 * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs 9672 * 9673 * Wrapper kfunc that takes arguments via struct to work around BPF's 5 argument 9674 * limit. BPF programs should use scx_bpf_dsq_insert_vtime() which is provided 9675 * as an inline wrapper in common.bpf.h. 9676 * 9677 * Insert @p into the vtime priority queue of the DSQ identified by 9678 * @args->dsq_id. Tasks queued into the priority queue are ordered by 9679 * @args->vtime. All other aspects are identical to scx_bpf_dsq_insert(). 9680 * 9681 * @args->vtime ordering is according to time_before64() which considers 9682 * wrapping. A numerically larger vtime may indicate an earlier position in the 9683 * ordering and vice-versa. vtime is a rolling cursor and values used for 9684 * ordering within a given DSQ should stay less than 2^63 apart for 9685 * time_before64() ordering to remain well-defined. 9686 * 9687 * A DSQ can only be used as a FIFO or priority queue at any given time and this 9688 * function must not be called on a DSQ which already has one or more FIFO tasks 9689 * queued and vice-versa. Also, the built-in DSQs (SCX_DSQ_LOCAL and 9690 * SCX_DSQ_GLOBAL) cannot be used as priority queues. 9691 * 9692 * Returns %true on successful insertion, %false on failure. On the root 9693 * scheduler, %false return triggers scheduler abort and the caller doesn't need 9694 * to check the return value. 9695 */ 9696 __bpf_kfunc bool 9697 __scx_bpf_dsq_insert_vtime(struct task_struct *p, 9698 struct scx_bpf_dsq_insert_vtime_args *args, 9699 const struct bpf_prog_aux *aux) 9700 { 9701 struct scx_sched *sch; 9702 9703 guard(rcu)(); 9704 9705 sch = scx_prog_sched(aux); 9706 if (unlikely(!sch)) 9707 return false; 9708 9709 return scx_dsq_insert_vtime(sch, p, args->dsq_id, args->slice, 9710 args->vtime, args->enq_flags); 9711 } 9712 9713 /* 9714 * COMPAT: Will be removed in v6.23. 9715 */ 9716 __bpf_kfunc void scx_bpf_dsq_insert_vtime(struct task_struct *p, u64 dsq_id, 9717 u64 slice, u64 vtime, u64 enq_flags) 9718 { 9719 struct scx_sched *sch; 9720 9721 guard(rcu)(); 9722 9723 sch = rcu_dereference(scx_root); 9724 if (unlikely(!sch)) 9725 return; 9726 9727 #ifdef CONFIG_EXT_SUB_SCHED 9728 /* 9729 * Disallow if any sub-scheds are attached. There is no way to tell 9730 * which scheduler called us, so error out @p's scheduler -- read it 9731 * under RCU as @p's locks aren't necessarily held here. @p may be a 9732 * task past sched_ext_dead() or an idle task, in which case its 9733 * scheduler can't be determined and there is nothing obviously wrong 9734 * to report; just refuse the call. 9735 */ 9736 if (unlikely(!list_empty(&sch->children))) { 9737 struct scx_sched *tsch = scx_task_sched_rcu(p); 9738 9739 if (tsch) 9740 scx_error(tsch, "__scx_bpf_dsq_insert_vtime() must be used"); 9741 return; 9742 } 9743 #endif 9744 9745 scx_dsq_insert_vtime(sch, p, dsq_id, slice, vtime, enq_flags); 9746 } 9747 9748 __bpf_kfunc_end_defs(); 9749 9750 BTF_KFUNCS_START(scx_kfunc_ids_enqueue_dispatch) 9751 BTF_ID_FLAGS(func, scx_bpf_dsq_insert, KF_IMPLICIT_ARGS | KF_RCU) 9752 BTF_ID_FLAGS(func, scx_bpf_dsq_insert___v2, KF_IMPLICIT_ARGS | KF_RCU) 9753 BTF_ID_FLAGS(func, __scx_bpf_dsq_insert_vtime, KF_IMPLICIT_ARGS | KF_RCU) 9754 BTF_ID_FLAGS(func, scx_bpf_dsq_insert_vtime, KF_RCU) 9755 BTF_KFUNCS_END(scx_kfunc_ids_enqueue_dispatch) 9756 9757 static const struct btf_kfunc_id_set scx_kfunc_set_enqueue_dispatch = { 9758 .owner = THIS_MODULE, 9759 .set = &scx_kfunc_ids_enqueue_dispatch, 9760 .filter = scx_kfunc_context_filter, 9761 }; 9762 9763 /* 9764 * Lock @rq from a kfunc called either from ops.dispatch(), which holds the 9765 * dispatched rq's lock, or from a context holding no rq lock. Under core 9766 * scheduling, dispatch can run for a sibling rq, so the locked rq is not 9767 * necessarily this CPU's. Return the rq locked on entry, NULL if none. 9768 */ 9769 static struct rq *kf_switch_rq_lock(struct rq *rq, unsigned long *flags) 9770 { 9771 struct rq *entry_rq; 9772 9773 local_irq_save(*flags); 9774 9775 entry_rq = scx_locked_rq(); 9776 if (entry_rq) { 9777 if (entry_rq != rq) 9778 switch_rq_lock(entry_rq, rq); 9779 } else { 9780 raw_spin_rq_lock(rq); 9781 } 9782 return entry_rq; 9783 } 9784 9785 /* undo kf_switch_rq_lock(), @rq is the rq locked now */ 9786 static void kf_restore_rq_lock(struct rq *rq, struct rq *entry_rq, unsigned long flags) 9787 { 9788 if (entry_rq) { 9789 if (entry_rq != rq) 9790 switch_rq_lock(rq, entry_rq); 9791 } else { 9792 scx_rq_lock_drop(rq); 9793 raw_spin_rq_unlock_irqrestore(rq, flags); 9794 } 9795 } 9796 9797 static bool scx_dsq_move(struct bpf_iter_scx_dsq_kern *kit, 9798 struct task_struct *p, u64 dsq_id, u64 enq_flags, 9799 bool priq) 9800 { 9801 struct scx_dispatch_q *src_dsq = kit->dsq, *dst_dsq; 9802 struct scx_sched *sch; 9803 struct rq *p_rq, *src_rq, *locked_rq; 9804 bool dispatched = false; 9805 unsigned long flags; 9806 9807 /* 9808 * The verifier considers an iterator slot initialized on any 9809 * KF_ITER_NEW return, so a BPF program may legally reach here after 9810 * bpf_iter_scx_dsq_new() failed and left @kit->dsq NULL. 9811 */ 9812 if (unlikely(!src_dsq)) 9813 return false; 9814 9815 sch = src_dsq->sched; 9816 9817 if (!scx_vet_enq_flags(sch, dsq_id, &enq_flags)) 9818 return false; 9819 9820 /* internal bit, can only go in after @enq_flags is vetted */ 9821 if (priq) 9822 enq_flags |= SCX_ENQ_DSQ_PRIQ; 9823 9824 /* 9825 * If the BPF scheduler keeps calling this function repeatedly, it can 9826 * cause similar live-lock conditions as scx_consume_dispatch_q(). 9827 */ 9828 if (unlikely(READ_ONCE(sch->aborting))) 9829 return false; 9830 9831 src_rq = task_rq(p); 9832 locked_rq = kf_switch_rq_lock(src_rq, &flags); 9833 9834 p_rq = src_rq; 9835 raw_spin_lock(&src_dsq->lock); 9836 9837 /* did someone else get to it while we dropped the locks? */ 9838 if (nldsq_cursor_lost_task(&kit->cursor, src_rq, src_dsq, p)) { 9839 raw_spin_unlock(&src_dsq->lock); 9840 goto out; 9841 } 9842 9843 /* 9844 * @p has been on $src_dsq and can't move anymore. If @p is not on @sch, 9845 * the caller didn't have authority over @p at the time of the call. 9846 */ 9847 if (unlikely(!scx_task_on_sched(sch, p))) { 9848 scx_error(sch, "scx_bpf_dsq_move[_vtime]() on %s[%d] but the task belongs to a different scheduler", 9849 p->comm, p->pid); 9850 raw_spin_unlock(&src_dsq->lock); 9851 goto out; 9852 } 9853 9854 /* @p is still on $src_dsq and stable, determine the destination */ 9855 dst_dsq = find_dsq_for_dispatch(sch, locked_rq ?: this_rq(), dsq_id, task_cpu(p)); 9856 9857 /* 9858 * Apply vtime and slice updates before moving. @p is still on $src_dsq 9859 * with both $src_dsq and its task_rq locked, satisfying the write 9860 * rules, and the PRIQ insertion into $dst_dsq reads the new vtime. 9861 */ 9862 if (kit->cursor.flags & __SCX_DSQ_ITER_HAS_VTIME) 9863 p->scx.dsq_vtime = kit->vtime; 9864 if (kit->cursor.flags & __SCX_DSQ_ITER_HAS_SLICE) 9865 scx_set_task_slice(p, kit->slice); 9866 9867 /* execute move */ 9868 p_rq = move_task_between_dsqs(sch, p, enq_flags, src_dsq, dst_dsq); 9869 dispatched = true; 9870 out: 9871 kf_restore_rq_lock(p_rq, locked_rq, flags); 9872 9873 kit->cursor.flags &= ~(__SCX_DSQ_ITER_HAS_SLICE | 9874 __SCX_DSQ_ITER_HAS_VTIME); 9875 return dispatched; 9876 } 9877 9878 __bpf_kfunc_start_defs(); 9879 9880 /** 9881 * scx_bpf_dispatch_nr_slots - Return the number of remaining dispatch slots 9882 * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs 9883 * 9884 * Can only be called from ops.dispatch(). 9885 */ 9886 __bpf_kfunc u32 scx_bpf_dispatch_nr_slots(const struct bpf_prog_aux *aux) 9887 { 9888 struct scx_sched *sch; 9889 9890 guard(rcu)(); 9891 9892 sch = scx_prog_sched(aux); 9893 if (unlikely(!sch)) 9894 return 0; 9895 9896 return sch->dsp_max_batch - __this_cpu_read(sch->pcpu->dsp_ctx.cursor); 9897 } 9898 9899 /** 9900 * scx_bpf_dispatch_cancel - Cancel the latest dispatch 9901 * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs 9902 * 9903 * Cancel the latest dispatch. Can be called multiple times to cancel further 9904 * dispatches. Can only be called from ops.dispatch(). 9905 */ 9906 __bpf_kfunc void scx_bpf_dispatch_cancel(const struct bpf_prog_aux *aux) 9907 { 9908 struct scx_sched *sch; 9909 struct scx_dsp_ctx *dspc; 9910 9911 guard(rcu)(); 9912 9913 sch = scx_prog_sched(aux); 9914 if (unlikely(!sch)) 9915 return; 9916 9917 dspc = &this_cpu_ptr(sch->pcpu)->dsp_ctx; 9918 9919 if (dspc->cursor > 0) 9920 dspc->cursor--; 9921 else 9922 scx_error(sch, "dispatch buffer underflow"); 9923 } 9924 9925 /** 9926 * scx_bpf_dsq_move_to_local___v2 - move a task from a DSQ to the current CPU's local DSQ 9927 * @dsq_id: DSQ to move task from. Must be a user-created DSQ 9928 * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs 9929 * @enq_flags: %SCX_ENQ_* 9930 * 9931 * Move a task from the non-local DSQ identified by @dsq_id to the current CPU's 9932 * local DSQ for execution with @enq_flags applied. Can only be called from 9933 * ops.dispatch(). 9934 * 9935 * Built-in DSQs (%SCX_DSQ_GLOBAL and %SCX_DSQ_LOCAL*) are not supported as 9936 * sources. Local DSQs support reenqueueing (a task can be picked up for 9937 * execution, dequeued for property changes, or reenqueued), but the BPF 9938 * scheduler cannot directly iterate or move tasks from them. %SCX_DSQ_GLOBAL 9939 * is similar but also doesn't support reenqueueing, as it maps to multiple 9940 * per-node DSQs making the scope difficult to define; this may change in the 9941 * future. 9942 * 9943 * This function flushes the in-flight dispatches from scx_bpf_dsq_insert() 9944 * before trying to move from the specified DSQ. It may also grab rq locks and 9945 * thus can't be called under any BPF locks. 9946 * 9947 * Returns %true if a task has been moved, %false if there isn't any task to 9948 * move. 9949 */ 9950 __bpf_kfunc bool scx_bpf_dsq_move_to_local___v2(u64 dsq_id, u64 enq_flags, 9951 const struct bpf_prog_aux *aux) 9952 { 9953 struct scx_dispatch_q *dsq; 9954 struct scx_sched *sch; 9955 struct scx_dsp_ctx *dspc; 9956 9957 guard(rcu)(); 9958 9959 sch = scx_prog_sched(aux); 9960 if (unlikely(!sch)) 9961 return false; 9962 9963 if (!scx_vet_enq_flags(sch, SCX_DSQ_LOCAL, &enq_flags)) 9964 return false; 9965 9966 dspc = &this_cpu_ptr(sch->pcpu)->dsp_ctx; 9967 9968 scx_flush_dispatch_buf(sch, dspc->rq); 9969 9970 dsq = find_user_dsq(sch, dsq_id); 9971 if (unlikely(!dsq)) { 9972 scx_error(sch, "invalid DSQ ID 0x%016llx", dsq_id); 9973 return false; 9974 } 9975 9976 if (scx_consume_dispatch_q(sch, dspc->rq, dsq, enq_flags)) { 9977 /* 9978 * A successfully consumed task can be dequeued before it starts 9979 * running while the CPU is trying to migrate other dispatched 9980 * tasks. Bump nr_tasks to tell dispatch_one() to retry on empty 9981 * local DSQ. 9982 */ 9983 dspc->nr_tasks++; 9984 return true; 9985 } else { 9986 return false; 9987 } 9988 } 9989 9990 /* 9991 * COMPAT: ___v2 was introduced in v7.1. Remove this and ___v2 tag in the future. 9992 */ 9993 __bpf_kfunc bool scx_bpf_dsq_move_to_local(u64 dsq_id, const struct bpf_prog_aux *aux) 9994 { 9995 return scx_bpf_dsq_move_to_local___v2(dsq_id, 0, aux); 9996 } 9997 9998 /** 9999 * scx_bpf_dsq_move_set_slice - Override slice when moving between DSQs 10000 * @it__iter: DSQ iterator in progress 10001 * @slice: duration the moved task can run for in nsecs 10002 * 10003 * Override the slice of the next task that will be moved from @it__iter using 10004 * scx_bpf_dsq_move[_vtime](). If this function is not called, the previous 10005 * slice duration is kept. 10006 */ 10007 __bpf_kfunc void scx_bpf_dsq_move_set_slice(struct bpf_iter_scx_dsq *it__iter, 10008 u64 slice) 10009 { 10010 struct bpf_iter_scx_dsq_kern *kit = (void *)it__iter; 10011 10012 kit->slice = slice; 10013 kit->cursor.flags |= __SCX_DSQ_ITER_HAS_SLICE; 10014 } 10015 10016 /** 10017 * scx_bpf_dsq_move_set_vtime - Override vtime when moving between DSQs 10018 * @it__iter: DSQ iterator in progress 10019 * @vtime: task's ordering inside the vtime-sorted queue of the target DSQ 10020 * 10021 * Override the vtime of the next task that will be moved from @it__iter using 10022 * scx_bpf_dsq_move_vtime(). If this function is not called, the previous slice 10023 * vtime is kept. If scx_bpf_dsq_move() is used to dispatch the next task, the 10024 * override is ignored and cleared. 10025 */ 10026 __bpf_kfunc void scx_bpf_dsq_move_set_vtime(struct bpf_iter_scx_dsq *it__iter, 10027 u64 vtime) 10028 { 10029 struct bpf_iter_scx_dsq_kern *kit = (void *)it__iter; 10030 10031 kit->vtime = vtime; 10032 kit->cursor.flags |= __SCX_DSQ_ITER_HAS_VTIME; 10033 } 10034 10035 /** 10036 * scx_bpf_dsq_move - Move a task from DSQ iteration to a DSQ 10037 * @it__iter: DSQ iterator in progress 10038 * @p: task to transfer 10039 * @dsq_id: DSQ to move @p to 10040 * @enq_flags: SCX_ENQ_* 10041 * 10042 * Transfer @p which is on the DSQ currently iterated by @it__iter to the DSQ 10043 * specified by @dsq_id. All DSQs - local DSQs, global DSQ and user DSQs - can 10044 * be the destination. 10045 * 10046 * For the transfer to be successful, @p must still be on the DSQ and have been 10047 * queued before the DSQ iteration started. This function doesn't care whether 10048 * @p was obtained from the DSQ iteration. @p just has to be on the DSQ and have 10049 * been queued before the iteration started. 10050 * 10051 * @p's slice is kept by default. Use scx_bpf_dsq_move_set_slice() to update. 10052 * 10053 * Can be called from ops.dispatch() or any BPF context which doesn't hold a rq 10054 * lock (e.g. BPF timers or SYSCALL programs). 10055 * 10056 * Returns %true if @p has been consumed, %false if @p had already been 10057 * consumed, dequeued, or, for sub-scheds, @dsq_id points to a disallowed local 10058 * DSQ. 10059 */ 10060 __bpf_kfunc bool scx_bpf_dsq_move(struct bpf_iter_scx_dsq *it__iter, 10061 struct task_struct *p, u64 dsq_id, 10062 u64 enq_flags) 10063 { 10064 return scx_dsq_move((struct bpf_iter_scx_dsq_kern *)it__iter, 10065 p, dsq_id, enq_flags, false); 10066 } 10067 10068 /** 10069 * scx_bpf_dsq_move_vtime - Move a task from DSQ iteration to a PRIQ DSQ 10070 * @it__iter: DSQ iterator in progress 10071 * @p: task to transfer 10072 * @dsq_id: DSQ to move @p to 10073 * @enq_flags: SCX_ENQ_* 10074 * 10075 * Transfer @p which is on the DSQ currently iterated by @it__iter to the 10076 * priority queue of the DSQ specified by @dsq_id. The destination must be a 10077 * user DSQ as only user DSQs support priority queue. 10078 * 10079 * @p's slice and vtime are kept by default. Use scx_bpf_dsq_move_set_slice() 10080 * and scx_bpf_dsq_move_set_vtime() to update. 10081 * 10082 * All other aspects are identical to scx_bpf_dsq_move(). See 10083 * scx_bpf_dsq_insert_vtime() for more information on @vtime. 10084 */ 10085 __bpf_kfunc bool scx_bpf_dsq_move_vtime(struct bpf_iter_scx_dsq *it__iter, 10086 struct task_struct *p, u64 dsq_id, 10087 u64 enq_flags) 10088 { 10089 return scx_dsq_move((struct bpf_iter_scx_dsq_kern *)it__iter, 10090 p, dsq_id, enq_flags, true); 10091 } 10092 10093 __bpf_kfunc_end_defs(); 10094 10095 BTF_KFUNCS_START(scx_kfunc_ids_dispatch) 10096 BTF_ID_FLAGS(func, scx_bpf_dispatch_nr_slots, KF_IMPLICIT_ARGS) 10097 BTF_ID_FLAGS(func, scx_bpf_dispatch_cancel, KF_IMPLICIT_ARGS) 10098 BTF_ID_FLAGS(func, scx_bpf_dsq_move_to_local, KF_IMPLICIT_ARGS) 10099 BTF_ID_FLAGS(func, scx_bpf_dsq_move_to_local___v2, KF_IMPLICIT_ARGS) 10100 /* scx_bpf_dsq_move*() also in scx_kfunc_ids_unlocked: callable from unlocked contexts */ 10101 BTF_ID_FLAGS(func, scx_bpf_dsq_move_set_slice, KF_RCU) 10102 BTF_ID_FLAGS(func, scx_bpf_dsq_move_set_vtime, KF_RCU) 10103 BTF_ID_FLAGS(func, scx_bpf_dsq_move, KF_RCU) 10104 BTF_ID_FLAGS(func, scx_bpf_dsq_move_vtime, KF_RCU) 10105 /* also in scx_kfunc_ids_unlocked, same contexts as scx_bpf_dsq_move() */ 10106 BTF_ID_FLAGS(func, scx_bpf_dsq_reenq_task, KF_RCU) 10107 #ifdef CONFIG_EXT_SUB_SCHED 10108 BTF_ID_FLAGS(func, scx_bpf_sub_dispatch, KF_IMPLICIT_ARGS) 10109 #endif 10110 BTF_KFUNCS_END(scx_kfunc_ids_dispatch) 10111 10112 static const struct btf_kfunc_id_set scx_kfunc_set_dispatch = { 10113 .owner = THIS_MODULE, 10114 .set = &scx_kfunc_ids_dispatch, 10115 .filter = scx_kfunc_context_filter, 10116 }; 10117 10118 __bpf_kfunc_start_defs(); 10119 10120 /** 10121 * scx_bpf_reenqueue_local - Re-enqueue tasks on a local DSQ 10122 * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs 10123 * 10124 * Iterate over all of the tasks currently enqueued on the local DSQ of the 10125 * caller's CPU, and re-enqueue them in the BPF scheduler. Returns the number of 10126 * processed tasks. Can only be called from ops.cpu_release(). 10127 */ 10128 __bpf_kfunc u32 scx_bpf_reenqueue_local(const struct bpf_prog_aux *aux) 10129 { 10130 struct scx_sched *sch; 10131 struct rq *rq; 10132 10133 guard(rcu)(); 10134 sch = scx_prog_sched(aux); 10135 if (unlikely(!sch)) 10136 return 0; 10137 10138 rq = cpu_rq(smp_processor_id()); 10139 lockdep_assert_rq_held(rq); 10140 10141 return reenq_local(sch, rq, SCX_REENQ_ANY); 10142 } 10143 10144 __bpf_kfunc_end_defs(); 10145 10146 BTF_KFUNCS_START(scx_kfunc_ids_cpu_release) 10147 BTF_ID_FLAGS(func, scx_bpf_reenqueue_local, KF_IMPLICIT_ARGS) 10148 BTF_KFUNCS_END(scx_kfunc_ids_cpu_release) 10149 10150 static const struct btf_kfunc_id_set scx_kfunc_set_cpu_release = { 10151 .owner = THIS_MODULE, 10152 .set = &scx_kfunc_ids_cpu_release, 10153 .filter = scx_kfunc_context_filter, 10154 }; 10155 10156 __bpf_kfunc_start_defs(); 10157 10158 /** 10159 * scx_bpf_create_dsq - Create a custom DSQ 10160 * @dsq_id: DSQ to create 10161 * @node: NUMA node to allocate from 10162 * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs 10163 * 10164 * Create a custom DSQ identified by @dsq_id. Can be called from any sleepable 10165 * scx callback, and any BPF_PROG_TYPE_SYSCALL prog. 10166 */ 10167 __bpf_kfunc s32 scx_bpf_create_dsq(u64 dsq_id, s32 node, const struct bpf_prog_aux *aux) 10168 { 10169 struct scx_dispatch_q *dsq; 10170 struct scx_sched *sch; 10171 s32 ret; 10172 10173 if (unlikely(node >= (int)nr_node_ids || 10174 (node < 0 && node != NUMA_NO_NODE))) 10175 return -EINVAL; 10176 10177 if (unlikely(dsq_id & SCX_DSQ_FLAG_BUILTIN)) 10178 return -EINVAL; 10179 10180 dsq = kmalloc_node(sizeof(*dsq), GFP_KERNEL, node); 10181 if (!dsq) 10182 return -ENOMEM; 10183 10184 /* 10185 * scx_init_dsq() must be called in GFP_KERNEL context. Init it with 10186 * NULL @sch and update afterwards. 10187 */ 10188 ret = scx_init_dsq(dsq, dsq_id, NULL); 10189 if (ret) { 10190 kfree(dsq); 10191 return ret; 10192 } 10193 10194 rcu_read_lock(); 10195 10196 sch = scx_prog_sched(aux); 10197 if (sch) { 10198 dsq->sched = sch; 10199 ret = rhashtable_lookup_insert_fast(&sch->dsq_hash, &dsq->hash_node, 10200 dsq_hash_params); 10201 } else { 10202 ret = -ENODEV; 10203 } 10204 10205 rcu_read_unlock(); 10206 if (ret) { 10207 exit_dsq(dsq); 10208 kfree(dsq); 10209 } 10210 return ret; 10211 } 10212 10213 __bpf_kfunc_end_defs(); 10214 10215 BTF_KFUNCS_START(scx_kfunc_ids_unlocked) 10216 BTF_ID_FLAGS(func, scx_bpf_create_dsq, KF_IMPLICIT_ARGS | KF_SLEEPABLE) 10217 /* also in scx_kfunc_ids_dispatch: also callable from ops.dispatch() */ 10218 BTF_ID_FLAGS(func, scx_bpf_dsq_move_set_slice, KF_RCU) 10219 BTF_ID_FLAGS(func, scx_bpf_dsq_move_set_vtime, KF_RCU) 10220 BTF_ID_FLAGS(func, scx_bpf_dsq_move, KF_RCU) 10221 BTF_ID_FLAGS(func, scx_bpf_dsq_move_vtime, KF_RCU) 10222 BTF_ID_FLAGS(func, scx_bpf_dsq_reenq_task, KF_RCU) 10223 /* also in scx_kfunc_ids_select_cpu: also callable from ops.select_cpu()/ops.enqueue() */ 10224 BTF_ID_FLAGS(func, __scx_bpf_select_cpu_and, KF_IMPLICIT_ARGS | KF_RCU) 10225 BTF_ID_FLAGS(func, scx_bpf_select_cpu_and, KF_RCU) 10226 BTF_ID_FLAGS(func, scx_bpf_select_cpu_dfl, KF_IMPLICIT_ARGS | KF_RCU) 10227 BTF_KFUNCS_END(scx_kfunc_ids_unlocked) 10228 10229 static const struct btf_kfunc_id_set scx_kfunc_set_unlocked = { 10230 .owner = THIS_MODULE, 10231 .set = &scx_kfunc_ids_unlocked, 10232 .filter = scx_kfunc_context_filter, 10233 }; 10234 10235 __bpf_kfunc_start_defs(); 10236 10237 /** 10238 * scx_bpf_task_set_slice - Set task's time slice 10239 * @p: task of interest 10240 * @slice: time slice to set in nsecs 10241 * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs 10242 * 10243 * Set @p's time slice. @p must be on the calling scheduler. The value is 10244 * applied whether or not the caller holds @p's rq lock - see the slice write 10245 * rules above for the ownership model. 10246 * 10247 * Raising the slice is honored only while the scheduler holds %SCX_CAP_BASE on 10248 * @p's cpu, otherwise it is counted in %SCX_EV_SLICE_DENIED. Shortening is 10249 * always allowed. On the stashed path the slice is packed into an atomic64_t 10250 * with the scheduler id and a flag bit, so a slice too large to fit is clamped 10251 * and counted in %SCX_EV_SLICE_CLAMPED. %SCX_SLICE_INF is preserved. 10252 * 10253 * Return %true on success, %false if @p is not on the calling scheduler. 10254 */ 10255 __bpf_kfunc bool scx_bpf_task_set_slice(struct task_struct *p, u64 slice, 10256 const struct bpf_prog_aux *aux) 10257 { 10258 struct scx_sched *sch; 10259 struct rq *locked_rq; 10260 10261 guard(rcu)(); 10262 sch = scx_prog_sched(aux); 10263 if (unlikely(!sch || !scx_task_on_sched(sch, p))) 10264 return false; 10265 10266 /* 10267 * Directly write only when we hold the lock of the rq @p is queued on or 10268 * provides the current scheduling context for. Under proxy execution, 10269 * rq->donor owns and consumes the slice while rq->curr executes on its 10270 * behalf. See the slice write rules above. 10271 * 10272 * While @p is queued on a user DSQ or in the BPF scheduler, 10273 * synchronization is the scheduler's responsibility. This write can 10274 * race a concurrent dispatch's commit, see apply_slice_vtime(). 10275 * 10276 * Making this kfunc always go through the oob stash would leave the 10277 * commit as the only direct writer and close the race, but that would 10278 * require two more oob application points - the dispatch keep-prev test 10279 * and the tick-time expiry check. 10280 */ 10281 locked_rq = scx_locked_rq(); 10282 if (!locked_rq || 10283 (READ_ONCE(p->scx.runnable_cpu) != cpu_of(locked_rq) && 10284 !task_current_donor(locked_rq, p))) { 10285 set_task_slice_oob(sch, p, slice); 10286 return true; 10287 } 10288 10289 /* under the rq lock: apply now, extensions gated on baseline access */ 10290 if (slice > p->scx.slice && 10291 unlikely(scx_missing_caps(sch, cpu_of(locked_rq), SCX_CAP_BASE))) { 10292 __scx_add_event(sch, SCX_EV_SLICE_DENIED, 1); 10293 return true; 10294 } 10295 10296 if (unlikely(!scx_set_task_slice(p, slice))) 10297 __scx_add_event(sch, SCX_EV_SLICE_DENIED, 1); 10298 10299 return true; 10300 } 10301 10302 /** 10303 * scx_bpf_task_set_dsq_vtime - Set task's virtual time for DSQ ordering 10304 * @p: task of interest 10305 * @vtime: virtual time to set 10306 * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs 10307 * 10308 * Set @p's virtual time to @vtime. Returns %true on success, %false if the 10309 * calling scheduler doesn't have authority over @p. 10310 */ 10311 __bpf_kfunc bool scx_bpf_task_set_dsq_vtime(struct task_struct *p, u64 vtime, 10312 const struct bpf_prog_aux *aux) 10313 { 10314 struct scx_sched *sch; 10315 10316 guard(rcu)(); 10317 sch = scx_prog_sched(aux); 10318 if (unlikely(!sch || !scx_task_on_sched(sch, p))) 10319 return false; 10320 10321 p->scx.dsq_vtime = vtime; 10322 return true; 10323 } 10324 10325 /** 10326 * scx_bpf_task_set_lazy_resched - Set task's tick reschedule mode 10327 * @p: task of interest 10328 * @lazy: whether slice expiry should request lazy rescheduling 10329 * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs 10330 * 10331 * Choose whether depletion of @p's slice at the scheduler tick requests lazy or 10332 * immediate rescheduling. This is a persistent per-task policy and does not 10333 * itself clear @p's slice or request rescheduling, unlike the 10334 * %SCX_ENQ_PREEMPT_LAZY and %SCX_KICK_PREEMPT_LAZY one-shot operations. 10335 * 10336 * With lazy rescheduling enabled, a task interrupted in user space still 10337 * reschedules before returning to user space. A task interrupted in the kernel 10338 * may continue until its next return to user space or the next scheduler tick, 10339 * which promotes the request. If lazy preemption is disabled at runtime, the 10340 * request behaves like an immediate reschedule. 10341 * 10342 * @p must be on the calling scheduler. 10343 * 10344 * Return %true on success, %false if @p is not on the calling scheduler. 10345 */ 10346 __bpf_kfunc bool scx_bpf_task_set_lazy_resched(struct task_struct *p, bool lazy, 10347 const struct bpf_prog_aux *aux) 10348 { 10349 struct scx_sched *sch; 10350 10351 /* 10352 * clang's register locations for @lazy make pahole 1.32 drop this kfunc 10353 * from BTF. Keep @lazy in memory so its location names no register. 10354 */ 10355 barrier_data(&lazy); 10356 guard(rcu)(); 10357 sch = scx_prog_sched(aux); 10358 if (unlikely(!sch || !scx_task_on_sched(sch, p))) 10359 return false; 10360 10361 WRITE_ONCE(p->scx.lazy_resched, lazy); 10362 return true; 10363 } 10364 10365 void scx_kick_cpu(struct scx_sched *sch, s32 cpu, u64 flags) 10366 { 10367 struct scx_sched_pcpu *pcpu; 10368 struct rq *this_rq; 10369 unsigned long irq_flags; 10370 10371 if (!scx_kf_allowed_ctx(sch)) 10372 return; 10373 if (unlikely(flags & ~SCX_KICK_ALL_FLAGS)) { 10374 scx_error(sch, "invalid kick flags 0x%llx", flags); 10375 return; 10376 } 10377 10378 local_irq_save(irq_flags); 10379 10380 this_rq = this_rq(); 10381 pcpu = this_cpu_ptr(sch->pcpu); 10382 10383 /* 10384 * While bypassing for PM ops, IRQ handling may not be online which can 10385 * lead to irq_work_queue() malfunction such as infinite busy wait for 10386 * IRQ status update. Suppress kicking. 10387 */ 10388 if (scx_bypassing(sch, cpu_of(this_rq))) 10389 goto out; 10390 10391 /* 10392 * Actual kicking is bounced to kick_cpus_irq_workfn() to avoid nesting 10393 * rq locks. We can probably be smarter and avoid bouncing if called 10394 * from ops which don't hold a rq lock. 10395 * 10396 * The kick masks are owned by @sch->pcpu, so that a preempt kick can be 10397 * attributed to @sch. 10398 */ 10399 if (flags & SCX_KICK_IDLE) { 10400 struct rq *target_rq = cpu_rq(cpu); 10401 10402 if (unlikely(flags & (SCX_KICK_PREEMPT | SCX_KICK_PREEMPT_LAZY | 10403 SCX_KICK_WAIT))) 10404 scx_error(sch, "PREEMPT/WAIT cannot be used with SCX_KICK_IDLE"); 10405 10406 if (raw_spin_rq_trylock(target_rq)) { 10407 if (can_skip_idle_kick(target_rq)) { 10408 scx_rq_lock_drop(target_rq); 10409 raw_spin_rq_unlock(target_rq); 10410 goto out; 10411 } 10412 scx_rq_lock_drop(target_rq); 10413 raw_spin_rq_unlock(target_rq); 10414 } 10415 cpumask_set_cpu(cpu, pcpu->cpus_to_kick_if_idle); 10416 } else { 10417 /* 10418 * Accumulate requests and resolve their precedence at delivery. 10419 */ 10420 if (flags & SCX_KICK_PREEMPT) 10421 cpumask_set_cpu(cpu, pcpu->cpus_to_preempt); 10422 if (flags & SCX_KICK_PREEMPT_LAZY) 10423 cpumask_set_cpu(cpu, pcpu->cpus_to_preempt_lazy); 10424 if (flags & SCX_KICK_WAIT) 10425 cpumask_set_cpu(cpu, pcpu->cpus_to_wait); 10426 if (!(flags & SCX_KICK_PREEMPT_LAZY)) 10427 cpumask_set_cpu(cpu, pcpu->cpus_to_kick); 10428 } 10429 10430 if (list_empty(&pcpu->to_kick_node)) 10431 list_add_tail(&pcpu->to_kick_node, &this_rq->scx.sched_pcpus_to_kick); 10432 irq_work_queue(&this_rq->scx.kick_cpus_irq_work); 10433 out: 10434 local_irq_restore(irq_flags); 10435 } 10436 10437 /** 10438 * scx_bpf_kick_cpu - Trigger reschedule on a CPU 10439 * @cpu: cpu to kick 10440 * @flags: %SCX_KICK_* flags 10441 * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs 10442 * 10443 * Kick @cpu into rescheduling. This can be used to wake up an idle CPU or 10444 * trigger rescheduling on a busy CPU. This can be called from any online 10445 * scx_ops operation and the actual kicking is performed asynchronously through 10446 * an irq work. 10447 */ 10448 __bpf_kfunc void scx_bpf_kick_cpu(s32 cpu, u64 flags, const struct bpf_prog_aux *aux) 10449 { 10450 struct scx_sched *sch; 10451 10452 guard(rcu)(); 10453 sch = scx_prog_sched(aux); 10454 if (likely(sch) && scx_cpu_valid(sch, cpu, NULL)) 10455 scx_kick_cpu(sch, cpu, flags); 10456 } 10457 10458 /** 10459 * scx_bpf_kick_cid - Trigger reschedule on the CPU mapped to @cid 10460 * @cid: cid to kick 10461 * @flags: %SCX_KICK_* flags 10462 * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs 10463 * 10464 * cid-addressed equivalent of scx_bpf_kick_cpu(). An invalid @cid aborts the 10465 * scheduler via scx_cid_to_cpu(). Caps are enforced on the delivery path: a 10466 * kick is dropped if the caller lacks baseline access on @cid, and a 10467 * %SCX_KICK_PREEMPT or %SCX_KICK_PREEMPT_LAZY request degrades to a plain 10468 * reschedule if the caller lacks %SCX_CAP_PREEMPT for a task outside its 10469 * subtree. 10470 */ 10471 __bpf_kfunc void scx_bpf_kick_cid(s32 cid, u64 flags, const struct bpf_prog_aux *aux) 10472 { 10473 struct scx_sched *sch; 10474 s32 cpu; 10475 10476 guard(rcu)(); 10477 sch = scx_prog_sched(aux); 10478 if (unlikely(!sch)) 10479 return; 10480 cpu = scx_cid_to_cpu(sch, cid); 10481 if (cpu < 0) 10482 return; 10483 scx_kick_cpu(sch, cpu, flags); 10484 } 10485 10486 /** 10487 * scx_bpf_dsq_nr_queued - Return the number of queued tasks 10488 * @dsq_id: id of the DSQ 10489 * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs 10490 * 10491 * Return the number of tasks in the DSQ matching @dsq_id. If not found, 10492 * -%ENOENT is returned. 10493 * 10494 * %SCX_DSQ_LOCAL resolves to the local DSQ of the rq the current scheduler 10495 * operation is locked to - e.g. the rq being dispatched for in ops.dispatch() - 10496 * or the calling CPU's when no rq is locked. 10497 */ 10498 __bpf_kfunc s32 scx_bpf_dsq_nr_queued(u64 dsq_id, const struct bpf_prog_aux *aux) 10499 { 10500 struct scx_sched *sch; 10501 struct scx_dispatch_q *dsq; 10502 s32 ret; 10503 10504 preempt_disable(); 10505 10506 sch = scx_prog_sched(aux); 10507 if (unlikely(!sch)) { 10508 ret = -ENODEV; 10509 goto out; 10510 } 10511 10512 if (dsq_id == SCX_DSQ_LOCAL) { 10513 ret = READ_ONCE((scx_locked_rq() ?: this_rq())->scx.local_dsq.nr); 10514 goto out; 10515 } else if ((dsq_id & SCX_DSQ_LOCAL_ON) == SCX_DSQ_LOCAL_ON) { 10516 s32 cpu = scx_cpu_ret(sch, dsq_id & SCX_DSQ_LOCAL_CPU_MASK); 10517 10518 if (scx_cpu_valid(sch, cpu, NULL)) { 10519 ret = READ_ONCE(cpu_rq(cpu)->scx.local_dsq.nr); 10520 goto out; 10521 } 10522 } else { 10523 dsq = find_user_dsq(sch, dsq_id); 10524 if (dsq) { 10525 ret = READ_ONCE(dsq->nr); 10526 goto out; 10527 } 10528 } 10529 ret = -ENOENT; 10530 out: 10531 preempt_enable(); 10532 return ret; 10533 } 10534 10535 /** 10536 * scx_bpf_destroy_dsq - Destroy a custom DSQ 10537 * @dsq_id: DSQ to destroy 10538 * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs 10539 * 10540 * Destroy the custom DSQ identified by @dsq_id. Only DSQs created with 10541 * scx_bpf_create_dsq() can be destroyed. The caller must ensure that the DSQ is 10542 * empty and no further tasks are dispatched to it. Ignored if called on a DSQ 10543 * which doesn't exist. Can be called from any online scx_ops operations. 10544 */ 10545 __bpf_kfunc void scx_bpf_destroy_dsq(u64 dsq_id, const struct bpf_prog_aux *aux) 10546 { 10547 struct scx_sched *sch; 10548 10549 guard(rcu)(); 10550 sch = scx_prog_sched(aux); 10551 if (unlikely(!sch)) 10552 return; 10553 10554 if (!scx_kf_allowed_ctx(sch)) 10555 return; 10556 10557 destroy_dsq(sch, dsq_id); 10558 } 10559 10560 /** 10561 * bpf_iter_scx_dsq_new - Create a DSQ iterator 10562 * @it: iterator to initialize 10563 * @dsq_id: DSQ to iterate 10564 * @flags: %SCX_DSQ_ITER_* 10565 * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs 10566 * 10567 * Initialize BPF iterator @it which can be used with bpf_for_each() to walk 10568 * tasks in the DSQ specified by @dsq_id. Iteration using @it only includes 10569 * tasks which are already queued when this function is invoked. 10570 */ 10571 __bpf_kfunc int bpf_iter_scx_dsq_new(struct bpf_iter_scx_dsq *it, u64 dsq_id, 10572 u64 flags, const struct bpf_prog_aux *aux) 10573 { 10574 struct bpf_iter_scx_dsq_kern *kit = (void *)it; 10575 struct scx_sched *sch; 10576 10577 BUILD_BUG_ON(sizeof(struct bpf_iter_scx_dsq_kern) > 10578 sizeof(struct bpf_iter_scx_dsq)); 10579 BUILD_BUG_ON(__alignof__(struct bpf_iter_scx_dsq_kern) != 10580 __alignof__(struct bpf_iter_scx_dsq)); 10581 BUILD_BUG_ON(__SCX_DSQ_ITER_ALL_FLAGS & 10582 ((1U << __SCX_DSQ_LNODE_PRIV_SHIFT) - 1)); 10583 10584 /* 10585 * next() and destroy() will be called regardless of the return value. 10586 * Always clear $kit->dsq. 10587 */ 10588 kit->dsq = NULL; 10589 10590 sch = scx_prog_sched(aux); 10591 if (unlikely(!sch)) 10592 return -ENODEV; 10593 10594 if (!scx_kf_allowed_ctx(sch)) 10595 return -EDEADLK; 10596 10597 if (flags & ~__SCX_DSQ_ITER_USER_FLAGS) 10598 return -EINVAL; 10599 10600 kit->dsq = find_user_dsq(sch, dsq_id); 10601 if (!kit->dsq) 10602 return -ENOENT; 10603 10604 kit->cursor = INIT_DSQ_LIST_CURSOR(kit->cursor, kit->dsq, flags); 10605 10606 return 0; 10607 } 10608 10609 /** 10610 * bpf_iter_scx_dsq_next - Progress a DSQ iterator 10611 * @it: iterator to progress 10612 * 10613 * Return the next task. See bpf_iter_scx_dsq_new(). 10614 */ 10615 __bpf_kfunc struct task_struct *bpf_iter_scx_dsq_next(struct bpf_iter_scx_dsq *it) 10616 { 10617 struct bpf_iter_scx_dsq_kern *kit = (void *)it; 10618 10619 if (!kit->dsq) 10620 return NULL; 10621 10622 guard(raw_spinlock_irqsave)(&kit->dsq->lock); 10623 10624 return nldsq_cursor_next_task(&kit->cursor, kit->dsq); 10625 } 10626 10627 /** 10628 * bpf_iter_scx_dsq_destroy - Destroy a DSQ iterator 10629 * @it: iterator to destroy 10630 * 10631 * Undo bpf_iter_scx_dsq_new(). If the iteration marked tasks with 10632 * scx_bpf_dsq_reenq_task(), schedule their re-enqueue. 10633 */ 10634 __bpf_kfunc void bpf_iter_scx_dsq_destroy(struct bpf_iter_scx_dsq *it) 10635 { 10636 struct bpf_iter_scx_dsq_kern *kit = (void *)it; 10637 10638 if (!kit->dsq) 10639 return; 10640 10641 if (!list_empty(&kit->cursor.node)) { 10642 unsigned long flags; 10643 10644 raw_spin_lock_irqsave(&kit->dsq->lock, flags); 10645 list_del_init(&kit->cursor.node); 10646 raw_spin_unlock_irqrestore(&kit->dsq->lock, flags); 10647 } 10648 10649 if (kit->cursor.flags & __SCX_DSQ_ITER_HAS_REENQ) { 10650 guard(preempt)(); 10651 schedule_dsq_reenq(kit->dsq->sched, kit->dsq, SCX_REENQ_MARKED, 10652 scx_locked_rq()); 10653 } 10654 10655 kit->dsq = NULL; 10656 } 10657 10658 /** 10659 * scx_bpf_dsq_peek - Lockless peek at the first element. 10660 * @dsq_id: DSQ to examine. 10661 * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs 10662 * 10663 * Read the first element in the DSQ. This is semantically equivalent to using 10664 * the DSQ iterator, but is lockfree. Of course, like any lockless operation, 10665 * this provides only a point-in-time snapshot, and the contents may change 10666 * by the time any subsequent locking operation reads the queue. 10667 * 10668 * Returns the pointer, or NULL indicates an empty queue OR internal error. 10669 */ 10670 __bpf_kfunc struct task_struct *scx_bpf_dsq_peek(u64 dsq_id, 10671 const struct bpf_prog_aux *aux) 10672 { 10673 struct scx_sched *sch; 10674 struct scx_dispatch_q *dsq; 10675 10676 sch = scx_prog_sched(aux); 10677 if (unlikely(!sch)) 10678 return NULL; 10679 10680 if (unlikely(dsq_id & SCX_DSQ_FLAG_BUILTIN)) { 10681 scx_error(sch, "peek disallowed on builtin DSQ 0x%llx", dsq_id); 10682 return NULL; 10683 } 10684 10685 dsq = find_user_dsq(sch, dsq_id); 10686 if (unlikely(!dsq)) { 10687 scx_error(sch, "peek on non-existent DSQ 0x%llx", dsq_id); 10688 return NULL; 10689 } 10690 10691 return rcu_dereference(dsq->first_task); 10692 } 10693 10694 /** 10695 * scx_bpf_dsq_reenq - Re-enqueue tasks on a DSQ 10696 * @dsq_id: DSQ to re-enqueue 10697 * @reenq_flags: %SCX_RENQ_* 10698 * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs 10699 * 10700 * Iterate over all of the tasks currently enqueued on the DSQ identified by 10701 * @dsq_id, and re-enqueue them in the BPF scheduler. The following DSQs are 10702 * supported: 10703 * 10704 * - Local DSQs (%SCX_DSQ_LOCAL or %SCX_DSQ_LOCAL_ON | $cpu) 10705 * - User DSQs 10706 * 10707 * Re-enqueues are performed asynchronously. Can be called from anywhere. A 10708 * re-enqueue of an inactive cpu's local DSQ is ignored. 10709 * 10710 * %SCX_DSQ_LOCAL resolves to the local DSQ of the rq the current scheduler 10711 * operation is locked to - e.g. the rq being dispatched for in ops.dispatch() - 10712 * or the calling CPU's when no rq is locked. 10713 */ 10714 __bpf_kfunc void scx_bpf_dsq_reenq(u64 dsq_id, u64 reenq_flags, 10715 const struct bpf_prog_aux *aux) 10716 { 10717 struct rq *locked_rq = scx_locked_rq(); 10718 struct scx_sched *sch; 10719 struct scx_dispatch_q *dsq; 10720 10721 guard(preempt)(); 10722 10723 sch = scx_prog_sched(aux); 10724 if (unlikely(!sch)) 10725 return; 10726 10727 if (unlikely(reenq_flags & ~__SCX_REENQ_USER_MASK)) { 10728 scx_error(sch, "invalid SCX_REENQ flags 0x%llx", reenq_flags); 10729 return; 10730 } 10731 10732 if (!scx_kf_allowed_ctx(sch)) 10733 return; 10734 10735 /* not specifying any filter bits is the same as %SCX_REENQ_ANY */ 10736 if (!(reenq_flags & __SCX_REENQ_FILTER_MASK)) 10737 reenq_flags |= SCX_REENQ_ANY; 10738 10739 dsq = find_dsq_for_dispatch(sch, locked_rq ?: this_rq(), dsq_id, smp_processor_id()); 10740 schedule_dsq_reenq(sch, dsq, reenq_flags, locked_rq); 10741 } 10742 10743 /** 10744 * scx_bpf_dsq_reenq_task - Re-enqueue a task from a DSQ iteration 10745 * @it__iter: DSQ iterator in progress 10746 * @p: task to re-enqueue 10747 * 10748 * Mark @p, which is on the DSQ iterated by @it__iter and was queued before the 10749 * iteration started, for re-enqueue. When the iteration ends, the DSQ's marked 10750 * tasks go through ops.enqueue() with %SCX_ENQ_REENQ in DSQ order and the other 10751 * tasks on the DSQ keep their positions. A marked task that leaves the DSQ in 10752 * the meantime is not re-enqueued. The mark belongs to @p, so a re-enqueue 10753 * scheduled by another iteration of the DSQ may re-enqueue @p before this 10754 * iteration ends. @p must be on the DSQ's scheduler. 10755 * 10756 * Re-enqueues are performed asynchronously. Can be called from ops.dispatch() 10757 * or any BPF context which doesn't hold a rq lock (e.g. BPF timers or SYSCALL 10758 * programs). 10759 * 10760 * Return %true if @p was marked, %false if @p left the DSQ or was queued after 10761 * the iteration started, @p is on another scheduler, or the iterator holds no 10762 * DSQ. 10763 */ 10764 __bpf_kfunc bool scx_bpf_dsq_reenq_task(struct bpf_iter_scx_dsq *it__iter, 10765 struct task_struct *p) 10766 { 10767 struct bpf_iter_scx_dsq_kern *kit = (void *)it__iter; 10768 struct scx_dispatch_q *dsq = kit->dsq; 10769 struct rq *src_rq, *entry_rq; 10770 unsigned long flags; 10771 bool marked = false; 10772 10773 /* NULL after a failed bpf_iter_scx_dsq_new(), see scx_dsq_move() */ 10774 if (unlikely(!dsq)) 10775 return false; 10776 10777 /* the cursor check needs @p's rq locked */ 10778 src_rq = task_rq(p); 10779 entry_rq = kf_switch_rq_lock(src_rq, &flags); 10780 10781 scoped_guard (raw_spinlock, &dsq->lock) { 10782 if (nldsq_cursor_lost_task(&kit->cursor, src_rq, dsq, p)) 10783 break; 10784 10785 if (unlikely(!scx_task_on_sched(dsq->sched, p))) { 10786 scx_error(dsq->sched, "scx_bpf_dsq_reenq_task() on %s[%d] but the task belongs to a different scheduler", 10787 p->comm, p->pid); 10788 break; 10789 } 10790 10791 p->scx.dsq_flags |= SCX_TASK_DSQ_REENQ; 10792 /* the walk is scheduled once, by bpf_iter_scx_dsq_destroy() */ 10793 kit->cursor.flags |= __SCX_DSQ_ITER_HAS_REENQ; 10794 marked = true; 10795 } 10796 10797 kf_restore_rq_lock(src_rq, entry_rq, flags); 10798 return marked; 10799 } 10800 10801 /** 10802 * scx_bpf_reenqueue_local___v2 - Re-enqueue tasks on a local DSQ 10803 * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs 10804 * 10805 * Iterate over all of the tasks currently enqueued on the local DSQ of the 10806 * caller's CPU, and re-enqueue them in the BPF scheduler. Can be called from 10807 * anywhere. 10808 * 10809 * This is now a special case of scx_bpf_dsq_reenq() and may be removed in the 10810 * future. 10811 */ 10812 __bpf_kfunc void scx_bpf_reenqueue_local___v2(const struct bpf_prog_aux *aux) 10813 { 10814 scx_bpf_dsq_reenq(SCX_DSQ_LOCAL, 0, aux); 10815 } 10816 10817 __bpf_kfunc_end_defs(); 10818 10819 __printf(5, 0) 10820 static s32 __bstr_format(struct scx_sched *sch, u64 *data_buf, char *line_buf, 10821 size_t line_size, char *fmt, unsigned long long *data, 10822 u32 data__sz) 10823 { 10824 struct bpf_bprintf_data bprintf_data = { .get_bin_args = true }; 10825 s32 ret; 10826 10827 if (data__sz % 8 || data__sz > MAX_BPRINTF_VARARGS * 8 || 10828 (data__sz && !data)) { 10829 scx_error(sch, "invalid data=%p and data__sz=%u", (void *)data, data__sz); 10830 return -EINVAL; 10831 } 10832 10833 ret = copy_from_kernel_nofault(data_buf, data, data__sz); 10834 if (ret < 0) { 10835 scx_error(sch, "failed to read data fields (%d)", ret); 10836 return ret; 10837 } 10838 10839 ret = bpf_bprintf_prepare(fmt, UINT_MAX, data_buf, data__sz / 8, 10840 &bprintf_data); 10841 if (ret < 0) { 10842 scx_error(sch, "format preparation failed (%d)", ret); 10843 return ret; 10844 } 10845 10846 ret = bstr_printf(line_buf, line_size, fmt, 10847 bprintf_data.bin_args); 10848 bpf_bprintf_cleanup(&bprintf_data); 10849 if (ret < 0) { 10850 scx_error(sch, "(\"%s\", %p, %u) failed to format", fmt, data, data__sz); 10851 return ret; 10852 } 10853 10854 return ret; 10855 } 10856 10857 /* 10858 * Exit @sch with the reason formatted from a BPF-supplied bstr format. The exit 10859 * is claimed first and the reason is formatted directly into the winner-owned 10860 * exit_info buffer, which allows use from any context including NMI. 10861 * 10862 * @fmt_blame is the sched blamed for formatting failures through the 10863 * scx_error() calls in __bstr_format() and differs from @sch when a parent 10864 * supplies the kill reason for a child. A formatting failure doesn't revert the 10865 * claim - @sch still exits with the claimed kind and a fallback message. 10866 */ 10867 __printf(5, 0) 10868 bool scx_exit_bstr(struct scx_sched *sch, enum scx_exit_kind kind, 10869 s64 exit_code, struct scx_sched *fmt_blame, char *fmt, 10870 unsigned long long *data, u32 data__sz) 10871 { 10872 struct scx_exit_info *ei = sch->exit_info; 10873 u64 data_buf[MAX_BPRINTF_VARARGS]; 10874 s32 ret; 10875 10876 guard(preempt)(); 10877 10878 if (!scx_claim_exit(sch, kind)) 10879 return false; 10880 10881 ret = __bstr_format(fmt_blame, data_buf, ei->msg, SCX_EXIT_MSG_LEN, 10882 fmt, data, data__sz); 10883 if (ret < 0) 10884 scnprintf(ei->msg, SCX_EXIT_MSG_LEN, 10885 "exit message formatting failed (%d)", ret); 10886 10887 scx_finish_exit(sch, kind, exit_code, raw_smp_processor_id()); 10888 return true; 10889 } 10890 10891 __bpf_kfunc_start_defs(); 10892 10893 /** 10894 * scx_bpf_exit_bstr - Gracefully exit the BPF scheduler. 10895 * @exit_code: Exit value to pass to user space via struct scx_exit_info. 10896 * @fmt: error message format string 10897 * @data: format string parameters packaged using ___bpf_fill() macro 10898 * @data__sz: @data len, must end in '__sz' for the verifier 10899 * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs 10900 * 10901 * Indicate that the BPF scheduler wants to exit gracefully, and initiate ops 10902 * disabling. 10903 */ 10904 __printf(2, 0) 10905 __bpf_kfunc void scx_bpf_exit_bstr(s64 exit_code, char *fmt, 10906 unsigned long long *data, u32 data__sz, 10907 const struct bpf_prog_aux *aux) 10908 { 10909 struct scx_sched *sch; 10910 10911 guard(rcu)(); 10912 10913 sch = scx_prog_sched(aux); 10914 if (likely(sch)) 10915 scx_exit_bstr(sch, SCX_EXIT_UNREG_BPF, exit_code, sch, fmt, 10916 data, data__sz); 10917 } 10918 10919 /** 10920 * scx_bpf_error_bstr - Indicate fatal error 10921 * @fmt: error message format string 10922 * @data: format string parameters packaged using ___bpf_fill() macro 10923 * @data__sz: @data len, must end in '__sz' for the verifier 10924 * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs 10925 * 10926 * Indicate that the BPF scheduler encountered a fatal error and initiate ops 10927 * disabling. 10928 */ 10929 __printf(1, 0) 10930 __bpf_kfunc void scx_bpf_error_bstr(char *fmt, unsigned long long *data, 10931 u32 data__sz, const struct bpf_prog_aux *aux) 10932 { 10933 struct scx_sched *sch; 10934 10935 guard(rcu)(); 10936 10937 sch = scx_prog_sched(aux); 10938 if (likely(sch)) 10939 scx_exit_bstr(sch, SCX_EXIT_ERROR_BPF, 0, sch, fmt, data, 10940 data__sz); 10941 } 10942 10943 /** 10944 * scx_bpf_dump_bstr - Generate extra debug dump specific to the BPF scheduler 10945 * @fmt: format string 10946 * @data: format string parameters packaged using ___bpf_fill() macro 10947 * @data__sz: @data len, must end in '__sz' for the verifier 10948 * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs 10949 * 10950 * To be called through scx_bpf_dump() helper from ops.dump(), dump_cpu() and 10951 * dump_task() to generate extra debug dump specific to the BPF scheduler. 10952 * 10953 * The extra dump may be multiple lines. A single line may be split over 10954 * multiple calls. The last line is automatically terminated. 10955 */ 10956 __printf(1, 0) 10957 __bpf_kfunc void scx_bpf_dump_bstr(char *fmt, unsigned long long *data, 10958 u32 data__sz, const struct bpf_prog_aux *aux) 10959 { 10960 struct scx_sched *sch; 10961 struct scx_dump_data *dd = &scx_dump_data; 10962 struct scx_bstr_buf *buf = &dd->buf; 10963 s32 ret; 10964 10965 guard(rcu)(); 10966 10967 sch = scx_prog_sched(aux); 10968 if (unlikely(!sch)) 10969 return; 10970 10971 if (raw_smp_processor_id() != dd->cpu) { 10972 scx_error(sch, "scx_bpf_dump() must only be called from ops.dump() and friends"); 10973 return; 10974 } 10975 10976 /* append the formatted string to the line buf */ 10977 ret = __bstr_format(sch, buf->data, buf->line + dd->cursor, 10978 sizeof(buf->line) - dd->cursor, fmt, data, data__sz); 10979 if (ret < 0) { 10980 scx_dump_line(dd->s, "%s[!] (\"%s\", %p, %u) failed to format (%d)", 10981 dd->prefix, fmt, data, data__sz, ret); 10982 return; 10983 } 10984 10985 dd->cursor += ret; 10986 dd->cursor = min_t(s32, dd->cursor, sizeof(buf->line)); 10987 10988 if (!dd->cursor) 10989 return; 10990 10991 /* 10992 * If the line buf overflowed or ends in a newline, flush it into the 10993 * dump. This is to allow the caller to generate a single line over 10994 * multiple calls. As ops_dump_flush() can also handle multiple lines in 10995 * the line buf, the only case which can lead to an unexpected 10996 * truncation is when the caller keeps generating newlines in the middle 10997 * instead of the end consecutively. Don't do that. 10998 */ 10999 if (dd->cursor >= sizeof(buf->line) || buf->line[dd->cursor - 1] == '\n') 11000 ops_dump_flush(); 11001 } 11002 11003 /** 11004 * scx_bpf_cpuperf_cap - Query the maximum relative capacity of a CPU 11005 * @cpu: CPU of interest 11006 * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs 11007 * 11008 * Return the maximum relative capacity of @cpu in relation to the most 11009 * performant CPU in the system. The return value is in the range [1, 11010 * %SCX_CPUPERF_ONE]. See scx_bpf_cpuperf_cur(). 11011 */ 11012 __bpf_kfunc u32 scx_bpf_cpuperf_cap(s32 cpu, const struct bpf_prog_aux *aux) 11013 { 11014 struct scx_sched *sch; 11015 11016 guard(rcu)(); 11017 11018 sch = scx_prog_sched(aux); 11019 if (likely(sch) && scx_cpu_valid(sch, cpu, NULL)) 11020 return arch_scale_cpu_capacity(cpu); 11021 else 11022 return SCX_CPUPERF_ONE; 11023 } 11024 11025 /** 11026 * scx_bpf_cidperf_cap - Query the maximum relative capacity of the CPU at @cid 11027 * @cid: cid of the CPU to query 11028 * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs 11029 * 11030 * cid-addressed equivalent of scx_bpf_cpuperf_cap(). 11031 */ 11032 __bpf_kfunc u32 scx_bpf_cidperf_cap(s32 cid, const struct bpf_prog_aux *aux) 11033 { 11034 struct scx_sched *sch; 11035 s32 cpu; 11036 11037 guard(rcu)(); 11038 11039 sch = scx_prog_sched(aux); 11040 if (unlikely(!sch)) 11041 return SCX_CPUPERF_ONE; 11042 cpu = scx_cid_to_cpu(sch, cid); 11043 if (cpu < 0) 11044 return SCX_CPUPERF_ONE; 11045 return arch_scale_cpu_capacity(cpu); 11046 } 11047 11048 /** 11049 * scx_bpf_cpuperf_cur - Query the current relative performance of a CPU 11050 * @cpu: CPU of interest 11051 * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs 11052 * 11053 * Return the current relative performance of @cpu in relation to its maximum. 11054 * The return value is in the range [1, %SCX_CPUPERF_ONE]. 11055 * 11056 * The current performance level of a CPU in relation to the maximum performance 11057 * available in the system can be calculated as follows: 11058 * 11059 * scx_bpf_cpuperf_cap() * scx_bpf_cpuperf_cur() / %SCX_CPUPERF_ONE 11060 * 11061 * The result is in the range [1, %SCX_CPUPERF_ONE]. 11062 */ 11063 __bpf_kfunc u32 scx_bpf_cpuperf_cur(s32 cpu, const struct bpf_prog_aux *aux) 11064 { 11065 struct scx_sched *sch; 11066 11067 guard(rcu)(); 11068 11069 sch = scx_prog_sched(aux); 11070 if (likely(sch) && scx_cpu_valid(sch, cpu, NULL)) 11071 return arch_scale_freq_capacity(cpu); 11072 else 11073 return SCX_CPUPERF_ONE; 11074 } 11075 11076 /** 11077 * scx_bpf_cidperf_cur - Query the current performance of the CPU at @cid 11078 * @cid: cid of the CPU to query 11079 * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs 11080 * 11081 * cid-addressed equivalent of scx_bpf_cpuperf_cur(). 11082 */ 11083 __bpf_kfunc u32 scx_bpf_cidperf_cur(s32 cid, const struct bpf_prog_aux *aux) 11084 { 11085 struct scx_sched *sch; 11086 s32 cpu; 11087 11088 guard(rcu)(); 11089 11090 sch = scx_prog_sched(aux); 11091 if (unlikely(!sch)) 11092 return SCX_CPUPERF_ONE; 11093 cpu = scx_cid_to_cpu(sch, cid); 11094 if (cpu < 0) 11095 return SCX_CPUPERF_ONE; 11096 return arch_scale_freq_capacity(cpu); 11097 } 11098 11099 /* validate and apply a cpuperf target, see scx_bpf_cpuperf_set() */ 11100 static s32 scx_cpuperf_set(struct scx_sched *sch, s32 cpu, u32 perf) 11101 { 11102 struct rq *rq, *locked_rq; 11103 struct rq_flags rf; 11104 s32 ret; 11105 11106 if (unlikely(perf > SCX_CPUPERF_ONE)) { 11107 scx_error(sch, "Invalid cpuperf target %u for CPU %d", perf, cpu); 11108 return -EINVAL; 11109 } 11110 11111 if (!scx_cpu_valid(sch, cpu, NULL)) 11112 return -EINVAL; 11113 11114 rq = cpu_rq(cpu); 11115 locked_rq = scx_locked_rq(); 11116 11117 /* 11118 * When called with an rq lock held, restrict the operation to the 11119 * corresponding CPU to prevent ABBA deadlocks. 11120 */ 11121 if (locked_rq && rq != locked_rq) { 11122 scx_error(sch, "Invalid target CPU %d", cpu); 11123 return -EINVAL; 11124 } 11125 11126 /* 11127 * If no rq lock is held, allow to operate on any CPU by acquiring 11128 * the corresponding rq lock. 11129 */ 11130 if (!locked_rq) { 11131 rq_lock_irqsave(rq, &rf); 11132 update_rq_clock(rq); 11133 } 11134 11135 /* 11136 * ecaps updates are folded under the rq lock, making this test 11137 * authoritative: a write can never land after a revoke has taken 11138 * effect on @cpu. 11139 */ 11140 if (likely(!scx_missing_caps(sch, cpu, SCX_CAP_PERF))) { 11141 rq->scx.cpuperf_target = perf; 11142 cpufreq_update_util(rq, 0); 11143 ret = 0; 11144 } else { 11145 __scx_add_event(sch, SCX_EV_SUB_CIDPERF_DENIED, 1); 11146 ret = -EACCES; 11147 } 11148 11149 if (!locked_rq) 11150 rq_unlock_irqrestore(rq, &rf); 11151 11152 return ret; 11153 } 11154 11155 /** 11156 * scx_bpf_cpuperf_set - Set the relative performance target of a CPU 11157 * @cpu: CPU of interest 11158 * @perf: target performance level [0, %SCX_CPUPERF_ONE] 11159 * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs 11160 * 11161 * Set the target performance level of @cpu to @perf. @perf is in linear 11162 * relative scale between 0 and %SCX_CPUPERF_ONE. This determines how the 11163 * schedutil cpufreq governor chooses the target frequency. 11164 * 11165 * The actual performance level chosen, CPU grouping, and the overhead and 11166 * latency of the operations are dependent on the hardware and cpufreq driver in 11167 * use. Consult hardware and cpufreq documentation for more information. The 11168 * current performance level can be monitored using scx_bpf_cpuperf_cur(). 11169 */ 11170 __bpf_kfunc void scx_bpf_cpuperf_set(s32 cpu, u32 perf, const struct bpf_prog_aux *aux) 11171 { 11172 struct scx_sched *sch; 11173 11174 guard(rcu)(); 11175 11176 sch = scx_prog_sched(aux); 11177 if (unlikely(!sch)) 11178 return; 11179 11180 if (!scx_kf_allowed_ctx(sch)) 11181 return; 11182 11183 scx_cpuperf_set(sch, cpu, perf); 11184 } 11185 11186 /** 11187 * scx_bpf_cidperf_set - Set the performance target of the CPU at @cid 11188 * @cid: cid of the CPU to target 11189 * @perf: target performance level [0, %SCX_CPUPERF_ONE] 11190 * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs 11191 * 11192 * cid-addressed equivalent of scx_bpf_cpuperf_set(). A sub-sched needs 11193 * SCX_CAP_PERF on @cid. Returns 0 if the target was applied, -%EACCES if 11194 * the write was denied for missing caps, other -errnos if @cid didn't 11195 * resolve. 11196 */ 11197 __bpf_kfunc s32 scx_bpf_cidperf_set(s32 cid, u32 perf, 11198 const struct bpf_prog_aux *aux) 11199 { 11200 struct scx_sched *sch; 11201 s32 cpu; 11202 11203 guard(rcu)(); 11204 11205 sch = scx_prog_sched(aux); 11206 if (unlikely(!sch)) 11207 return -ENODEV; 11208 11209 if (!scx_kf_allowed_ctx(sch)) 11210 return -EDEADLK; 11211 11212 cpu = scx_cid_to_cpu(sch, cid); 11213 if (cpu < 0) 11214 return cpu; 11215 11216 return scx_cpuperf_set(sch, cpu, perf); 11217 } 11218 11219 /** 11220 * scx_bpf_nr_node_ids - Return the number of possible node IDs 11221 * 11222 * All valid node IDs in the system are smaller than the returned value. 11223 */ 11224 __bpf_kfunc u32 scx_bpf_nr_node_ids(void) 11225 { 11226 return nr_node_ids; 11227 } 11228 11229 /** 11230 * scx_bpf_nr_cpu_ids - Return the number of possible CPU IDs 11231 * 11232 * All valid CPU IDs in the system are smaller than the returned value. 11233 */ 11234 __bpf_kfunc u32 scx_bpf_nr_cpu_ids(void) 11235 { 11236 return nr_cpu_ids; 11237 } 11238 11239 /** 11240 * scx_bpf_nr_cids - Return the size of the cid space 11241 * 11242 * Equals num_possible_cpus(). All valid cids are in [0, return value). 11243 */ 11244 __bpf_kfunc u32 scx_bpf_nr_cids(void) 11245 { 11246 return num_possible_cpus(); 11247 } 11248 11249 /** 11250 * scx_bpf_nr_online_cids - Return current count of online CPUs in cid space 11251 * 11252 * Return num_online_cpus(). The standard model restarts the scheduler on 11253 * hotplug, which lets schedulers treat [0, nr_online_cids) as the online 11254 * range. Schedulers that prefer to handle hotplug without a restart should 11255 * install a custom mapping via scx_bpf_cid_override() and track onlining 11256 * through the ops.cid_online / ops.cid_offline callbacks, starting from the 11257 * mask scx_bpf_online_cmask() returns. 11258 */ 11259 __bpf_kfunc u32 scx_bpf_nr_online_cids(void) 11260 { 11261 return num_online_cpus(); 11262 } 11263 11264 /** 11265 * scx_bpf_online_cmask - Return the online cid mask in the scheduler arena 11266 * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs 11267 * 11268 * Return a kernel-maintained cmask covering [0, scx_bpf_nr_cids()), or NULL if 11269 * the calling program is not associated with a live cid-form scheduler or the 11270 * mask is not allocated yet, as in ops.init_cids(). Treat the mask as read-only 11271 * even though arena memory stays writable by the BPF scheduler. The mask 11272 * follows the SCX hotplug notifications: a cid's bit is updated before 11273 * ops.cid_online/offline() runs for it. The pointer is valid from ops.init() 11274 * through ops.exit(). Root ops.init() runs with hotplug excluded. Other 11275 * contexts can observe concurrent updates. 11276 */ 11277 __bpf_kfunc const void *scx_bpf_online_cmask(const struct bpf_prog_aux *aux) 11278 { 11279 struct scx_sched *sch; 11280 struct scx_cmask *online; 11281 11282 guard(rcu)(); 11283 11284 sch = scx_prog_sched(aux); 11285 if (unlikely(!sch)) 11286 return NULL; 11287 online = sch->online_cmask; 11288 if (unlikely(!online)) 11289 return NULL; 11290 11291 return (void *)scx_kaddr_to_arena(sch, online); 11292 } 11293 11294 /** 11295 * scx_bpf_this_cid - Return the cid of the CPU this program is running on 11296 * 11297 * cid-addressed equivalent of bpf_get_smp_processor_id() for scx programs. 11298 * The current cpu is trivially valid, so this is just a table lookup. Return 11299 * -EINVAL if called before any scheduler has ever published its cid tables. 11300 */ 11301 __bpf_kfunc s32 scx_bpf_this_cid(void) 11302 { 11303 s16 *tbl; 11304 11305 guard(rcu)(); 11306 11307 tbl = rcu_dereference(scx_cpu_to_cid_tbl); 11308 if (!tbl) 11309 return -EINVAL; 11310 return tbl[raw_smp_processor_id()]; 11311 } 11312 11313 /** 11314 * scx_bpf_get_possible_cpumask - Get a referenced kptr to cpu_possible_mask 11315 */ 11316 __bpf_kfunc const struct cpumask *scx_bpf_get_possible_cpumask(void) 11317 { 11318 return cpu_possible_mask; 11319 } 11320 11321 /** 11322 * scx_bpf_get_online_cpumask - Get a referenced kptr to cpu_online_mask 11323 */ 11324 __bpf_kfunc const struct cpumask *scx_bpf_get_online_cpumask(void) 11325 { 11326 return cpu_online_mask; 11327 } 11328 11329 /** 11330 * scx_bpf_put_cpumask - Release a possible/online cpumask 11331 * @cpumask: cpumask to release 11332 */ 11333 __bpf_kfunc void scx_bpf_put_cpumask(const struct cpumask *cpumask) 11334 { 11335 /* 11336 * Empty function body because we aren't actually acquiring or releasing 11337 * a reference to a global cpumask, which is read-only in the caller and 11338 * is never released. The acquire / release semantics here are just used 11339 * to make the cpumask is a trusted pointer in the caller. 11340 */ 11341 } 11342 11343 /** 11344 * scx_bpf_task_running - Is task the current scheduling context? 11345 * @p: task of interest 11346 * 11347 * Under proxy execution, this reports the donor rather than the task whose 11348 * code is physically executing. The physical execution context is intentionally 11349 * not exposed to the BPF scheduler, which continues to observe the donor as the 11350 * running scheduling context. 11351 */ 11352 __bpf_kfunc bool scx_bpf_task_running(const struct task_struct *p) 11353 { 11354 return rcu_access_pointer(task_rq(p)->donor) == p; 11355 } 11356 11357 /** 11358 * scx_bpf_task_cpu - CPU a task is currently associated with 11359 * @p: task of interest 11360 */ 11361 __bpf_kfunc s32 scx_bpf_task_cpu(const struct task_struct *p) 11362 { 11363 return task_cpu(p); 11364 } 11365 11366 /** 11367 * scx_bpf_task_cid - cid a task is currently associated with 11368 * @p: task of interest 11369 * 11370 * cid-addressed equivalent of scx_bpf_task_cpu(). task_cpu(p) is always a 11371 * valid cpu, so this is just a table lookup. Return -EINVAL if called before 11372 * any scheduler has ever published its cid tables. 11373 */ 11374 __bpf_kfunc s32 scx_bpf_task_cid(const struct task_struct *p) 11375 { 11376 s16 *tbl; 11377 11378 /* KF_RCU covers only @p - a sleepable program holds no RCU lock */ 11379 guard(rcu)(); 11380 11381 tbl = rcu_dereference(scx_cpu_to_cid_tbl); 11382 if (!tbl) 11383 return -EINVAL; 11384 return tbl[task_cpu(p)]; 11385 } 11386 11387 /** 11388 * scx_bpf_locked_rq - Return the rq currently locked by SCX 11389 * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs 11390 * 11391 * Returns the rq if a rq lock is currently held by SCX. 11392 * Otherwise emits an error and returns NULL. 11393 */ 11394 __bpf_kfunc struct rq *scx_bpf_locked_rq(const struct bpf_prog_aux *aux) 11395 { 11396 struct scx_sched *sch; 11397 struct rq *rq; 11398 11399 guard(preempt)(); 11400 11401 sch = scx_prog_sched(aux); 11402 if (unlikely(!sch)) 11403 return NULL; 11404 11405 rq = scx_locked_rq(); 11406 if (!rq) { 11407 scx_error(sch, "accessing rq without holding rq lock"); 11408 return NULL; 11409 } 11410 11411 return rq; 11412 } 11413 11414 /** 11415 * scx_bpf_cpu_curr - Return remote CPU's current scheduling context 11416 * @cpu: CPU of interest 11417 * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs 11418 * 11419 * Under proxy execution, this returns the donor, which supplies the scheduling 11420 * policy and runtime budget, rather than the task whose code is physically 11421 * executing. The physical execution context is intentionally not exposed to 11422 * the BPF scheduler. 11423 * 11424 * Callers must hold RCU read lock (KF_RCU). 11425 */ 11426 __bpf_kfunc struct task_struct *scx_bpf_cpu_curr(s32 cpu, const struct bpf_prog_aux *aux) 11427 { 11428 struct scx_sched *sch; 11429 11430 guard(rcu)(); 11431 11432 sch = scx_prog_sched(aux); 11433 if (unlikely(!sch)) 11434 return NULL; 11435 11436 if (!scx_cpu_valid(sch, cpu, NULL)) 11437 return NULL; 11438 11439 return rcu_dereference(cpu_rq(cpu)->donor); 11440 } 11441 11442 /** 11443 * scx_bpf_cid_curr - Return the curr task on the CPU at @cid 11444 * @cid: cid of interest 11445 * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs 11446 * 11447 * cid-addressed equivalent of scx_bpf_cpu_curr(). Callers must hold RCU 11448 * read lock (KF_RCU). 11449 */ 11450 __bpf_kfunc struct task_struct *scx_bpf_cid_curr(s32 cid, const struct bpf_prog_aux *aux) 11451 { 11452 struct scx_sched *sch; 11453 s32 cpu; 11454 11455 guard(rcu)(); 11456 11457 sch = scx_prog_sched(aux); 11458 if (unlikely(!sch)) 11459 return NULL; 11460 cpu = scx_cid_to_cpu(sch, cid); 11461 if (cpu < 0) 11462 return NULL; 11463 return rcu_dereference(cpu_rq(cpu)->donor); 11464 } 11465 11466 /** 11467 * scx_bpf_tid_to_task - Look up a task by its scx tid 11468 * @tid: task ID previously read from p->scx.tid 11469 * 11470 * Returns the task with the given tid, or NULL if no such task exists. The 11471 * returned pointer is valid until the end of the current RCU read section 11472 * (KF_RCU_PROTECTED). Requires SCX_OPS_TID_TO_TASK to be set on the root 11473 * scheduler; otherwise an error is raised and NULL returned. 11474 */ 11475 __bpf_kfunc struct task_struct *scx_bpf_tid_to_task(u64 tid) 11476 { 11477 struct sched_ext_entity *scx; 11478 11479 if (!scx_tid_to_task_enabled()) { 11480 struct scx_sched *sch = rcu_dereference(scx_root); 11481 11482 if (sch) 11483 scx_error(sch, "scx_bpf_tid_to_task() called without SCX_OPS_TID_TO_TASK"); 11484 return NULL; 11485 } 11486 11487 scx = rhashtable_lookup(&scx_tid_hash, &tid, scx_tid_hash_params); 11488 if (!scx) 11489 return NULL; 11490 11491 return container_of(scx, struct task_struct, scx); 11492 } 11493 11494 u64 __scx_bpf_now(struct rq *rq) 11495 { 11496 /* the caller must be on @rq's cpu or hold its lock */ 11497 lockdep_assert((rq == this_rq() && !preemptible()) || 11498 lockdep_is_held(__rq_lockp(rq))); 11499 11500 if (smp_load_acquire(&rq->scx.flags) & SCX_RQ_CLK_VALID) { 11501 /* if the rq clock is valid, use the cached rq clock */ 11502 return READ_ONCE(rq->scx.clock); 11503 } else { 11504 /* 11505 * Otherwise, return a fresh rq clock. 11506 * 11507 * The rq clock is updated outside of the rq lock. 11508 * In this case, keep the updated rq clock invalid so the next 11509 * read outside the rq lock gets a fresh rq clock. 11510 */ 11511 return sched_clock_cpu(cpu_of(rq)); 11512 } 11513 } 11514 11515 /** 11516 * scx_bpf_now - Returns a high-performance monotonically non-decreasing 11517 * clock for the current CPU. The clock returned is in nanoseconds. 11518 * 11519 * It provides the following properties: 11520 * 11521 * 1) High performance: Many BPF schedulers call bpf_ktime_get_ns() frequently 11522 * to account for execution time and track tasks' runtime properties. 11523 * Unfortunately, in some hardware platforms, bpf_ktime_get_ns() -- which 11524 * eventually reads a hardware timestamp counter -- is neither performant nor 11525 * scalable. scx_bpf_now() aims to provide a high-performance clock by 11526 * using the rq clock in the scheduler core whenever possible. 11527 * 11528 * 2) High enough resolution for the BPF scheduler use cases: In most BPF 11529 * scheduler use cases, the required clock resolution is lower than the most 11530 * accurate hardware clock (e.g., rdtsc in x86). scx_bpf_now() basically 11531 * uses the rq clock in the scheduler core whenever it is valid. It considers 11532 * that the rq clock is valid from the time the rq clock is updated 11533 * (update_rq_clock) until the rq is unlocked (rq_unpin_lock). 11534 * 11535 * 3) Monotonically non-decreasing clock for the same CPU: scx_bpf_now() 11536 * guarantees the clock never goes backward when comparing them in the same 11537 * CPU. On the other hand, when comparing clocks in different CPUs, there 11538 * is no such guarantee -- the clock can go backward. It provides a 11539 * monotonically *non-decreasing* clock so that it would provide the same 11540 * clock values in two different scx_bpf_now() calls in the same CPU 11541 * during the same period of when the rq clock is valid. 11542 */ 11543 __bpf_kfunc u64 scx_bpf_now(void) 11544 { 11545 /* 11546 * Note that scx_bpf_now() is re-entrant between a process context and 11547 * an interrupt context (e.g., timer interrupt). However, we don't need 11548 * to consider the race between them because such race is not observable 11549 * from a caller. 11550 */ 11551 guard(preempt)(); 11552 return __scx_bpf_now(this_rq()); 11553 } 11554 11555 static void scx_read_events(struct scx_sched *sch, struct scx_event_stats *events) 11556 { 11557 int cpu; 11558 11559 /* Aggregate per-CPU event counters into @events. */ 11560 memset(events, 0, sizeof(*events)); 11561 for_each_possible_cpu(cpu) { 11562 struct scx_event_stats *e_cpu = &per_cpu_ptr(sch->pcpu, cpu)->event_stats; 11563 #define SCX_EVENT(name) (events->name += READ_ONCE(e_cpu->name)) 11564 SCX_EVENTS_LIST(SCX_EVENT); 11565 #undef SCX_EVENT 11566 } 11567 } 11568 11569 /** 11570 * scx_bpf_events - Read the event counters of the calling scheduler 11571 * @events: output buffer from a BPF program 11572 * @events__sz: @events len, must end in '__sz' for the verifier 11573 * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs 11574 * 11575 * Read the event counters of the scheduler associated with the calling program. 11576 * @events is zeroed when no scheduler can be resolved. 11577 */ 11578 __bpf_kfunc void scx_bpf_events(struct scx_event_stats *events, size_t events__sz, 11579 const struct bpf_prog_aux *aux) 11580 { 11581 struct scx_sched *sch; 11582 struct scx_event_stats e_sys; 11583 11584 rcu_read_lock(); 11585 sch = scx_prog_sched(aux); 11586 if (sch) 11587 scx_read_events(sch, &e_sys); 11588 else 11589 memset(&e_sys, 0, sizeof(e_sys)); 11590 rcu_read_unlock(); 11591 11592 /* 11593 * We cannot entirely trust a BPF-provided size since a BPF program 11594 * might be compiled against a different vmlinux.h, of which 11595 * scx_event_stats would be larger (a newer vmlinux.h) or smaller 11596 * (an older vmlinux.h). Hence, we use the smaller size to avoid 11597 * memory corruption. 11598 */ 11599 events__sz = min(events__sz, sizeof(*events)); 11600 memcpy(events, &e_sys, events__sz); 11601 } 11602 11603 #ifdef CONFIG_CGROUP_SCHED 11604 /** 11605 * scx_bpf_task_cgroup - Return the sched cgroup of a task 11606 * @p: task of interest 11607 * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs 11608 * 11609 * @p->sched_task_group->css.cgroup represents the cgroup @p is associated with 11610 * from the scheduler's POV. SCX operations should use this function to 11611 * determine @p's current cgroup as, unlike following @p->cgroups, 11612 * @p->sched_task_group is stable for the duration of the SCX op. See 11613 * SCX_CALL_OP_TASK() for details. 11614 */ 11615 __bpf_kfunc struct cgroup *scx_bpf_task_cgroup(struct task_struct *p, 11616 const struct bpf_prog_aux *aux) 11617 { 11618 struct task_group *tg = p->sched_task_group; 11619 struct cgroup *cgrp = &cgrp_dfl_root.cgrp; 11620 struct scx_sched *sch; 11621 11622 guard(rcu)(); 11623 11624 sch = scx_prog_sched(aux); 11625 if (unlikely(!sch)) 11626 goto out; 11627 11628 if (!scx_kf_arg_task_ok(sch, p)) 11629 goto out; 11630 11631 cgrp = tg_cgrp(tg); 11632 11633 out: 11634 cgroup_get(cgrp); 11635 return cgrp; 11636 } 11637 11638 /** 11639 * scx_bpf_cgroup_nr_cpus - Return the number of CPUs in a cgroup's cpuset 11640 * @cgrp: cgroup of interest 11641 * 11642 * Return the number of CPUs in @cgrp's effective cpuset, which is inherited 11643 * from the nearest ancestor with the cpuset controller enabled. This matches 11644 * the count used by fair's group share calculation and lets hierarchical BPF 11645 * schedulers bound a group's weight by the CPUs it can actually run on. 11646 * 11647 * The value is a snapshot and may change at any time through cpuset updates or 11648 * CPU hotplug. Schedulers should re-read it when recomputing group state. 11649 */ 11650 __bpf_kfunc u32 scx_bpf_cgroup_nr_cpus(struct cgroup *cgrp) 11651 { 11652 return cpuset_num_cpus(cgrp); 11653 } 11654 #endif /* CONFIG_CGROUP_SCHED */ 11655 11656 __bpf_kfunc_end_defs(); 11657 11658 BTF_KFUNCS_START(scx_kfunc_ids_any) 11659 BTF_ID_FLAGS(func, scx_bpf_task_set_slice, KF_IMPLICIT_ARGS | KF_RCU); 11660 BTF_ID_FLAGS(func, scx_bpf_task_set_dsq_vtime, KF_IMPLICIT_ARGS | KF_RCU); 11661 BTF_ID_FLAGS(func, scx_bpf_task_set_lazy_resched, KF_IMPLICIT_ARGS | KF_RCU); 11662 BTF_ID_FLAGS(func, scx_bpf_kick_cpu, KF_IMPLICIT_ARGS) 11663 BTF_ID_FLAGS(func, scx_bpf_kick_cid, KF_IMPLICIT_ARGS) 11664 BTF_ID_FLAGS(func, scx_bpf_dsq_nr_queued, KF_IMPLICIT_ARGS) 11665 BTF_ID_FLAGS(func, scx_bpf_destroy_dsq, KF_IMPLICIT_ARGS) 11666 BTF_ID_FLAGS(func, scx_bpf_dsq_peek, KF_IMPLICIT_ARGS | KF_RCU_PROTECTED | KF_RET_NULL) 11667 BTF_ID_FLAGS(func, scx_bpf_dsq_reenq, KF_IMPLICIT_ARGS) 11668 BTF_ID_FLAGS(func, scx_bpf_reenqueue_local___v2, KF_IMPLICIT_ARGS) 11669 BTF_ID_FLAGS(func, bpf_iter_scx_dsq_new, KF_IMPLICIT_ARGS | KF_ITER_NEW | KF_RCU_PROTECTED) 11670 BTF_ID_FLAGS(func, bpf_iter_scx_dsq_next, KF_ITER_NEXT | KF_RET_NULL) 11671 BTF_ID_FLAGS(func, bpf_iter_scx_dsq_destroy, KF_ITER_DESTROY) 11672 BTF_ID_FLAGS(func, scx_bpf_exit_bstr, KF_IMPLICIT_ARGS) 11673 BTF_ID_FLAGS(func, scx_bpf_error_bstr, KF_IMPLICIT_ARGS) 11674 BTF_ID_FLAGS(func, scx_bpf_dump_bstr, KF_IMPLICIT_ARGS) 11675 BTF_ID_FLAGS(func, scx_bpf_cpuperf_cap, KF_IMPLICIT_ARGS) 11676 BTF_ID_FLAGS(func, scx_bpf_cpuperf_cur, KF_IMPLICIT_ARGS) 11677 BTF_ID_FLAGS(func, scx_bpf_cpuperf_set, KF_IMPLICIT_ARGS) 11678 BTF_ID_FLAGS(func, scx_bpf_cidperf_cap, KF_IMPLICIT_ARGS) 11679 BTF_ID_FLAGS(func, scx_bpf_cidperf_cur, KF_IMPLICIT_ARGS) 11680 BTF_ID_FLAGS(func, scx_bpf_cidperf_set, KF_IMPLICIT_ARGS) 11681 BTF_ID_FLAGS(func, scx_bpf_nr_node_ids) 11682 BTF_ID_FLAGS(func, scx_bpf_nr_cpu_ids) 11683 BTF_ID_FLAGS(func, scx_bpf_nr_cids) 11684 BTF_ID_FLAGS(func, scx_bpf_nr_online_cids) 11685 BTF_ID_FLAGS(func, scx_bpf_online_cmask, KF_IMPLICIT_ARGS | KF_ARENA_RET) 11686 BTF_ID_FLAGS(func, scx_bpf_this_cid) 11687 BTF_ID_FLAGS(func, scx_bpf_get_possible_cpumask, KF_ACQUIRE) 11688 BTF_ID_FLAGS(func, scx_bpf_get_online_cpumask, KF_ACQUIRE) 11689 BTF_ID_FLAGS(func, scx_bpf_put_cpumask, KF_RELEASE) 11690 BTF_ID_FLAGS(func, scx_bpf_task_running, KF_RCU) 11691 BTF_ID_FLAGS(func, scx_bpf_task_cpu, KF_RCU) 11692 BTF_ID_FLAGS(func, scx_bpf_task_cid, KF_RCU) 11693 BTF_ID_FLAGS(func, scx_bpf_locked_rq, KF_IMPLICIT_ARGS | KF_RET_NULL) 11694 BTF_ID_FLAGS(func, scx_bpf_cpu_curr, KF_IMPLICIT_ARGS | KF_RET_NULL | KF_RCU_PROTECTED) 11695 BTF_ID_FLAGS(func, scx_bpf_cid_curr, KF_IMPLICIT_ARGS | KF_RET_NULL | KF_RCU_PROTECTED) 11696 BTF_ID_FLAGS(func, scx_bpf_tid_to_task, KF_RET_NULL | KF_RCU_PROTECTED) 11697 BTF_ID_FLAGS(func, scx_bpf_now) 11698 BTF_ID_FLAGS(func, scx_bpf_events, KF_IMPLICIT_ARGS) 11699 #ifdef CONFIG_CGROUP_SCHED 11700 BTF_ID_FLAGS(func, scx_bpf_task_cgroup, KF_IMPLICIT_ARGS | KF_RCU | KF_ACQUIRE) 11701 BTF_ID_FLAGS(func, scx_bpf_cgroup_nr_cpus, KF_RCU) 11702 #endif 11703 BTF_ID_FLAGS(func, scx_bpf_sub_grant, KF_IMPLICIT_ARGS) 11704 BTF_ID_FLAGS(func, scx_bpf_sub_revoke, KF_IMPLICIT_ARGS) 11705 BTF_ID_FLAGS(func, scx_bpf_sub_caps, KF_IMPLICIT_ARGS) 11706 BTF_ID_FLAGS(func, scx_bpf_sub_kill_bstr, KF_IMPLICIT_ARGS) 11707 BTF_KFUNCS_END(scx_kfunc_ids_any) 11708 11709 static const struct btf_kfunc_id_set scx_kfunc_set_any = { 11710 .owner = THIS_MODULE, 11711 .set = &scx_kfunc_ids_any, 11712 .filter = scx_kfunc_context_filter, 11713 }; 11714 11715 /* 11716 * cpu-form kfuncs that are forbidden from cid-form schedulers 11717 * (bpf_sched_ext_ops_cid). Programs targeting the cid struct_ops type must 11718 * use the cid-form alternative (cid/cmask kfuncs). 11719 * 11720 * Membership overlaps with scx_kfunc_ids_{any,idle,select_cpu}; the filter 11721 * tests this set independently and rejects matches before the per-op 11722 * allow-list check runs. 11723 * 11724 * pahole/resolve_btfids scans every BTF_ID_FLAGS() at build time and 11725 * intersects flags across duplicate entries, so each entry must carry the 11726 * same flags as the kfunc's primary declaration; otherwise the flags get 11727 * dropped globally. 11728 */ 11729 BTF_KFUNCS_START(scx_kfunc_ids_cpu_only) 11730 BTF_ID_FLAGS(func, scx_bpf_kick_cpu, KF_IMPLICIT_ARGS) 11731 BTF_ID_FLAGS(func, scx_bpf_task_cpu, KF_RCU) 11732 BTF_ID_FLAGS(func, scx_bpf_cpu_curr, KF_IMPLICIT_ARGS | KF_RET_NULL | KF_RCU_PROTECTED) 11733 BTF_ID_FLAGS(func, scx_bpf_cpu_node, KF_IMPLICIT_ARGS) 11734 BTF_ID_FLAGS(func, scx_bpf_cpuperf_cap, KF_IMPLICIT_ARGS) 11735 BTF_ID_FLAGS(func, scx_bpf_cpuperf_cur, KF_IMPLICIT_ARGS) 11736 BTF_ID_FLAGS(func, scx_bpf_cpuperf_set, KF_IMPLICIT_ARGS) 11737 BTF_ID_FLAGS(func, scx_bpf_get_possible_cpumask, KF_ACQUIRE) 11738 BTF_ID_FLAGS(func, scx_bpf_get_online_cpumask, KF_ACQUIRE) 11739 BTF_ID_FLAGS(func, scx_bpf_put_cpumask, KF_RELEASE) 11740 BTF_ID_FLAGS(func, scx_bpf_select_cpu_dfl, KF_IMPLICIT_ARGS | KF_RCU) 11741 BTF_ID_FLAGS(func, __scx_bpf_select_cpu_and, KF_IMPLICIT_ARGS | KF_RCU) 11742 BTF_ID_FLAGS(func, scx_bpf_select_cpu_and, KF_RCU) 11743 BTF_ID_FLAGS(func, scx_bpf_get_idle_cpumask, KF_IMPLICIT_ARGS | KF_ACQUIRE) 11744 BTF_ID_FLAGS(func, scx_bpf_get_idle_cpumask_node, KF_IMPLICIT_ARGS | KF_ACQUIRE) 11745 BTF_ID_FLAGS(func, scx_bpf_get_idle_smtmask, KF_IMPLICIT_ARGS | KF_ACQUIRE) 11746 BTF_ID_FLAGS(func, scx_bpf_get_idle_smtmask_node, KF_IMPLICIT_ARGS | KF_ACQUIRE) 11747 BTF_ID_FLAGS(func, scx_bpf_put_idle_cpumask, KF_RELEASE) 11748 BTF_ID_FLAGS(func, scx_bpf_test_and_clear_cpu_idle, KF_IMPLICIT_ARGS) 11749 BTF_ID_FLAGS(func, scx_bpf_pick_idle_cpu, KF_IMPLICIT_ARGS | KF_RCU) 11750 BTF_ID_FLAGS(func, scx_bpf_pick_idle_cpu_node, KF_IMPLICIT_ARGS | KF_RCU) 11751 BTF_ID_FLAGS(func, scx_bpf_pick_any_cpu, KF_IMPLICIT_ARGS | KF_RCU) 11752 BTF_ID_FLAGS(func, scx_bpf_pick_any_cpu_node, KF_IMPLICIT_ARGS | KF_RCU) 11753 BTF_KFUNCS_END(scx_kfunc_ids_cpu_only) 11754 11755 /* 11756 * Per-op kfunc allow flags. Each bit corresponds to a context-sensitive kfunc 11757 * group; an op may permit zero or more groups, with the union expressed in 11758 * scx_kf_allow_flags[]. The verifier-time filter (scx_kfunc_context_filter()) 11759 * consults this table to decide whether a context-sensitive kfunc is callable 11760 * from a given SCX op. 11761 */ 11762 enum scx_kf_allow_flags { 11763 SCX_KF_ALLOW_UNLOCKED = 1 << 0, 11764 SCX_KF_ALLOW_INIT_CIDS = 1 << 1, 11765 SCX_KF_ALLOW_CPU_RELEASE = 1 << 2, 11766 SCX_KF_ALLOW_DISPATCH = 1 << 3, 11767 SCX_KF_ALLOW_ENQUEUE = 1 << 4, 11768 SCX_KF_ALLOW_SELECT_CPU = 1 << 5, 11769 }; 11770 11771 /* 11772 * Map each SCX op to the union of kfunc groups it permits, indexed by 11773 * SCX_OP_IDX(op). Ops not listed only permit kfuncs that are not 11774 * context-sensitive. 11775 */ 11776 static const u32 scx_kf_allow_flags[] = { 11777 [SCX_OP_IDX(select_cpu)] = SCX_KF_ALLOW_SELECT_CPU | SCX_KF_ALLOW_ENQUEUE, 11778 [SCX_OP_IDX(enqueue)] = SCX_KF_ALLOW_SELECT_CPU | SCX_KF_ALLOW_ENQUEUE, 11779 [SCX_OP_IDX(dispatch)] = SCX_KF_ALLOW_ENQUEUE | SCX_KF_ALLOW_DISPATCH, 11780 [SCX_OP_IDX(cpu_release)] = SCX_KF_ALLOW_CPU_RELEASE, 11781 [SCX_OP_IDX(init_task)] = SCX_KF_ALLOW_UNLOCKED, 11782 [SCX_OP_IDX(dump)] = SCX_KF_ALLOW_UNLOCKED, 11783 #ifdef CONFIG_EXT_GROUP_SCHED 11784 [SCX_OP_IDX(cgroup_init)] = SCX_KF_ALLOW_UNLOCKED, 11785 [SCX_OP_IDX(cgroup_exit)] = SCX_KF_ALLOW_UNLOCKED, 11786 [SCX_OP_IDX(cgroup_prep_move)] = SCX_KF_ALLOW_UNLOCKED, 11787 [SCX_OP_IDX(cgroup_cancel_move)] = SCX_KF_ALLOW_UNLOCKED, 11788 [SCX_OP_IDX(cgroup_set_weight)] = SCX_KF_ALLOW_UNLOCKED, 11789 [SCX_OP_IDX(cgroup_set_bandwidth)] = SCX_KF_ALLOW_UNLOCKED, 11790 [SCX_OP_IDX(cgroup_set_idle)] = SCX_KF_ALLOW_UNLOCKED, 11791 #endif /* CONFIG_EXT_GROUP_SCHED */ 11792 [SCX_OP_IDX(sub_attach)] = SCX_KF_ALLOW_UNLOCKED, 11793 [SCX_OP_IDX(sub_detach)] = SCX_KF_ALLOW_UNLOCKED, 11794 [SCX_OP_IDX(sub_ecaps_updated)] = SCX_KF_ALLOW_ENQUEUE | SCX_KF_ALLOW_DISPATCH, 11795 [SCX_OP_IDX(sub_child_ecaps_updated)] = SCX_KF_ALLOW_ENQUEUE | SCX_KF_ALLOW_DISPATCH, 11796 [SCX_OP_IDX(cpu_online)] = SCX_KF_ALLOW_UNLOCKED, 11797 [SCX_OP_IDX(cpu_offline)] = SCX_KF_ALLOW_UNLOCKED, 11798 [SCX_OP_IDX(init_cids)] = SCX_KF_ALLOW_UNLOCKED | SCX_KF_ALLOW_INIT_CIDS, 11799 [SCX_OP_IDX(init)] = SCX_KF_ALLOW_UNLOCKED, 11800 [SCX_OP_IDX(exit)] = SCX_KF_ALLOW_UNLOCKED, 11801 }; 11802 11803 /* 11804 * Verifier-time filter for SCX kfuncs. Registered via the .filter field on 11805 * each per-group btf_kfunc_id_set. The BPF core invokes this for every kfunc 11806 * call in the registered hook (BPF_PROG_TYPE_STRUCT_OPS or 11807 * BPF_PROG_TYPE_SYSCALL), regardless of which set originally introduced the 11808 * kfunc - so the filter must short-circuit on kfuncs it doesn't govern by 11809 * falling through to "allow" when none of the SCX sets contain the kfunc. 11810 */ 11811 int scx_kfunc_context_filter(const struct bpf_prog *prog, u32 kfunc_id) 11812 { 11813 bool in_unlocked = btf_id_set8_contains(&scx_kfunc_ids_unlocked, kfunc_id); 11814 bool in_init_cids = btf_id_set8_contains(&scx_kfunc_ids_init_cids, kfunc_id); 11815 bool in_select_cpu = btf_id_set8_contains(&scx_kfunc_ids_select_cpu, kfunc_id); 11816 bool in_enqueue = btf_id_set8_contains(&scx_kfunc_ids_enqueue_dispatch, kfunc_id); 11817 bool in_dispatch = btf_id_set8_contains(&scx_kfunc_ids_dispatch, kfunc_id); 11818 bool in_cpu_release = btf_id_set8_contains(&scx_kfunc_ids_cpu_release, kfunc_id); 11819 bool in_idle = btf_id_set8_contains(&scx_kfunc_ids_idle, kfunc_id); 11820 bool in_any = btf_id_set8_contains(&scx_kfunc_ids_any, kfunc_id); 11821 bool in_cpu_only = btf_id_set8_contains(&scx_kfunc_ids_cpu_only, kfunc_id); 11822 bool in_cid = btf_id_set8_contains(&scx_kfunc_ids_cid, kfunc_id); 11823 u32 moff, flags; 11824 11825 /* Not an SCX kfunc - allow. */ 11826 if (!(in_unlocked || in_init_cids || in_select_cpu || in_enqueue || in_dispatch || 11827 in_cpu_release || in_idle || in_any || in_cid)) 11828 return 0; 11829 11830 /* SYSCALL progs (e.g. BPF test_run()) may call unlocked and select_cpu kfuncs. */ 11831 if (prog->type == BPF_PROG_TYPE_SYSCALL) 11832 return (in_unlocked || in_select_cpu || in_idle || in_any || in_cid) ? 0 : -EACCES; 11833 11834 if (prog->type != BPF_PROG_TYPE_STRUCT_OPS) 11835 return (in_any || in_idle || in_cid) ? 0 : -EACCES; 11836 11837 /* 11838 * add_subprog_and_kfunc() collects all kfunc calls, including dead code 11839 * guarded by bpf_ksym_exists(), before check_attach_btf_id() sets 11840 * prog->aux->st_ops. Allow all kfuncs when st_ops is not yet set; 11841 * do_check_main() re-runs the filter with st_ops set and enforces the 11842 * actual restrictions. 11843 */ 11844 if (!prog->aux->st_ops) 11845 return 0; 11846 11847 /* 11848 * Non-SCX struct_ops: SCX kfuncs are not permitted. 11849 * 11850 * Both bpf_sched_ext_ops (cpu-form) and bpf_sched_ext_ops_cid 11851 * (cid-form) are valid SCX struct_ops. Member offsets match between 11852 * the two (verified by BUILD_BUG_ON in scx_init()), so the shared 11853 * scx_kf_allow_flags[] table indexed by SCX_MOFF_IDX(moff) applies to 11854 * both. 11855 */ 11856 if (prog->aux->st_ops != &bpf_sched_ext_ops && 11857 prog->aux->st_ops != &bpf_sched_ext_ops_cid) 11858 return -EACCES; 11859 11860 /* 11861 * cid-form schedulers must use cid/cmask kfuncs. cid and cpu are both 11862 * small s32s and trivially confused, so cpu-only kfuncs are rejected at 11863 * load time. The reverse (cpu-form calling cid-form kfuncs) is 11864 * intentionally permissive to ease gradual cpumask -> cid migration. 11865 */ 11866 if (prog->aux->st_ops == &bpf_sched_ext_ops_cid && in_cpu_only) 11867 return -EACCES; 11868 11869 /* SCX struct_ops: check the per-op allow list. */ 11870 if (in_any || in_idle || in_cid) 11871 return 0; 11872 11873 moff = prog->aux->attach_st_ops_member_off; 11874 flags = scx_kf_allow_flags[SCX_MOFF_IDX(moff)]; 11875 11876 if ((flags & SCX_KF_ALLOW_UNLOCKED) && in_unlocked) 11877 return 0; 11878 if ((flags & SCX_KF_ALLOW_INIT_CIDS) && in_init_cids) 11879 return 0; 11880 if ((flags & SCX_KF_ALLOW_CPU_RELEASE) && in_cpu_release) 11881 return 0; 11882 if ((flags & SCX_KF_ALLOW_DISPATCH) && in_dispatch) 11883 return 0; 11884 if ((flags & SCX_KF_ALLOW_ENQUEUE) && in_enqueue) 11885 return 0; 11886 if ((flags & SCX_KF_ALLOW_SELECT_CPU) && in_select_cpu) 11887 return 0; 11888 11889 return -EACCES; 11890 } 11891 11892 static int __init scx_init(void) 11893 { 11894 int ret; 11895 11896 /* 11897 * sched_ext_ops_cid mirrors sched_ext_ops up to and including @priv. 11898 * Both bpf_scx_init_member() and bpf_scx_check_member() use offsets 11899 * from struct sched_ext_ops; sched_ext_ops_cid relies on those offsets 11900 * matching for the shared fields. Catch any drift at boot. 11901 */ 11902 #define CID_OFFSET_MATCH(cpu_field, cid_field) \ 11903 BUILD_BUG_ON(offsetof(struct sched_ext_ops, cpu_field) != \ 11904 offsetof(struct sched_ext_ops_cid, cid_field)) 11905 /* data fields used by bpf_scx_init_member() */ 11906 CID_OFFSET_MATCH(dispatch_max_batch, dispatch_max_batch); 11907 CID_OFFSET_MATCH(flags, flags); 11908 CID_OFFSET_MATCH(name, name); 11909 CID_OFFSET_MATCH(timeout_ms, timeout_ms); 11910 CID_OFFSET_MATCH(exit_dump_len, exit_dump_len); 11911 CID_OFFSET_MATCH(hotplug_seq, hotplug_seq); 11912 CID_OFFSET_MATCH(cid_shard_size, cid_shard_size); 11913 CID_OFFSET_MATCH(rescue_bandwidth_ppt, rescue_bandwidth_ppt); 11914 CID_OFFSET_MATCH(rescue_quantum_us, rescue_quantum_us); 11915 CID_OFFSET_MATCH(sub_cgroup_id, sub_cgroup_id); 11916 /* shared callbacks: the union view requires byte-for-byte offset match */ 11917 CID_OFFSET_MATCH(enqueue, enqueue); 11918 CID_OFFSET_MATCH(dequeue, dequeue); 11919 CID_OFFSET_MATCH(dispatch, dispatch); 11920 CID_OFFSET_MATCH(tick, tick); 11921 CID_OFFSET_MATCH(runnable, runnable); 11922 CID_OFFSET_MATCH(running, running); 11923 CID_OFFSET_MATCH(stopping, stopping); 11924 CID_OFFSET_MATCH(quiescent, quiescent); 11925 CID_OFFSET_MATCH(yield, yield); 11926 CID_OFFSET_MATCH(core_sched_before, core_sched_before); 11927 CID_OFFSET_MATCH(set_weight, set_weight); 11928 CID_OFFSET_MATCH(update_idle, update_idle); 11929 CID_OFFSET_MATCH(init_task, init_task); 11930 CID_OFFSET_MATCH(exit_task, exit_task); 11931 CID_OFFSET_MATCH(enable, enable); 11932 CID_OFFSET_MATCH(disable, disable); 11933 CID_OFFSET_MATCH(dump, dump); 11934 CID_OFFSET_MATCH(dump_task, dump_task); 11935 CID_OFFSET_MATCH(sub_attach, sub_attach); 11936 CID_OFFSET_MATCH(sub_detach, sub_detach); 11937 CID_OFFSET_MATCH(sub_caps_updated, sub_caps_updated); 11938 CID_OFFSET_MATCH(sub_ecaps_updated, sub_ecaps_updated); 11939 CID_OFFSET_MATCH(sub_cid_sched_updated, sub_cid_sched_updated); 11940 CID_OFFSET_MATCH(sub_child_ecaps_updated, sub_child_ecaps_updated); 11941 CID_OFFSET_MATCH(init_cids, init_cids); 11942 CID_OFFSET_MATCH(init, init); 11943 CID_OFFSET_MATCH(exit, exit); 11944 /* renamed callbacks must occupy the same slot as their cpu-form sibling */ 11945 CID_OFFSET_MATCH(select_cpu, select_cid); 11946 CID_OFFSET_MATCH(set_cpumask, set_cmask); 11947 CID_OFFSET_MATCH(cpu_online, cid_online); 11948 CID_OFFSET_MATCH(cpu_offline, cid_offline); 11949 CID_OFFSET_MATCH(dump_cpu, dump_cid); 11950 #ifdef CONFIG_EXT_GROUP_SCHED 11951 CID_OFFSET_MATCH(cgroup_init, cpuctl_init); 11952 CID_OFFSET_MATCH(cgroup_exit, cpuctl_exit); 11953 CID_OFFSET_MATCH(cgroup_prep_move, cpuctl_prep_move); 11954 CID_OFFSET_MATCH(cgroup_move, cpuctl_move); 11955 CID_OFFSET_MATCH(cgroup_cancel_move, cpuctl_cancel_move); 11956 CID_OFFSET_MATCH(cgroup_set_weight, cpuctl_set_weight); 11957 CID_OFFSET_MATCH(cgroup_set_bandwidth, cpuctl_set_bandwidth); 11958 CID_OFFSET_MATCH(cgroup_set_idle, cpuctl_set_idle); 11959 #endif 11960 /* @priv tail must align since both share the same data block */ 11961 CID_OFFSET_MATCH(priv, priv); 11962 /* 11963 * cid-form must end exactly at @priv - scx_validate_ops() skips 11964 * cpu_acquire/cpu_release for cid-form because reading those fields 11965 * past the BPF allocation would be UB. 11966 */ 11967 BUILD_BUG_ON(offsetof(struct sched_ext_ops_cid, __end) != 11968 offsetofend(struct sched_ext_ops, priv)); 11969 #undef CID_OFFSET_MATCH 11970 11971 /* 11972 * kfunc registration can't be done from init_sched_ext_class() as 11973 * register_btf_kfunc_id_set() needs most of the system to be up. 11974 * 11975 * Some kfuncs are context-sensitive and can only be called from 11976 * specific SCX ops. They are grouped into per-context BTF sets, each 11977 * registered with scx_kfunc_context_filter as its .filter callback. The 11978 * BPF core dedups identical filter pointers per hook 11979 * (btf_populate_kfunc_set()), so the filter is invoked exactly once per 11980 * kfunc lookup; it consults scx_kf_allow_flags[] to enforce per-op 11981 * restrictions at verify time. 11982 */ 11983 if ((ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_STRUCT_OPS, 11984 &scx_kfunc_set_enqueue_dispatch)) || 11985 (ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_STRUCT_OPS, 11986 &scx_kfunc_set_dispatch)) || 11987 (ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_STRUCT_OPS, 11988 &scx_kfunc_set_cpu_release)) || 11989 (ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_STRUCT_OPS, 11990 &scx_kfunc_set_unlocked)) || 11991 (ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_SYSCALL, 11992 &scx_kfunc_set_unlocked)) || 11993 (ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_STRUCT_OPS, 11994 &scx_kfunc_set_any)) || 11995 (ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_TRACING, 11996 &scx_kfunc_set_any)) || 11997 (ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_SYSCALL, 11998 &scx_kfunc_set_any))) { 11999 pr_err("sched_ext: Failed to register kfunc sets (%d)\n", ret); 12000 return ret; 12001 } 12002 12003 ret = scx_idle_init(); 12004 if (ret) { 12005 pr_err("sched_ext: Failed to initialize idle tracking (%d)\n", ret); 12006 return ret; 12007 } 12008 12009 ret = scx_cid_kfunc_init(); 12010 if (ret) { 12011 pr_err("sched_ext: Failed to register cid kfuncs (%d)\n", ret); 12012 return ret; 12013 } 12014 12015 ret = register_bpf_struct_ops(&bpf_sched_ext_ops, sched_ext_ops); 12016 if (ret) { 12017 pr_err("sched_ext: Failed to register struct_ops (%d)\n", ret); 12018 return ret; 12019 } 12020 12021 ret = register_bpf_struct_ops(&bpf_sched_ext_ops_cid, sched_ext_ops_cid); 12022 if (ret) { 12023 pr_err("sched_ext: Failed to register cid struct_ops (%d)\n", ret); 12024 return ret; 12025 } 12026 12027 ret = register_pm_notifier(&scx_pm_notifier); 12028 if (ret) { 12029 pr_err("sched_ext: Failed to register PM notifier (%d)\n", ret); 12030 return ret; 12031 } 12032 12033 scx_kset = kset_create_and_add("sched_ext", &scx_uevent_ops, kernel_kobj); 12034 if (!scx_kset) { 12035 pr_err("sched_ext: Failed to create /sys/kernel/sched_ext\n"); 12036 return -ENOMEM; 12037 } 12038 12039 ret = sysfs_create_group(&scx_kset->kobj, &scx_global_attr_group); 12040 if (ret < 0) { 12041 pr_err("sched_ext: Failed to add global attributes\n"); 12042 return ret; 12043 } 12044 12045 return 0; 12046 } 12047 __initcall(scx_init); 12048 12049 /* 12050 * Compatibility markers for userspace. Existence of a marker function 12051 * represents that the kernel supports that sched-ext feature. 12052 */ 12053 12054 /* 12055 * scx_compat_marker_cgroup_set_bandwidth_may_sleep: advertises that 12056 * ops.cgroup_set_bandwidth() may be implemented as a sleepable callback. 12057 */ 12058 #ifdef CONFIG_EXT_GROUP_SCHED 12059 DEFINE_SCX_COMPAT_MARKER(cgroup_set_bandwidth_may_sleep); 12060 #endif /* CONFIG_EXT_GROUP_SCHED */ 12061