1 // SPDX-License-Identifier: GPL-2.0 2 /* 3 * BPF extensible scheduler class: Documentation/scheduler/sched-ext.rst 4 * 5 * Sub-scheduler hierarchy support. 6 * 7 * A sub-scheduler is an scx_sched attached to a cgroup subtree under another 8 * scx_sched. This file holds the sub-scheduler implementation: the scheduler 9 * tree walk, capability delegation, per-shard cap state and its sync, and the 10 * sub-scheduler enable/disable paths. The core dispatch/enqueue machinery it 11 * builds on lives in ext.c. 12 * 13 * Copyright (c) 2026 Meta Platforms, Inc. and affiliates. 14 * Copyright (c) 2026 Tejun Heo <tj@kernel.org> 15 */ 16 #include <linux/rhashtable.h> 17 #include "internal.h" 18 #include "cid.h" 19 #include "arena.h" 20 #include "sub.h" 21 #include "inlines.h" 22 23 #ifdef CONFIG_EXT_SUB_SCHED 24 25 /* 26 * On while any sub-scheduler exists so that a root-only system doesn't pay for 27 * the sub-sched portions of hot paths. See scx_has_subs(). 28 */ 29 DEFINE_STATIC_KEY_FALSE(__scx_has_subs); 30 31 /** 32 * scx_skip_subtree_pre - Skip @pos's subtree in a pre-order walk 33 * @pos: current position 34 * @root: walk root 35 * 36 * In a walk started by scx_next_descendant_pre(), continue past @pos's subtree: 37 * return @pos's next sibling, or the closest ancestor's next sibling, or NULL 38 * if @pos's subtree is the last under @root. Same locking rules. 39 */ 40 struct scx_sched *scx_skip_subtree_pre(struct scx_sched *pos, struct scx_sched *root) 41 { 42 struct scx_sched *next; 43 44 lockdep_assert(lockdep_is_held(&scx_enable_mutex) || 45 lockdep_is_held(&scx_sched_lock) || 46 rcu_read_lock_any_held()); 47 48 while (pos != root) { 49 next = list_next_or_null_rcu(&scx_parent(pos)->children, &pos->sibling, 50 struct scx_sched, sibling); 51 if (next) 52 return next; 53 pos = scx_parent(pos); 54 } 55 return NULL; 56 } 57 58 /** 59 * scx_next_descendant_pre - find the next descendant for pre-order walk 60 * @pos: the current position (%NULL to initiate traversal) 61 * @root: sched whose descendants to walk 62 * 63 * To be used by scx_for_each_descendant_pre(). Find the next descendant to 64 * visit for pre-order traversal of @root's descendants. @root is included in 65 * the iteration and the first node to be visited. 66 */ 67 struct scx_sched *scx_next_descendant_pre(struct scx_sched *pos, struct scx_sched *root) 68 { 69 struct scx_sched *next; 70 71 lockdep_assert(lockdep_is_held(&scx_enable_mutex) || 72 lockdep_is_held(&scx_sched_lock) || 73 rcu_read_lock_any_held()); 74 75 /* if first iteration, visit @root */ 76 if (!pos) 77 return root; 78 79 /* visit the first child if exists */ 80 next = list_first_or_null_rcu(&pos->children, struct scx_sched, sibling); 81 if (next) 82 return next; 83 84 /* no child, visit my or the closest ancestor's next sibling */ 85 return scx_skip_subtree_pre(pos, root); 86 } 87 88 static struct scx_sched *scx_find_sub_sched(u64 cgroup_id) 89 { 90 return rhashtable_lookup(&scx_sched_hash, &cgroup_id, 91 scx_sched_hash_params); 92 } 93 94 void scx_set_task_sched(struct task_struct *p, struct scx_sched *sch) 95 { 96 rcu_assign_pointer(p->scx.sched, sch); 97 } 98 99 struct cgroup *sch_cgroup(struct scx_sched *sch) 100 { 101 return sch->cgrp; 102 } 103 104 /* for each descendant of @cgrp including self, set ->scx_sched to @sch */ 105 void set_cgroup_sched(struct cgroup *cgrp, struct scx_sched *sch) 106 { 107 struct cgroup *pos; 108 struct cgroup_subsys_state *css; 109 110 cgroup_for_each_live_descendant_pre(pos, css, cgrp) 111 rcu_assign_pointer(pos->scx_sched, sch); 112 } 113 114 static void free_pshard(struct scx_pshard *pshard) 115 { 116 struct scx_caps_updated *cu; 117 118 if (!pshard) 119 return; 120 cu = &pshard->caps_updated; 121 if (cu->cmask_arena_out) 122 scx_arena_free(pshard->sch, cu->cmask_arena_out, 123 struct_size_t(struct scx_cmask, bits, 124 SCX_CMASK_NR_WORDS(pshard->nr_cids))); 125 kfree(pshard); 126 } 127 128 void scx_free_pshards(struct scx_sched *sch) 129 { 130 s32 si; 131 132 if (!sch->pshard) 133 return; 134 for (si = 0; si < sch->nr_pshards; si++) 135 free_pshard(sch->pshard[si]); 136 kfree(sch->pshard); 137 } 138 139 static struct scx_pshard *alloc_pshard(struct scx_sched *sch, s32 shard_idx, s32 node) 140 { 141 const struct scx_cid_shard *shard = &scx_cid_shard_ranges[shard_idx]; 142 size_t cmask_size = struct_size_t(struct scx_cmask, bits, 143 SCX_CMASK_NR_WORDS(shard->nr_cids)); 144 struct scx_pshard *pshard; 145 struct scx_caps_updated *cu; 146 s32 i; 147 148 pshard = kzalloc_node(sizeof(*pshard), GFP_KERNEL, node); 149 if (!pshard) 150 return NULL; 151 152 raw_spin_lock_init(&pshard->lock); 153 pshard->sch = sch; 154 pshard->base = shard->base_cid; 155 pshard->nr_cids = shard->nr_cids; 156 157 for (i = 0; i < __SCX_NR_CAPS; i++) 158 scx_cmask_init(&pshard->caps[i].cmask, shard->base_cid, shard->nr_cids); 159 160 cu = &pshard->caps_updated; 161 raw_spin_lock_init(&cu->lock); 162 INIT_LIST_HEAD(&cu->node_in_flight); 163 __scx_cmask_init(&cu->cmask, shard->base_cid, shard->nr_cids, SCX_CID_SHARD_MAX_CPUS); 164 165 cu->cmask_arena_out = scx_arena_alloc(sch, cmask_size); 166 if (!cu->cmask_arena_out) { 167 free_pshard(pshard); 168 return NULL; 169 } 170 171 scx_cmask_init(cu->cmask_arena_out, shard->base_cid, shard->nr_cids); 172 173 return pshard; 174 } 175 176 s32 scx_alloc_pshards(struct scx_sched *sch) 177 { 178 struct scx_pshard **pshard; 179 s32 si; 180 181 if (!sch->is_cid_type || !sch->arena_pool) 182 return 0; 183 184 pshard = kzalloc_objs(pshard[0], scx_nr_cid_shards, GFP_KERNEL); 185 if (!pshard) 186 return -ENOMEM; 187 188 for (si = 0; si < scx_nr_cid_shards; si++) { 189 pshard[si] = alloc_pshard(sch, si, scx_shard_node[si]); 190 if (!pshard[si]) { 191 while (--si >= 0) 192 free_pshard(pshard[si]); 193 kfree(pshard); 194 return -ENOMEM; 195 } 196 } 197 198 sch->nr_pshards = scx_nr_cid_shards; 199 /* 200 * Publish only after every entry is built so a reader observing 201 * @sch->pshard never sees a partially-filled array. Pair the store 202 * with a barrier and READ_ONCE() on the read side. 203 */ 204 smp_wmb(); 205 WRITE_ONCE(sch->pshard, pshard); 206 return 0; 207 } 208 209 /* 210 * Seed the root's caps fully. Root owns all cids on all caps at enable time. 211 * Children acquire caps via scx_bpf_sub_grant(). 212 */ 213 void scx_init_root_caps(struct scx_sched *sch) 214 { 215 s32 si, i; 216 217 for (si = 0; si < sch->nr_pshards; si++) { 218 struct scx_pshard *ps = sch->pshard[si]; 219 220 for (i = 0; i < __SCX_NR_CAPS; i++) 221 scx_cmask_fill(&ps->caps[i].cmask); 222 } 223 } 224 225 /** 226 * scx_local_or_reject_dsq - Pick the local or reject DSQ for an insert 227 * @sch: enqueuing sub-sched 228 * @rq: rq whose local DSQ @p targets 229 * @p: task being inserted 230 * @enq_flags: in/out, unhonored flags are cleared 231 * 232 * Return @rq's local DSQ if @sch holds the required caps on @rq's cid, 233 * otherwise @rq's reject DSQ after recording the reenq reason on @p. 234 * 235 * %SCX_ENQ_IMMED and %SCX_ENQ_PREEMPT are cleared when diverting to reject. 236 * %SCX_ENQ_PREEMPT is also cleared on a fallback migration-disabled admission. 237 * 238 * Bypass doesn't need special-casing as a bypassing sched's tasks are enqueued 239 * to and run by its nearest non-bypassing ancestor. If root is bypassing, it 240 * always holds all caps. 241 */ 242 struct scx_dispatch_q *scx_local_or_reject_dsq(struct scx_sched *sch, struct rq *rq, 243 struct task_struct *p, u64 *enq_flags) 244 { 245 if (!scx_has_subs()) 246 return &rq->scx.local_dsq; 247 248 s32 cid = __scx_cpu_to_cid(cpu_of(rq)); 249 struct scx_sched *asch = rq->scx.remote_activate_sch ?: sch; 250 u64 needed = scx_caps_for_enq(*enq_flags); 251 u64 missing; 252 253 /* 254 * On a remote activation the scheduling sched (@asch) differs from 255 * @p's owner (@sch). Check caps against the scheduling sched. 256 */ 257 if (*enq_flags & SCX_ENQ_PREEMPT) 258 needed |= scx_caps_for_preempt(asch, rq); 259 missing = scx_missing_caps(asch, cpu_of(rq), needed); 260 261 /* requirements met */ 262 if (likely(!missing)) 263 return &rq->scx.local_dsq; 264 265 /* 266 * The task must run on this CPU regardless of caps: the rq is draining 267 * offline (BPF scheduler bypassed), the task is migration-disabled, or a 268 * migration is pending. Admit despite the missing caps and count it. 269 * Refuse preemptions. 270 */ 271 if (unlikely(!scx_rq_online(rq) || is_migration_disabled(p) || 272 p->migration_pending)) { 273 __scx_add_event(sch, SCX_EV_SUB_FORCED_ADMIT, 1); 274 *enq_flags &= ~SCX_ENQ_PREEMPT; 275 return &rq->scx.local_dsq; 276 } 277 278 p->scx.reenq_reason_caps = missing; 279 p->scx.reenq_reason_cid = cid; 280 281 /* 282 * Only local DSQ can honor IMMED and dsq_inc_nr() WARNs on IMMED into 283 * others. Strip both the enq flag and the sticky task flag - the 284 * latter can carry in from an earlier admitted IMMED insert. Strip 285 * PREEMPT too. 286 */ 287 *enq_flags &= ~(SCX_ENQ_IMMED | SCX_ENQ_PREEMPT); 288 p->scx.flags &= ~SCX_TASK_IMMED; 289 290 return &rq->scx.reject_dsq; 291 } 292 293 /* @p lost the caps needed to stay on @rq's local DSQ? Record reason if so. */ 294 bool scx_task_reenq_on_cap_revoke(struct rq *rq, struct task_struct *p) 295 { 296 u64 missing; 297 298 /* migration-disabled tasks are admitted regardless of caps */ 299 if (is_migration_disabled(p)) 300 return false; 301 302 missing = scx_missing_caps(scx_task_sched(p), cpu_of(rq), scx_caps_for_task(p)); 303 if (likely(!missing)) 304 return false; 305 306 p->scx.reenq_reason_caps = missing; 307 p->scx.reenq_reason_cid = __scx_cpu_to_cid(cpu_of(rq)); 308 return true; 309 } 310 311 /* 312 * Drain @rq->scx.reject_dsq, reenqueueing each task so the BPF re-decides 313 * from p->scx.reenq_reason_*. 314 * 315 * A task can be re-rejected repeatedly, and there's no repeat limit here. 316 * Rejection can't happen for root, and sub-scheds can be safely ejected after 317 * triggering the stall watchdog. 318 */ 319 void scx_reenq_reject(struct rq *rq) 320 { 321 LIST_HEAD(tasks); 322 struct task_struct *p, *n; 323 324 lockdep_assert_rq_held(rq); 325 326 if (!scx_has_subs() || list_empty(&rq->scx.reject_dsq.list)) 327 return; 328 329 /* 330 * Move to a private list so a task re-rejected by the 331 * scx_do_enqueue_task() below isn't revisited this round. 332 */ 333 list_for_each_entry_safe(p, n, &rq->scx.reject_dsq.list, scx.dsq_list.node) { 334 /* migration_pending tasks should have bypassed to local DSQ */ 335 if (WARN_ON_ONCE(p->migration_pending)) 336 continue; 337 338 scx_dispatch_dequeue(rq, p); 339 340 if (WARN_ON_ONCE(p->scx.flags & SCX_TASK_REENQ_REASON_MASK)) 341 p->scx.flags &= ~SCX_TASK_REENQ_REASON_MASK; 342 p->scx.flags |= SCX_TASK_REENQ_CAP; 343 344 list_add_tail(&p->scx.dsq_list.node, &tasks); 345 } 346 347 list_for_each_entry_safe(p, n, &tasks, scx.dsq_list.node) { 348 list_del_init(&p->scx.dsq_list.node); 349 350 scx_do_enqueue_task(rq, p, SCX_ENQ_REENQ, -1); 351 352 p->scx.flags &= ~SCX_TASK_REENQ_REASON_MASK; 353 } 354 } 355 356 /* record a caps change, see struct scx_caps_updated */ 357 static void caps_updated_record(struct scx_pshard *ps, const struct scx_cmask *cids, u64 caps, 358 struct list_head *to_deliver) 359 { 360 struct scx_caps_updated *cu = &ps->caps_updated; 361 362 guard(raw_spinlock)(&cu->lock); 363 scx_cmask_or(&cu->cmask, cids); 364 cu->caps |= caps; 365 if (list_empty(&cu->node_in_flight)) 366 list_add_tail(&cu->node_in_flight, to_deliver); 367 } 368 369 /* deliver queued caps_updated callbacks, see struct scx_caps_updated */ 370 static void caps_updated_deliver(struct list_head *to_deliver) 371 { 372 struct scx_caps_updated *cu, *tmp; 373 374 list_for_each_entry_safe(cu, tmp, to_deliver, node_in_flight) { 375 struct scx_pshard *ps = container_of(cu, struct scx_pshard, caps_updated); 376 struct scx_sched *sch = ps->sch; 377 378 while (true) { 379 u64 caps = 0; 380 381 /* 382 * During enable, has_op is set after ops.sub_attach(), 383 * so !has_op means the op is absent or the sched isn't 384 * live yet - e.g. caps grant from ops.sub_attach(). 385 * Either way don't consume - leave for 386 * scx_sub_seed_caps() to deliver once live. 387 */ 388 scoped_guard (raw_spinlock, &cu->lock) { 389 if (cu->caps && SCX_HAS_OP(sch, sub_caps_updated) && 390 likely(!READ_ONCE(sch->aborting))) { 391 struct scx_cmask_ref ref; 392 393 caps = cu->caps; 394 scx_cmask_ref_init_kern(sch, cu->cmask_arena_out, 395 ps->base, ps->nr_cids, &ref); 396 scx_cmask_ref_copy(&ref, &cu->cmask); 397 scx_cmask_clear(&cu->cmask); 398 cu->caps = 0; 399 } else { 400 list_del_init(&cu->node_in_flight); 401 } 402 } 403 if (!caps) 404 break; 405 406 /* caps != 0 only when deliverable (has_op, above) */ 407 SCX_CALL_OP(sch, sub_caps_updated, NULL, 408 scx_kaddr_to_arena(sch, cu->cmask_arena_out), 409 caps); 410 } 411 } 412 } 413 414 /* 415 * Deliver caps owed to @sch that couldn't be delivered earlier (e.g. a grant 416 * taken during its sub_attach(), before has_op was set). Called once @sch is 417 * enabled. 418 */ 419 static void scx_sub_seed_caps(struct scx_sched *sch) 420 { 421 LIST_HEAD(to_deliver); 422 s32 si; 423 424 guard(irqsave)(); 425 426 for (si = 0; si < sch->nr_pshards; si++) { 427 struct scx_pshard *ps = sch->pshard[si]; 428 struct scx_caps_updated *cu = &ps->caps_updated; 429 430 scoped_guard (raw_spinlock, &cu->lock) { 431 if (cu->caps && list_empty(&cu->node_in_flight)) 432 list_add_tail(&cu->node_in_flight, &to_deliver); 433 } 434 } 435 caps_updated_deliver(&to_deliver); 436 } 437 438 static u64 calc_effective_caps(struct scx_pshard *ps, s32 cid) 439 { 440 u64 ecaps = 0; 441 u32 cap_bit; 442 443 for (cap_bit = 0; cap_bit < __SCX_NR_CAPS; cap_bit++) 444 if (scx_cmask_test(cid, &ps->caps[cap_bit].cmask)) 445 ecaps |= BIT_U64(cap_bit) | scx_caps_implied(BIT_U64(cap_bit)); 446 return ecaps; 447 } 448 449 /** 450 * queue_sync_ecaps - Queue ecaps update for a (sch, cid) pair 451 * @sch: sched to update 452 * @cid: cid to update 453 * 454 * Queue an ecaps update for @sch's @cid and kick the cpu so that it syncs in 455 * balance_one(). 456 */ 457 static void queue_sync_ecaps(struct scx_sched *sch, s32 cid) 458 { 459 s32 cpu = __scx_cid_to_cpu(cid); 460 struct scx_sched_pcpu *pcpu = per_cpu_ptr(sch->pcpu, cpu); 461 462 /* 463 * Pairs with smp_mb() in scx_process_sync_ecaps(). Either the check 464 * below sees the node off the list and queues it, or the in-flight sync 465 * sees the caps[] update made before this call. 466 */ 467 smp_mb(); 468 469 /* @cid's pshard->lock excludes concurrent queueing attempts */ 470 if (llist_on_list(&pcpu->ecaps_to_sync_node)) 471 return; 472 if (llist_add(&pcpu->ecaps_to_sync_node, &cpu_rq(cpu)->scx.ecaps_to_sync)) 473 scx_kick_cpu(scx_root, cpu, 0); 474 } 475 476 /* discard @rq's queued ecaps syncs */ 477 static void discard_queued_syncs(struct rq *rq) 478 { 479 struct llist_node *pos, *tmp; 480 481 lockdep_assert_rq_held(rq); 482 483 llist_for_each_safe(pos, tmp, llist_del_all(&rq->scx.ecaps_to_sync)) 484 init_llist_node(pos); 485 } 486 487 /** 488 * scx_process_sync_ecaps - Sync this cpu's ecaps to pshard->caps[] 489 * @rq: the cid's cpu rq 490 * @prev: @rq's previous task from the in-progress balance 491 * 492 * pshard->caps[] is the target configuration. pcpu->ecaps is the effective 493 * transposed copy owned by the cid's cpu and written only here under @rq's 494 * lock. 495 * 496 * A sched that newly gains baseline access here is owed an update_idle() so it 497 * learns the cid's idle state. Such a gain arms the per-rq 498 * %SCX_RQ_SUB_IDLE_RENOTIFY gate so the next idle pick delivers it. 499 */ 500 void scx_process_sync_ecaps(struct rq *rq, struct task_struct *prev) 501 { 502 s32 cpu = cpu_of(rq); 503 s32 cid, shard; 504 struct llist_node *batch, *pos, *tmp; 505 u64 lost_all = 0; 506 507 lockdep_assert_rq_held(rq); 508 509 if (!scx_has_subs() || likely(llist_empty(&rq->scx.ecaps_to_sync))) 510 return; 511 512 /* 513 * ecaps are zeroed while the cpu is inactive and must stay zero. 514 * Discard queued syncs instead of processing them - the 515 * scx_online_ecaps() reseed re-syncs every sched on activation. 516 * cpu_active() clears before the offline zeroing and sets before the 517 * reseed is queued, so this test can neither miss a racing sync nor 518 * eat the reseed. 519 */ 520 if (unlikely(!cpu_active(cpu))) { 521 discard_queued_syncs(rq); 522 return; 523 } 524 525 /* @cid is valid here: the cpu is active with queued syncs */ 526 cid = __scx_cpu_to_cid(cpu); 527 shard = scx_cid_to_shard[cid]; 528 529 batch = llist_del_all(&rq->scx.ecaps_to_sync); 530 llist_for_each_safe(pos, tmp, batch) { 531 struct scx_sched_pcpu *pcpu = 532 container_of(pos, struct scx_sched_pcpu, ecaps_to_sync_node); 533 struct scx_pshard *ps = pcpu->sch->pshard[shard]; 534 u64 old, ecaps, lost, gained; 535 536 init_llist_node(pos); 537 538 /* pairs with smp_mb() in queue_sync_ecaps(), see there */ 539 smp_mb(); 540 541 old = READ_ONCE(pcpu->ecaps); 542 ecaps = calc_effective_caps(ps, cid); 543 WRITE_ONCE(pcpu->ecaps, ecaps); 544 545 lost = old & ~ecaps; 546 gained = ecaps & ~old; 547 lost_all |= lost; 548 549 /* 550 * Tell the sched its effective caps on this cid changed. The 551 * invocation is equivalent to the dispatch path and may drop 552 * and re-acquire the rq lock temporarily while the rest of 553 * @batch is held privately, see scx_discard_ecaps_to_sync(). 554 */ 555 if (ecaps != pcpu->reported_ecaps && 556 SCX_HAS_OP(pcpu->sch, sub_ecaps_updated) && 557 !scx_bypassing(pcpu->sch, cpu)) { 558 struct scx_dsp_ctx *dspc = &pcpu->dsp_ctx; 559 560 dspc->rq = rq; 561 /* stash @prev so nested dispatches can access it */ 562 rq->scx.sub_dispatch_prev = prev; 563 SCX_CALL_OP(pcpu->sch, sub_ecaps_updated, rq, scx_cpu_arg(cpu), 564 pcpu->reported_ecaps, ecaps); 565 rq->scx.sub_dispatch_prev = NULL; 566 scx_flush_dispatch_buf(pcpu->sch, rq); 567 pcpu->reported_ecaps = ecaps; 568 } 569 570 /* 571 * Gaining baseline access owes an update_idle() so the sched 572 * learns the cpu's idle state. Arm the per-rq gate so the next 573 * idle pick flushes it. Losing access drops any pending notify. 574 */ 575 if (gained & SCX_CAP_BASE) { 576 pcpu->idle_renotify = true; 577 rq->scx.flags |= SCX_RQ_SUB_IDLE_RENOTIFY; 578 } else if (lost & SCX_CAP_BASE) { 579 pcpu->idle_renotify = false; 580 } 581 } 582 583 /* 584 * Losing a cap can strand already-queued tasks. Schedule a reenq scan 585 * to move the now-capless ones off the local DSQ. The scan tests 586 * against the effective caps and thus must come after the ecaps sync. 587 */ 588 if (lost_all & SCX_CAPS_REENQ_ON_LOSS) 589 scx_schedule_reenq_local(rq, SCX_REENQ_CAP_REVOKE); 590 } 591 592 /** 593 * scx_unbypass_replay_ecaps - Replay a bypass-suppressed ecaps notification 594 * @rq: rq of the cpu leaving bypass 595 * @sch: scheduler that just left bypass on @rq's cpu 596 * 597 * scx_process_sync_ecaps() consumes syncs while bypassing without delivering 598 * ops.sub_ecaps_updated(), leaving reported_ecaps stale. Nothing re-queues a 599 * sync when bypass lifts, so without a replay a cid that never changes again 600 * would never be notified. The attach-time initial grants are the acute case 601 * as they are consumed during the enable bypass window. Re-queue a sync for 602 * any undelivered delta so the next balance delivers it. 603 */ 604 void scx_unbypass_replay_ecaps(struct rq *rq, struct scx_sched *sch) 605 { 606 s32 cpu = cpu_of(rq); 607 struct scx_sched_pcpu *pcpu = per_cpu_ptr(sch->pcpu, cpu); 608 struct scx_pshard *ps; 609 s32 cid; 610 611 lockdep_assert_rq_held(rq); 612 613 /* root holds every cap and never uses ecaps */ 614 if (!sch->level) 615 return; 616 617 if (READ_ONCE(pcpu->ecaps) == pcpu->reported_ecaps) 618 return; 619 620 cid = __scx_cpu_to_cid(cpu); 621 ps = sch->pshard[scx_cid_to_shard[cid]]; 622 623 guard(raw_spinlock)(&ps->lock); 624 queue_sync_ecaps(sch, cid); 625 } 626 627 /* 628 * A cpu came back. Re-seed each sub-sched's ecaps on the cpu's cid. The sync 629 * recomputes effective caps from the pshard and fires ops.sub_ecaps_updated() 630 * only on a real change since offline. 631 */ 632 void scx_online_ecaps(struct rq *rq) 633 { 634 s32 cid = __scx_cpu_to_cid(cpu_of(rq)); 635 s32 shard = scx_cid_to_shard[cid]; 636 struct scx_sched *pos; 637 638 guard(rq_lock_irqsave)(rq); 639 640 scx_for_each_descendant_pre(pos, scx_root) { 641 struct scx_pshard *ps; 642 643 /* root holds every cap and never uses ecaps */ 644 if (pos == scx_root) 645 continue; 646 647 ps = pos->pshard[shard]; 648 guard(raw_spinlock)(&ps->lock); 649 queue_sync_ecaps(pos, cid); 650 } 651 } 652 653 /* 654 * A cpu is going down. Zero each sub-sched's in-effect ecaps so cap checks 655 * treat the cpu as capless while offline. Pending and late-queued syncs are 656 * discarded at consumption by scx_process_sync_ecaps() while the cpu is 657 * inactive. Leave reported_ecaps. Ownership is unchanged, so the 658 * scx_online_ecaps() reseed reports only a genuine delta. No callback fires 659 * here. 660 */ 661 void scx_offline_ecaps(struct rq *rq) 662 { 663 s32 cpu = cpu_of(rq); 664 struct scx_sched *pos; 665 666 guard(rq_lock_irqsave)(rq); 667 668 scx_for_each_descendant_pre(pos, scx_root) { 669 /* root holds every cap and never uses ecaps */ 670 if (pos == scx_root) 671 continue; 672 673 WRITE_ONCE(per_cpu_ptr(pos->pcpu, cpu)->ecaps, 0); 674 } 675 } 676 677 /* 678 * @pcpu's sched was unhashed before the grace period, so nothing re-queues its 679 * sync node. Remove the node from @rq's pending list so the pcpu can be freed. 680 */ 681 void scx_discard_ecaps_to_sync(s32 cpu, struct scx_sched_pcpu *pcpu) 682 { 683 struct rq *rq = cpu_rq(cpu); 684 struct llist_node *head = NULL, *tail = NULL; 685 struct llist_node *pos, *tmp; 686 687 /* 688 * llist can't unlink a single node. Take all queued nodes, drop @pcpu's 689 * and resplice the rest. Nodes in the taken batch read as on-list 690 * throughout, so queue_sync_ecaps() stays correct. 691 */ 692 if (llist_on_list(&pcpu->ecaps_to_sync_node)) { 693 scoped_guard (rq_lock_irqsave, rq) { 694 llist_for_each_safe(pos, tmp, llist_del_all(&rq->scx.ecaps_to_sync)) { 695 if (pos == &pcpu->ecaps_to_sync_node) { 696 init_llist_node(pos); 697 } else { 698 pos->next = head; 699 head = pos; 700 if (!tail) 701 tail = pos; 702 } 703 } 704 if (head) 705 llist_add_batch(head, tail, &rq->scx.ecaps_to_sync); 706 } 707 } 708 709 /* 710 * An in-flight scx_process_sync_ecaps() batch may still hold the node 711 * privately across dispatch-induced rq unlocks, reading as on-list. 712 * 713 * Because a bypassing sched gets no op call, init_llist_node() and all 714 * @pcpu accesses share one contiguous lock hold, off-list under the rq 715 * lock means @pcpu won't be accessed again. 716 */ 717 while (true) { 718 scoped_guard (rq_lock_irqsave, rq) { 719 if (!llist_on_list(&pcpu->ecaps_to_sync_node)) 720 return; 721 } 722 cpu_relax(); 723 } 724 } 725 726 /** 727 * scx_discard_stale_ecaps_syncs - Discard ecaps syncs from earlier schedulers 728 * 729 * To be called during root enable before the scheduler goes live. An earlier 730 * root's sub-sched may not have gone through its RCU free path yet (e.g. a 731 * still-open link fd defers it) and can leave queued ecaps syncs behind. 732 * Processing them would decode the dead sched's pshards with the current cid 733 * layout. Discard them instead. The backing scx_sched_pcpu's are still 734 * allocated as the free path removes ecaps_to_sync_node before freeing. 735 */ 736 void scx_discard_stale_ecaps_syncs(void) 737 { 738 s32 cpu; 739 740 for_each_possible_cpu(cpu) { 741 struct rq *rq = cpu_rq(cpu); 742 743 guard(rq_lock_irqsave)(rq); 744 discard_queued_syncs(rq); 745 } 746 } 747 748 static DECLARE_WAIT_QUEUE_HEAD(scx_unlink_waitq); 749 750 void drain_descendants(struct scx_sched *sch) 751 { 752 /* 753 * Child scheds that finished the critical part of disabling will take 754 * themselves off @sch->children. Wait for it to drain. As propagation 755 * is recursive, empty @sch->children means that all proper descendant 756 * scheds reached unlinking stage. 757 */ 758 wait_event(scx_unlink_waitq, list_empty(&sch->children)); 759 } 760 761 static void scx_fail_parent(struct scx_sched *sch, 762 struct task_struct *failed, s32 fail_code) 763 { 764 struct scx_sched *parent = scx_parent(sch); 765 struct scx_task_iter sti; 766 struct task_struct *p; 767 768 scx_error(parent, "ops.init_task() failed (%d) for %s[%d] while disabling a sub-scheduler", 769 fail_code, failed->comm, failed->pid); 770 771 /* 772 * Once $parent is bypassed, it's safe to put SCX_TASK_NONE tasks into 773 * it. This may cause downstream failures on the BPF side but $parent is 774 * dying anyway. 775 */ 776 scx_bypass(parent, true); 777 778 scx_task_iter_start(&sti, sch->cgrp); 779 while ((p = scx_task_iter_next_locked(&sti))) { 780 if (scx_task_on_sched(parent, p)) 781 continue; 782 783 scoped_guard (sched_change, p, DEQUEUE_SAVE | DEQUEUE_MOVE) { 784 scx_disable_and_exit_task(sch, p); 785 scx_set_task_sched(p, parent); 786 } 787 } 788 scx_task_iter_stop(&sti); 789 } 790 791 void scx_sub_disable(struct scx_sched *sch) 792 { 793 struct scx_sched *parent = scx_parent(sch); 794 struct scx_task_iter sti; 795 struct task_struct *p; 796 int ret; 797 798 /* 799 * Guarantee forward progress and wait for descendants to be disabled. 800 * To limit disruptions, $parent is not bypassed. Tasks are fully 801 * prepped and then inserted back into $parent. 802 */ 803 scx_bypass(sch, true); 804 drain_descendants(sch); 805 806 /* 807 * Here, every runnable task is guaranteed to make forward progress and 808 * we can safely use blocking synchronization constructs. Actually 809 * disable ops. 810 */ 811 mutex_lock(&scx_enable_mutex); 812 percpu_down_write(&scx_fork_rwsem); 813 scx_cgroup_lock(); 814 815 /* 816 * An enable that failed before scx_link_sched() never owned a cgroup or 817 * task and won't be waited on by an ancestor's drain_descendants(). 818 * Nothing to reparent and walking the tasks can misbehave as the task 819 * ownership invariant (either owned by self or parent) does not hold. 820 */ 821 if (list_empty(&sch->sibling)) 822 goto dump; 823 824 set_cgroup_sched(sch_cgroup(sch), parent); 825 826 scx_task_iter_start(&sti, sch->cgrp); 827 while ((p = scx_task_iter_next_locked(&sti))) { 828 struct rq *rq; 829 struct rq_flags rf; 830 831 /* filter out duplicate visits */ 832 if (scx_task_on_sched(parent, p)) 833 continue; 834 835 /* 836 * By the time control reaches here, all linked descendant 837 * schedulers should have been disabled. 838 */ 839 WARN_ON_ONCE(!scx_task_on_sched(sch, p)); 840 841 /* 842 * @p is pinned by the iter: css_task_iter_next() takes a 843 * reference and holds it until the next iter_next() call, so 844 * @p->usage is guaranteed > 0. 845 */ 846 get_task_struct(p); 847 848 scx_task_iter_unlock(&sti); 849 850 /* 851 * $p is READY or ENABLED on @sch. Initialize for $parent, 852 * disable and exit from @sch, and then switch over to $parent. 853 * 854 * If a task fails to initialize for $parent, the only available 855 * action is disabling $parent too. While this allows disabling 856 * of a child sched to cause the parent scheduler to fail, the 857 * failure can only originate from ops.init_task() of the 858 * parent. A child can't directly affect the parent through its 859 * own failures. 860 */ 861 ret = __scx_init_task(parent, p, false); 862 if (ret) { 863 scx_fail_parent(sch, p, ret); 864 put_task_struct(p); 865 break; 866 } 867 868 rq = task_rq_lock(p, &rf); 869 870 if (scx_get_task_state(p) == SCX_TASK_DEAD) { 871 /* 872 * sched_ext_dead() raced us between __scx_init_task() 873 * and this rq lock and ran exit_task() on @sch (the 874 * sched @p was on at that point), not on $parent. 875 * $parent's just-completed init is owed an exit_task() 876 * and we issue it here. 877 */ 878 scx_sub_init_cancel_task(parent, p); 879 task_rq_unlock(rq, p, &rf); 880 put_task_struct(p); 881 continue; 882 } 883 884 scoped_guard (sched_change, p, DEQUEUE_SAVE | DEQUEUE_MOVE) { 885 /* 886 * $p is initialized for $parent and still attached to 887 * @sch. Disable and exit for @sch, switch over to 888 * $parent and override the state to READY to account 889 * for $p having already been initialized. 890 */ 891 scx_disable_and_exit_task(sch, p); 892 scx_set_task_state(p, SCX_TASK_INIT_BEGIN); 893 scx_set_task_state(p, SCX_TASK_INIT); 894 scx_set_task_sched(p, parent); 895 scx_set_task_state(p, SCX_TASK_READY); 896 897 /* 898 * A task on a non-ext class, possible under an 899 * %SCX_OPS_SWITCH_PARTIAL root, stays READY and is 900 * enabled by switching_to_scx() if it switches over. 901 */ 902 if (p->sched_class == &ext_sched_class) 903 scx_enable_task(parent, p); 904 } 905 906 task_rq_unlock(rq, p, &rf); 907 put_task_struct(p); 908 } 909 scx_task_iter_stop(&sti); 910 911 dump: 912 scx_disable_dump(sch); 913 914 scx_cgroup_unlock(); 915 percpu_up_write(&scx_fork_rwsem); 916 917 /* 918 * All tasks are moved off of @sch but there may still be on-going 919 * operations (e.g. ops.select_cpu()). Drain them by flushing RCU. Use 920 * the expedited version as ancestors may be waiting in bypass mode. 921 * Also, tell the parent that there is no need to keep running bypass 922 * DSQs for us. 923 */ 924 synchronize_rcu_expedited(); 925 scx_disable_bypass_dsp(sch); 926 927 scx_unlink_sched(sch); 928 929 mutex_unlock(&scx_enable_mutex); 930 931 /* 932 * @sch is now unlinked from the parent's children list. Notify and call 933 * ops.sub_detach/exit(). Note that ops.sub_detach/exit() must be called 934 * after unlinking and releasing all locks. See scx_claim_exit(). 935 */ 936 wake_up_all(&scx_unlink_waitq); 937 938 if (parent->ops.sub_detach && sch->sub_attached) { 939 struct scx_sub_detach_args sub_detach_args = { 940 .ops = &sch->ops, 941 .cgroup_path = sch->cgrp_path, 942 }; 943 SCX_CALL_OP(parent, sub_detach, NULL, 944 &sub_detach_args); 945 } 946 947 scx_log_sched_disable(sch); 948 949 if (sch->ops.exit) 950 SCX_CALL_OP(sch, exit, NULL, sch->exit_info); 951 952 /* 953 * @sch's non-ops programs such as timers and tracers can fire after 954 * ops.exit(). Now that exit is complete, stop scx_prog_sched() from 955 * resolving to @sch and drain in-flight resolvers. 956 */ 957 WRITE_ONCE(sch->dead, true); 958 synchronize_rcu(); 959 960 if (sch->sub_kset) 961 kobject_del(&sch->sub_kset->kobj); 962 /* not added if enable failed before scx_sched_sysfs_add() */ 963 if (sch->kobj.state_in_sysfs) 964 kobject_del(&sch->kobj); 965 } 966 967 /* verify that a scheduler can be attached to @cgrp and return the parent */ 968 static struct scx_sched *find_parent_sched(struct cgroup *cgrp) 969 { 970 struct scx_sched *parent = cgrp->scx_sched; 971 struct scx_sched *pos; 972 973 lockdep_assert_held(&scx_sched_lock); 974 975 /* can't attach twice to the same cgroup */ 976 if (parent->cgrp == cgrp) 977 return ERR_PTR(-EBUSY); 978 979 /* does $parent allow sub-scheds? */ 980 if (!parent->ops.sub_attach) 981 return ERR_PTR(-EOPNOTSUPP); 982 983 /* can't insert between $parent and its exiting children */ 984 list_for_each_entry(pos, &parent->children, sibling) 985 if (cgroup_is_descendant(pos->cgrp, cgrp)) 986 return ERR_PTR(-EBUSY); 987 988 return parent; 989 } 990 991 static bool assert_task_ready_or_enabled(struct task_struct *p) 992 { 993 u32 state = scx_get_task_state(p); 994 995 switch (state) { 996 case SCX_TASK_READY: 997 case SCX_TASK_ENABLED: 998 return true; 999 default: 1000 WARN_ONCE(true, "sched_ext: Invalid task state %d for %s[%d] during enabling sub sched", 1001 state, p->comm, p->pid); 1002 return false; 1003 } 1004 } 1005 1006 void scx_sub_enable_workfn(struct kthread_work *work) 1007 { 1008 struct scx_enable_cmd *cmd = container_of(work, struct scx_enable_cmd, work); 1009 struct sched_ext_ops *ops = cmd->ops; 1010 struct cgroup *cgrp; 1011 struct scx_sched *parent, *sch; 1012 struct scx_task_iter sti; 1013 struct task_struct *p; 1014 s32 i, ret; 1015 1016 mutex_lock(&scx_enable_mutex); 1017 1018 if (!scx_enabled()) { 1019 ret = -ENODEV; 1020 goto out_unlock; 1021 } 1022 1023 /* See scx_root_enable_workfn() for the @ops->priv check. */ 1024 if (rcu_access_pointer(ops->priv)) { 1025 ret = -EBUSY; 1026 goto out_unlock; 1027 } 1028 1029 cgrp = cgroup_get_from_id(ops->sub_cgroup_id); 1030 if (IS_ERR(cgrp)) { 1031 ret = PTR_ERR(cgrp); 1032 goto out_unlock; 1033 } 1034 1035 raw_spin_lock_irq(&scx_sched_lock); 1036 parent = find_parent_sched(cgrp); 1037 if (IS_ERR(parent)) { 1038 raw_spin_unlock_irq(&scx_sched_lock); 1039 ret = PTR_ERR(parent); 1040 goto out_put_cgrp; 1041 } 1042 kobject_get(&parent->kobj); 1043 raw_spin_unlock_irq(&scx_sched_lock); 1044 1045 /* 1046 * Flip the hot-path gates before ops->priv is published - the sub's 1047 * programs can e.g. kick cpus from that point on. The matching dec is 1048 * at the end of scx_sched_free_rcu_work(). 1049 */ 1050 static_branch_inc(&__scx_has_subs); 1051 1052 /* scx_alloc_and_add_sched() consumes @cgrp whether it succeeds or not */ 1053 sch = scx_alloc_and_add_sched(cmd, cgrp, parent); 1054 kobject_put(&parent->kobj); 1055 if (IS_ERR(sch)) { 1056 static_branch_dec(&__scx_has_subs); 1057 ret = PTR_ERR(sch); 1058 goto out_unlock; 1059 } 1060 1061 /* 1062 * Validate before scx_link_sched() publishes @sch, so an invalid sub 1063 * never becomes visible with an unallocated pshard. 1064 */ 1065 ret = scx_validate_ops(sch, ops); 1066 if (ret) 1067 goto err_disable; 1068 1069 /* 1070 * Allocate pshard[] before scx_link_sched() publishes @sch into the 1071 * parent's RCU children list. A concurrent revoke walking the tree 1072 * would otherwise dereference sch->pshard[si] while it's still NULL. 1073 * Unlike the root path, the cid shard layout is stable at this point. 1074 * 1075 * scx_alloc_pshards() skips allocation when @sch's arena pool isn't 1076 * initialized, so scx_arena_pool_init() must run first. 1077 */ 1078 ret = scx_arena_pool_init(sch); 1079 if (ret) 1080 goto err_disable; 1081 1082 ret = scx_alloc_pshards(sch); 1083 if (ret) 1084 goto err_disable; 1085 1086 ret = scx_link_sched(sch); 1087 if (ret) 1088 goto err_disable; 1089 1090 ret = scx_sched_sysfs_add(sch); 1091 if (ret) 1092 goto err_disable; 1093 1094 if (sch->level >= SCX_SUB_MAX_DEPTH) { 1095 scx_error(sch, "max nesting depth %d violated", 1096 SCX_SUB_MAX_DEPTH); 1097 goto err_disable; 1098 } 1099 1100 if (sch->ops.init) { 1101 ret = SCX_CALL_OP_RET(sch, init, NULL); 1102 if (ret) { 1103 ret = scx_ops_sanitize_err(sch, "init", ret); 1104 scx_error(sch, "ops.init() failed (%d)", ret); 1105 goto err_disable; 1106 } 1107 sch->exit_info->flags |= SCX_EFLAG_INITIALIZED; 1108 } 1109 1110 ret = scx_set_cmask_scratch_alloc(sch); 1111 if (ret) 1112 goto err_disable; 1113 1114 struct scx_sub_attach_args sub_attach_args = { 1115 .ops = &sch->ops, 1116 .cgroup_path = sch->cgrp_path, 1117 }; 1118 1119 ret = SCX_CALL_OP_RET(parent, sub_attach, NULL, 1120 &sub_attach_args); 1121 if (ret) { 1122 ret = scx_ops_sanitize_err(sch, "sub_attach", ret); 1123 scx_error(sch, "parent rejected (%d)", ret); 1124 goto err_disable; 1125 } 1126 sch->sub_attached = true; 1127 1128 scx_bypass(sch, true); 1129 1130 for (i = SCX_OPI_BEGIN; i < SCX_OPI_END; i++) 1131 if (((void (**)(void))ops)[i]) 1132 set_bit(i, sch->has_op); 1133 1134 percpu_down_write(&scx_fork_rwsem); 1135 scx_cgroup_lock(); 1136 1137 /* 1138 * Set cgroup->scx_sched's and check CSS_ONLINE. Either we see 1139 * !CSS_ONLINE or scx_cgroup_lifetime_notify() sees and shoots us down. 1140 */ 1141 set_cgroup_sched(sch_cgroup(sch), sch); 1142 if (!(cgrp->self.flags & CSS_ONLINE)) { 1143 scx_error(sch, "cgroup is not online"); 1144 goto err_unlock_and_disable; 1145 } 1146 1147 /* 1148 * Initialize tasks for the new child $sch without exiting them for 1149 * $parent so that the tasks can always be reverted back to $parent 1150 * sched on child init failure. 1151 */ 1152 WARN_ON_ONCE(scx_enabling_sub_sched); 1153 scx_enabling_sub_sched = sch; 1154 1155 scx_task_iter_start(&sti, sch->cgrp); 1156 while ((p = scx_task_iter_next_locked(&sti))) { 1157 struct rq *rq; 1158 struct rq_flags rf; 1159 1160 /* 1161 * Task iteration may visit the same task twice when racing 1162 * against exiting. Use %SCX_TASK_SUB_INIT to mark tasks which 1163 * finished __scx_init_task() and skip if set. 1164 * 1165 * A task may exit and get freed between __scx_init_task() 1166 * completion and scx_enable_task(). In such cases, 1167 * scx_disable_and_exit_task() must exit the task for both the 1168 * parent and child scheds. 1169 */ 1170 if (p->scx.flags & SCX_TASK_SUB_INIT) 1171 continue; 1172 1173 /* @p is pinned by the iter; see scx_sub_disable() */ 1174 get_task_struct(p); 1175 1176 if (!assert_task_ready_or_enabled(p)) { 1177 ret = -EINVAL; 1178 goto abort; 1179 } 1180 1181 scx_task_iter_unlock(&sti); 1182 1183 /* 1184 * As $p is still on $parent, it can't be transitioned to INIT. 1185 * Let's worry about task state later. Use __scx_init_task(). 1186 */ 1187 ret = __scx_init_task(sch, p, false); 1188 if (ret) 1189 goto abort; 1190 1191 rq = task_rq_lock(p, &rf); 1192 1193 if (scx_get_task_state(p) == SCX_TASK_DEAD) { 1194 /* 1195 * sched_ext_dead() raced us between __scx_init_task() 1196 * and this rq lock and ran exit_task() on $parent (the 1197 * sched @p was on at that point), not on @sch. @sch's 1198 * just-completed init is owed an exit_task() and we 1199 * issue it here. 1200 */ 1201 scx_sub_init_cancel_task(sch, p); 1202 task_rq_unlock(rq, p, &rf); 1203 put_task_struct(p); 1204 continue; 1205 } 1206 1207 p->scx.flags |= SCX_TASK_SUB_INIT; 1208 task_rq_unlock(rq, p, &rf); 1209 1210 put_task_struct(p); 1211 } 1212 scx_task_iter_stop(&sti); 1213 1214 /* 1215 * All tasks are prepped. Disable/exit tasks for $parent and enable for 1216 * the new @sch. 1217 */ 1218 scx_task_iter_start(&sti, sch->cgrp); 1219 while ((p = scx_task_iter_next_locked(&sti))) { 1220 /* 1221 * Use clearing of %SCX_TASK_SUB_INIT to detect and skip 1222 * duplicate iterations. 1223 */ 1224 if (!(p->scx.flags & SCX_TASK_SUB_INIT)) 1225 continue; 1226 1227 scoped_guard (sched_change, p, DEQUEUE_SAVE | DEQUEUE_MOVE) { 1228 /* 1229 * $p must be either READY or ENABLED. If ENABLED, 1230 * __scx_disabled_and_exit_task() first disables and 1231 * makes it READY. However, after exiting $p, it will 1232 * leave $p as READY. 1233 */ 1234 assert_task_ready_or_enabled(p); 1235 __scx_disable_and_exit_task(parent, p); 1236 1237 /* 1238 * $p is now only initialized for @sch and READY, which 1239 * is what we want. Assign it to @sch and, if it's on 1240 * the ext class, enable. A non-ext task, possible under 1241 * an %SCX_OPS_SWITCH_PARTIAL root, stays READY and is 1242 * enabled by switching_to_scx() if it switches over. 1243 */ 1244 scx_set_task_sched(p, sch); 1245 if (p->sched_class == &ext_sched_class) 1246 scx_enable_task(sch, p); 1247 1248 p->scx.flags &= ~SCX_TASK_SUB_INIT; 1249 } 1250 } 1251 scx_task_iter_stop(&sti); 1252 1253 scx_enabling_sub_sched = NULL; 1254 1255 scx_cgroup_unlock(); 1256 percpu_up_write(&scx_fork_rwsem); 1257 1258 scx_bypass(sch, false); 1259 1260 /* @sch is enabled; deliver any caps owed since its sub_attach() */ 1261 scx_sub_seed_caps(sch); 1262 1263 pr_info("sched_ext: BPF sub-scheduler \"%s\" enabled\n", sch->ops.name); 1264 kobject_uevent(&sch->kobj, KOBJ_ADD); 1265 ret = 0; 1266 goto out_unlock; 1267 1268 out_put_cgrp: 1269 cgroup_put(cgrp); 1270 out_unlock: 1271 mutex_unlock(&scx_enable_mutex); 1272 cmd->ret = ret; 1273 return; 1274 1275 abort: 1276 put_task_struct(p); 1277 scx_task_iter_stop(&sti); 1278 1279 /* 1280 * Undo __scx_init_task() for tasks we marked. scx_enable_task() never 1281 * ran for @sch on them, so calling scx_disable_task() here would invoke 1282 * ops.disable() without a matching ops.enable(). scx_enabling_sub_sched 1283 * must stay set until SUB_INIT is cleared from every marked task - 1284 * scx_disable_and_exit_task() reads it when a task exits concurrently. 1285 */ 1286 scx_task_iter_start(&sti, sch->cgrp); 1287 while ((p = scx_task_iter_next_locked(&sti))) { 1288 if (p->scx.flags & SCX_TASK_SUB_INIT) { 1289 scx_sub_init_cancel_task(sch, p); 1290 p->scx.flags &= ~SCX_TASK_SUB_INIT; 1291 } 1292 } 1293 scx_task_iter_stop(&sti); 1294 scx_enabling_sub_sched = NULL; 1295 err_unlock_and_disable: 1296 /* we'll soon enter disable path, keep bypass on */ 1297 scx_cgroup_unlock(); 1298 percpu_up_write(&scx_fork_rwsem); 1299 err_disable: 1300 mutex_unlock(&scx_enable_mutex); 1301 /* 1302 * Some enable failures only return an errno (e.g. -ENOMEM from an 1303 * allocation) without calling scx_error(). Record it so 1304 * scx_flush_disable_work() runs the disable and ops.exit() fires. 1305 */ 1306 scx_error(sch, "scx_sub_enable() failed (%d)", ret); 1307 scx_flush_disable_work(sch); 1308 cmd->ret = 0; 1309 } 1310 1311 static s32 scx_cgroup_lifetime_notify(struct notifier_block *nb, 1312 unsigned long action, void *data) 1313 { 1314 struct cgroup *cgrp = data; 1315 struct cgroup *parent = cgroup_parent(cgrp); 1316 1317 if (!cgroup_on_dfl(cgrp)) 1318 return NOTIFY_OK; 1319 1320 switch (action) { 1321 case CGROUP_LIFETIME_ONLINE: 1322 /* inherit ->scx_sched from $parent */ 1323 if (parent) 1324 rcu_assign_pointer(cgrp->scx_sched, parent->scx_sched); 1325 break; 1326 case CGROUP_LIFETIME_OFFLINE: 1327 /* if there is a sched attached, shoot it down */ 1328 if (cgrp->scx_sched && cgrp->scx_sched->cgrp == cgrp) 1329 scx_exit(cgrp->scx_sched, SCX_EXIT_UNREG_KERN, 1330 SCX_ECODE_RSN_CGROUP_OFFLINE, 1331 "cgroup %llu going offline", cgroup_id(cgrp)); 1332 break; 1333 } 1334 1335 return NOTIFY_OK; 1336 } 1337 1338 static struct notifier_block scx_cgroup_lifetime_nb = { 1339 .notifier_call = scx_cgroup_lifetime_notify, 1340 }; 1341 1342 static s32 __init scx_cgroup_lifetime_notifier_init(void) 1343 { 1344 return blocking_notifier_chain_register(&cgroup_lifetime_notifier, 1345 &scx_cgroup_lifetime_nb); 1346 } 1347 core_initcall(scx_cgroup_lifetime_notifier_init); 1348 1349 static void scx_pstack_recursion(struct bpf_prog *prog, const char *op) 1350 { 1351 struct scx_sched *sch; 1352 1353 guard(rcu)(); 1354 sch = scx_prog_sched(prog->aux); 1355 if (unlikely(!sch)) 1356 return; 1357 1358 scx_error(sch, "%s recursion detected", op); 1359 } 1360 1361 void scx_pstack_recursion_on_dispatch(struct bpf_prog *prog) 1362 { 1363 scx_pstack_recursion(prog, "dispatch"); 1364 } 1365 1366 void scx_pstack_recursion_on_caps_updated(struct bpf_prog *prog) 1367 { 1368 scx_pstack_recursion(prog, "sub_caps_updated"); 1369 } 1370 1371 __bpf_kfunc_start_defs(); 1372 1373 /** 1374 * scx_bpf_sub_dispatch - Trigger dispatching on a child scheduler 1375 * @cgroup_id: cgroup ID of the child scheduler to dispatch 1376 * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs 1377 * 1378 * Allows a parent scheduler to trigger dispatching on one of its direct 1379 * child schedulers. The child scheduler runs its dispatch operation to 1380 * move tasks from dispatch queues to the local runqueue. 1381 * 1382 * Returns: true on success, false if cgroup_id is invalid, not a direct 1383 * child, or caller lacks dispatch permission. 1384 */ 1385 __bpf_kfunc bool scx_bpf_sub_dispatch(u64 cgroup_id, const struct bpf_prog_aux *aux) 1386 { 1387 struct rq *this_rq = this_rq(); 1388 struct scx_sched *parent, *child; 1389 1390 guard(rcu)(); 1391 parent = scx_prog_sched(aux); 1392 if (unlikely(!parent)) 1393 return false; 1394 1395 child = scx_find_sub_sched(cgroup_id); 1396 1397 if (unlikely(!child)) 1398 return false; 1399 1400 if (unlikely(scx_parent(child) != parent)) { 1401 scx_error(parent, "trying to dispatch a distant sub-sched on cgroup %llu", 1402 cgroup_id); 1403 return false; 1404 } 1405 1406 /* 1407 * Skip a child that does not effectively hold the base cap on this cpu: 1408 * its inserts would only be rejected. ecaps are synced at the top of 1409 * balance_one() before dispatch, so this reflects the in-effect state. 1410 */ 1411 if (scx_missing_caps(child, cpu_of(this_rq), SCX_CAP_BASE)) 1412 return false; 1413 1414 return scx_dispatch_sched(child, this_rq, this_rq->scx.sub_dispatch_prev, 1415 true); 1416 } 1417 1418 /* Validate common inputs. On success, *parent_out and *child_out are set. */ 1419 static s32 sub_cap_preamble(u64 cgroup_id, u64 caps, const struct bpf_prog_aux *aux, 1420 struct scx_sched **parent_out, struct scx_sched **child_out) 1421 { 1422 struct scx_sched *parent, *child; 1423 1424 parent = scx_prog_sched(aux); 1425 if (unlikely(!parent)) 1426 return -ENODEV; 1427 1428 if (!scx_is_cid_type()) { 1429 scx_error(parent, "sub-cap kfuncs require a cid-form scheduler"); 1430 return -EOPNOTSUPP; 1431 } 1432 1433 child = scx_find_sub_sched(cgroup_id); 1434 if (unlikely(!child)) 1435 return -ENODEV; 1436 1437 if (unlikely(scx_parent(child) != parent)) { 1438 scx_error(parent, "%s: sub-%llu is not a direct child", 1439 parent->cgrp_path, cgroup_id); 1440 return -EINVAL; 1441 } 1442 1443 if (unlikely(caps & ~__SCX_CAP_ALL)) { 1444 scx_error(parent, "invalid caps 0x%llx", caps); 1445 return -EINVAL; 1446 } 1447 1448 *parent_out = parent; 1449 *child_out = child; 1450 return 0; 1451 } 1452 1453 /** 1454 * scx_bpf_sub_grant - Grant @caps on @cmask__ign's cids to a direct child 1455 * @cgroup_id: cgroup id of the direct child sub-sched 1456 * @caps: bitmask of SCX_CAP_* to grant 1457 * @cmask__ign: cid cmask to grant @caps on (arena pointer) 1458 * @denied_out__ign: optional arena cmask accumulating refused cids 1459 * @aux: implicit BPF argument 1460 * 1461 * A cid in @cmask__ign is granted to the child only if the parent holds every 1462 * requested cap on it. Refused cids are OR'd into @denied_out__ign when 1463 * provided. Refusals outside @denied_out__ign's range are not recorded. 1464 * 1465 * All-or-nothing keeps the caller-visible result binary per cid, so 1466 * @denied_out__ign is one mask to interpret rather than a per-cap matrix. 1467 * 1468 * Return 0 on full success, -EPERM if any cid was refused, or a negative 1469 * errno on other failures. 1470 */ 1471 __bpf_kfunc s32 scx_bpf_sub_grant(u64 cgroup_id, u64 caps, 1472 const struct scx_cmask *cmask__ign, 1473 struct scx_cmask *denied_out__ign, 1474 const struct bpf_prog_aux *aux) 1475 { 1476 struct scx_cmask_ref ref, denied_ref; 1477 struct scx_sched *parent, *child; 1478 bool any_denied = false; 1479 LIST_HEAD(to_deliver); 1480 s32 si, ret; 1481 1482 guard(irqsave)(); 1483 1484 ret = sub_cap_preamble(cgroup_id, caps, aux, &parent, &child); 1485 if (ret) 1486 return ret; 1487 1488 ret = scx_cmask_ref_init(parent, cmask__ign, &ref); 1489 if (ret) { 1490 scx_error(parent, "invalid cmask (%d)", ret); 1491 return ret; 1492 } 1493 1494 if (denied_out__ign) { 1495 ret = scx_cmask_ref_init(parent, denied_out__ign, &denied_ref); 1496 if (ret) { 1497 scx_error(parent, "invalid denied_out (%d)", ret); 1498 return ret; 1499 } 1500 } 1501 1502 /* apply the grant one shard at a time */ 1503 for (si = ref.shard_first; si < ref.shard_end; si++) { 1504 SCX_CMASK_DEFINE_SHARD(slice, 0, SCX_CID_SHARD_MAX_CPUS); 1505 struct scx_pshard *pps = parent->pshard[si]; 1506 struct scx_pshard *cps = child->pshard[si]; 1507 u64 granted_caps = 0; 1508 u32 cap_bit; 1509 1510 scx_cmask_ref_shard(&ref, si, slice); 1511 if (scx_cmask_empty(slice)) 1512 continue; 1513 1514 SCX_CMASK_DEFINE_SHARD(granted_cids, slice->base, slice->nr_cids); 1515 SCX_CMASK_DEFINE_SHARD(changed_cids, slice->base, slice->nr_cids); 1516 SCX_CMASK_DEFINE_SHARD(delta, slice->base, slice->nr_cids); 1517 1518 scx_cmask_copy(granted_cids, slice); 1519 1520 scoped_guard (raw_spinlock, &pps->lock) { 1521 guard(raw_spinlock_nested)(&cps->lock); 1522 1523 /* 1524 * Narrow granted_cids to cids the parent holds every 1525 * requested cap on. All-or-nothing per cid. 1526 */ 1527 scx_for_each_cap_bit(cap_bit, caps) 1528 scx_cmask_and(granted_cids, &pps->caps[cap_bit].cmask); 1529 1530 /* 1531 * For each requested cap, fold the newly-set cids into 1532 * the child and accumulate the delta. 1533 */ 1534 scx_for_each_cap_bit(cap_bit, caps) { 1535 struct scx_cmask *ccm = &cps->caps[cap_bit].cmask; 1536 1537 scx_cmask_copy(delta, granted_cids); 1538 scx_cmask_andnot(delta, ccm); 1539 if (scx_cmask_empty(delta)) 1540 continue; 1541 1542 scx_cmask_or(ccm, delta); 1543 scx_cmask_or(changed_cids, delta); 1544 granted_caps |= BIT_U64(cap_bit); 1545 } 1546 1547 if (granted_caps) { 1548 s32 cid; 1549 1550 caps_updated_record(cps, changed_cids, granted_caps, 1551 &to_deliver); 1552 /* 1553 * The sync arms an update_idle() re-notify if 1554 * the cid gains baseline access, so the holder 1555 * learns of an already-idle cid. 1556 */ 1557 scx_cmask_for_each_cid(cid, changed_cids) 1558 queue_sync_ecaps(child, cid); 1559 } 1560 } 1561 1562 /* record cids that didn't make it through into @denied_out */ 1563 if (!scx_cmask_subset(slice, granted_cids)) { 1564 any_denied = true; 1565 if (denied_out__ign) { 1566 SCX_CMASK_DEFINE_SHARD(denied, slice->base, slice->nr_cids); 1567 1568 scx_cmask_copy(denied, slice); 1569 scx_cmask_andnot(denied, granted_cids); 1570 scx_cmask_ref_or(&denied_ref, denied); 1571 } 1572 } 1573 } 1574 1575 caps_updated_deliver(&to_deliver); 1576 1577 return any_denied ? -EPERM : 0; 1578 } 1579 1580 /** 1581 * scx_bpf_sub_revoke - Revoke @caps on @cmask__ign's cids from @child 1582 * @cgroup_id: cgroup id of the direct child sub-sched 1583 * @caps: bitmask of SCX_CAP_* to revoke 1584 * @cmask__ign: cid cmask to revoke @caps on (arena pointer) 1585 * @aux: implicit BPF argument 1586 * 1587 * Clear @caps bits on @cmask__ign from the child named by @cgroup_id and all 1588 * its descendants. The origin parent's pshard lock is held across the subtree 1589 * walk so a concurrent grant from the origin parent observes the revoked 1590 * state. 1591 */ 1592 __bpf_kfunc void scx_bpf_sub_revoke(u64 cgroup_id, u64 caps, 1593 const struct scx_cmask *cmask__ign, 1594 const struct bpf_prog_aux *aux) 1595 { 1596 struct scx_cmask_ref ref; 1597 struct scx_sched *parent, *child, *pos; 1598 LIST_HEAD(to_deliver); 1599 s32 si, ret; 1600 1601 guard(irqsave)(); 1602 1603 if (sub_cap_preamble(cgroup_id, caps, aux, &parent, &child)) 1604 return; 1605 1606 ret = scx_cmask_ref_init(parent, cmask__ign, &ref); 1607 if (ret) { 1608 scx_error(parent, "invalid cmask (%d)", ret); 1609 return; 1610 } 1611 1612 /* per-shard, walk child's subtree and clear @caps */ 1613 for (si = ref.shard_first; si < ref.shard_end; si++) { 1614 SCX_CMASK_DEFINE_SHARD(slice, 0, SCX_CID_SHARD_MAX_CPUS); 1615 1616 scx_cmask_ref_shard(&ref, si, slice); 1617 if (scx_cmask_empty(slice)) 1618 continue; 1619 1620 /* 1621 * Pre-order with subtree skip: a descendant that cleared 1622 * nothing means no descendant of it can hold @caps on these 1623 * cids either. 1624 */ 1625 guard(raw_spinlock)(&parent->pshard[si]->lock); 1626 pos = scx_next_descendant_pre(NULL, child); 1627 while (pos) { 1628 struct scx_pshard *ps = pos->pshard[si]; 1629 SCX_CMASK_DEFINE_SHARD(changed_cids, slice->base, slice->nr_cids); 1630 SCX_CMASK_DEFINE_SHARD(delta, slice->base, slice->nr_cids); 1631 u64 revoked_caps = 0; 1632 u32 cap_bit; 1633 1634 scoped_guard (raw_spinlock_nested, &ps->lock) { 1635 /* 1636 * For each cap, clear lost cids and accumulate 1637 * the per-cap diff for notification. 1638 */ 1639 scx_for_each_cap_bit(cap_bit, caps) { 1640 struct scx_cmask *cm = &ps->caps[cap_bit].cmask; 1641 1642 scx_cmask_copy(delta, cm); 1643 scx_cmask_and(delta, slice); 1644 if (scx_cmask_empty(delta)) 1645 continue; 1646 1647 scx_cmask_andnot(cm, delta); 1648 scx_cmask_or(changed_cids, delta); 1649 revoked_caps |= BIT_U64(cap_bit); 1650 } 1651 1652 if (revoked_caps) { 1653 s32 cid; 1654 1655 caps_updated_record(ps, changed_cids, revoked_caps, 1656 &to_deliver); 1657 scx_cmask_for_each_cid(cid, changed_cids) 1658 queue_sync_ecaps(pos, cid); 1659 } 1660 } 1661 1662 if (revoked_caps) 1663 pos = scx_next_descendant_pre(pos, child); 1664 else 1665 pos = scx_skip_subtree_pre(pos, child); 1666 } 1667 } 1668 1669 caps_updated_deliver(&to_deliver); 1670 } 1671 1672 /** 1673 * scx_bpf_sub_caps - Read self's or a direct child's cap cmasks 1674 * @cgroup_id: 0 for self, or a direct child's cgroup id 1675 * @caps: one or more SCX_CAP_* bits 1676 * @out__ign: arena cmask to receive the union of @caps within its range 1677 * @aux: implicit BPF argument 1678 * 1679 * Read the cap cmasks granted on each cid for self (@cgroup_id 0) or a direct 1680 * child - the literal granted set. A sched can read only itself or a direct 1681 * child. 1682 * 1683 * Return 0, -ENODEV if @cgroup_id names no direct child, or -EINVAL on bad 1684 * inputs. 1685 */ 1686 __bpf_kfunc s32 scx_bpf_sub_caps(u64 cgroup_id, u64 caps, struct scx_cmask *out__ign, 1687 const struct bpf_prog_aux *aux) 1688 { 1689 struct scx_cmask_ref ref; 1690 struct scx_sched *sch, *target; 1691 struct scx_pshard **pshard; 1692 s32 si, ret; 1693 1694 guard(irqsave)(); 1695 1696 sch = scx_prog_sched(aux); 1697 if (unlikely(!sch)) 1698 return -ENODEV; 1699 1700 if (!scx_is_cid_type()) { 1701 scx_error(sch, "sub-cap kfuncs require a cid-form scheduler"); 1702 return -EOPNOTSUPP; 1703 } 1704 1705 if (unlikely(caps & ~__SCX_CAP_ALL)) { 1706 scx_error(sch, "invalid caps 0x%llx", caps); 1707 return -EINVAL; 1708 } 1709 1710 /* @cgroup_id 0 reads self, otherwise a direct child */ 1711 if (cgroup_id) { 1712 target = scx_find_sub_sched(cgroup_id); 1713 if (unlikely(!target)) 1714 return -ENODEV; 1715 if (unlikely(scx_parent(target) != sch)) { 1716 scx_error(sch, "%s: sub-%llu is not a direct child", 1717 sch->cgrp_path, cgroup_id); 1718 return -EINVAL; 1719 } 1720 } else { 1721 target = sch; 1722 } 1723 1724 /* 1725 * The target's caps storage may not be set up yet (e.g. a self-read 1726 * during ops.init_cids()). Pairs with the publish in 1727 * scx_alloc_pshards(): a non-NULL pshard has every element set. 1728 */ 1729 pshard = READ_ONCE(target->pshard); 1730 if (unlikely(!pshard)) { 1731 scx_error(sch, "scx_bpf_sub_caps() called before caps storage is initialized"); 1732 return -ENODEV; 1733 } 1734 1735 ret = scx_cmask_ref_init(sch, out__ign, &ref); 1736 if (ret) { 1737 scx_error(sch, "invalid out (%d)", ret); 1738 return ret; 1739 } 1740 1741 for (si = ref.shard_first; si < ref.shard_end; si++) { 1742 const struct scx_cid_shard *shard = &scx_cid_shard_ranges[si]; 1743 SCX_CMASK_DEFINE_SHARD(local_out, shard->base_cid, shard->nr_cids); 1744 u32 cap_bit; 1745 1746 scx_for_each_cap_bit(cap_bit, caps) 1747 scx_cmask_or(local_out, &pshard[si]->caps[cap_bit].cmask); 1748 scx_cmask_ref_copy(&ref, local_out); 1749 } 1750 return 0; 1751 } 1752 1753 /** 1754 * scx_bpf_sub_kill_bstr - Kill a direct child sub-scheduler 1755 * @cgroup_id: cgroup id of the direct child to kill 1756 * @fmt: reason message format string 1757 * @data: format string parameters packaged using ___bpf_fill() macro 1758 * @data__sz: @data len, must end in '__sz' for the verifier 1759 * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs 1760 * 1761 * Evict a direct child sub-scheduler, disabling it with the supplied reason. 1762 * The child and its subtree are torn down asynchronously through the usual 1763 * disable path. 1764 * 1765 * Unlike scx_bpf_exit(), no exit code is taken: the child is a separate 1766 * scheduler with its own exit-code semantics, so a code chosen by the parent 1767 * would have no defined meaning. The reason string carries the intent. 1768 * 1769 * Return 0 on success or -ENODEV if @cgroup_id names no sub-scheduler, which 1770 * can race with the child detaching on its own and so is not a scheduler error. 1771 * Naming a sched that exists but is not a direct child aborts the parent. 1772 */ 1773 __printf(2, 0) 1774 __bpf_kfunc s32 scx_bpf_sub_kill_bstr(u64 cgroup_id, char *fmt, 1775 unsigned long long *data, u32 data__sz, 1776 const struct bpf_prog_aux *aux) 1777 { 1778 struct scx_sched *parent, *child; 1779 s32 ret; 1780 1781 guard(rcu)(); 1782 1783 parent = scx_prog_sched(aux); 1784 if (unlikely(!parent)) 1785 return -ENODEV; 1786 1787 if (!scx_is_cid_type()) { 1788 scx_error(parent, "sub-cap kfuncs require a cid-form scheduler"); 1789 return -EOPNOTSUPP; 1790 } 1791 1792 child = scx_find_sub_sched(cgroup_id); 1793 if (unlikely(!child)) 1794 return -ENODEV; 1795 1796 if (unlikely(scx_parent(child) != parent)) { 1797 scx_error(parent, "%s: sub-%llu is not a direct child", 1798 parent->cgrp_path, cgroup_id); 1799 return -EINVAL; 1800 } 1801 1802 guard(raw_spinlock_irqsave)(&scx_exit_bstr_buf_lock); 1803 ret = scx_bstr_format(parent, &scx_exit_bstr_buf, fmt, data, data__sz); 1804 if (ret < 0) 1805 return ret; 1806 scx_exit(child, SCX_EXIT_PARENT_KILL, 0, "%s", scx_exit_bstr_buf.line); 1807 return 0; 1808 } 1809 1810 __bpf_kfunc_end_defs(); 1811 1812 #endif /* CONFIG_EXT_SUB_SCHED */ 1813