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 = 142 &rcu_dereference_protected(scx_cid_shard_ranges, 143 lockdep_is_held(&scx_enable_mutex))[shard_idx]; 144 size_t cmask_size = struct_size_t(struct scx_cmask, bits, 145 SCX_CMASK_NR_WORDS(shard->nr_cids)); 146 struct scx_pshard *pshard; 147 struct scx_caps_updated *cu; 148 s32 i; 149 150 pshard = kzalloc_node(sizeof(*pshard), GFP_KERNEL, node); 151 if (!pshard) 152 return NULL; 153 154 raw_spin_lock_init(&pshard->lock); 155 pshard->sch = sch; 156 pshard->base = shard->base_cid; 157 pshard->nr_cids = shard->nr_cids; 158 159 for (i = 0; i < __SCX_NR_CAPS; i++) 160 scx_cmask_init(&pshard->caps[i].cmask, shard->base_cid, shard->nr_cids); 161 162 cu = &pshard->caps_updated; 163 raw_spin_lock_init(&cu->lock); 164 INIT_LIST_HEAD(&cu->node_in_flight); 165 __scx_cmask_init(&cu->cmask, shard->base_cid, shard->nr_cids, SCX_CID_SHARD_MAX_CPUS); 166 167 cu->cmask_arena_out = scx_arena_alloc(sch, cmask_size); 168 if (!cu->cmask_arena_out) { 169 free_pshard(pshard); 170 return NULL; 171 } 172 173 scx_cmask_init(cu->cmask_arena_out, shard->base_cid, shard->nr_cids); 174 175 return pshard; 176 } 177 178 s32 scx_alloc_pshards(struct scx_sched *sch) 179 { 180 struct scx_pshard **pshard; 181 s32 *shard_node; 182 s32 si; 183 184 if (!sch->is_cid_type || !sch->arena_pool) 185 return 0; 186 187 shard_node = rcu_dereference_protected(scx_shard_node, 188 lockdep_is_held(&scx_enable_mutex)); 189 190 pshard = kzalloc_objs(pshard[0], scx_nr_cid_shards, GFP_KERNEL); 191 if (!pshard) 192 return -ENOMEM; 193 194 for (si = 0; si < scx_nr_cid_shards; si++) { 195 pshard[si] = alloc_pshard(sch, si, shard_node[si]); 196 if (!pshard[si]) { 197 while (--si >= 0) 198 free_pshard(pshard[si]); 199 kfree(pshard); 200 return -ENOMEM; 201 } 202 } 203 204 sch->nr_pshards = scx_nr_cid_shards; 205 /* 206 * Publish only after every entry is built so a reader observing 207 * @sch->pshard never sees a partially-filled array or unpublished cid 208 * tables. Pair the store with a barrier and an acquire load on the 209 * read side. 210 */ 211 smp_wmb(); 212 WRITE_ONCE(sch->pshard, pshard); 213 return 0; 214 } 215 216 /* 217 * Seed the root's caps fully. Root owns all cids on all caps at enable time. 218 * Children acquire caps via scx_bpf_sub_grant(). 219 */ 220 void scx_init_root_caps(struct scx_sched *sch) 221 { 222 s32 si, i; 223 224 for (si = 0; si < sch->nr_pshards; si++) { 225 struct scx_pshard *ps = sch->pshard[si]; 226 227 for (i = 0; i < __SCX_NR_CAPS; i++) 228 scx_cmask_fill(&ps->caps[i].cmask); 229 } 230 } 231 232 /** 233 * scx_local_or_reject_dsq - Pick the local or reject DSQ for an insert 234 * @sch: enqueuing sub-sched 235 * @rq: rq whose local DSQ @p targets 236 * @p: task being inserted 237 * @enq_flags: in/out, unhonored flags are cleared 238 * 239 * Return @rq's local DSQ if @sch holds the required caps on @rq's cid, 240 * otherwise @rq's reject DSQ after recording the reenq reason on @p. 241 * 242 * %SCX_ENQ_IMMED and %SCX_ENQ_PREEMPT are cleared when diverting to reject. 243 * %SCX_ENQ_PREEMPT is also cleared on a fallback migration-disabled admission. 244 * 245 * Bypass doesn't need special-casing as a bypassing sched's tasks are enqueued 246 * to and run by its nearest non-bypassing ancestor. If root is bypassing, it 247 * always holds all caps. 248 */ 249 struct scx_dispatch_q *scx_local_or_reject_dsq(struct scx_sched *sch, struct rq *rq, 250 struct task_struct *p, u64 *enq_flags) 251 { 252 if (!scx_has_subs()) 253 return &rq->scx.local_dsq; 254 255 s32 cid = __scx_cpu_to_cid(cpu_of(rq)); 256 struct scx_sched *asch = rq->scx.remote_activate_sch ?: sch; 257 u64 needed = scx_caps_for_enq(*enq_flags); 258 u64 missing; 259 260 /* 261 * On a remote activation the scheduling sched (@asch) differs from 262 * @p's owner (@sch). Check caps against the scheduling sched. 263 */ 264 if (*enq_flags & SCX_ENQ_PREEMPT) 265 needed |= scx_caps_for_preempt(asch, rq); 266 missing = scx_missing_caps(asch, cpu_of(rq), needed); 267 268 /* requirements met */ 269 if (likely(!missing)) 270 return &rq->scx.local_dsq; 271 272 /* 273 * The task must run on this CPU regardless of caps: the rq is draining 274 * offline (BPF scheduler bypassed), the task is migration-disabled, or a 275 * migration is pending. Admit despite the missing caps and count it. 276 * Refuse preemptions. 277 */ 278 if (unlikely(!scx_rq_online(rq) || is_migration_disabled(p) || 279 p->migration_pending)) { 280 __scx_add_event(sch, SCX_EV_SUB_FORCED_ADMIT, 1); 281 *enq_flags &= ~SCX_ENQ_PREEMPT; 282 return &rq->scx.local_dsq; 283 } 284 285 p->scx.reenq_reason_caps = missing; 286 p->scx.reenq_reason_cid = cid; 287 288 /* 289 * Only local DSQ can honor IMMED and dsq_inc_nr() WARNs on IMMED into 290 * others. Strip both the enq flag and the sticky task flag - the 291 * latter can carry in from an earlier admitted IMMED insert. Strip 292 * PREEMPT too. 293 */ 294 *enq_flags &= ~(SCX_ENQ_IMMED | SCX_ENQ_PREEMPT); 295 p->scx.flags &= ~SCX_TASK_IMMED; 296 297 return &rq->scx.reject_dsq; 298 } 299 300 /* @p lost the caps needed to stay on @rq's local DSQ? Record reason if so. */ 301 bool scx_task_reenq_on_cap_revoke(struct rq *rq, struct task_struct *p) 302 { 303 u64 missing; 304 305 /* migration-disabled tasks are admitted regardless of caps */ 306 if (is_migration_disabled(p)) 307 return false; 308 309 missing = scx_missing_caps(scx_task_sched(p), cpu_of(rq), scx_caps_for_task(p)); 310 if (likely(!missing)) 311 return false; 312 313 p->scx.reenq_reason_caps = missing; 314 p->scx.reenq_reason_cid = __scx_cpu_to_cid(cpu_of(rq)); 315 return true; 316 } 317 318 /* 319 * Drain @rq->scx.reject_dsq, reenqueueing each task so the BPF re-decides 320 * from p->scx.reenq_reason_*. 321 * 322 * A task can be re-rejected repeatedly. The reenqueue is bounded per task in 323 * scx_do_enqueue_task(), which ejects the owning sub past SCX_REENQ_MAX_REPEAT. 324 * Rejection can't happen for root. 325 */ 326 void scx_reenq_reject(struct rq *rq) 327 { 328 LIST_HEAD(tasks); 329 struct task_struct *p, *n; 330 331 lockdep_assert_rq_held(rq); 332 333 if (!scx_has_subs() || list_empty(&rq->scx.reject_dsq.list)) 334 return; 335 336 /* 337 * Move to a private list so a task re-rejected by the 338 * scx_do_enqueue_task() below isn't revisited this round. 339 */ 340 list_for_each_entry_safe(p, n, &rq->scx.reject_dsq.list, scx.dsq_list.node) { 341 /* migration_pending tasks should have bypassed to local DSQ */ 342 if (WARN_ON_ONCE(p->migration_pending)) 343 continue; 344 345 scx_dispatch_dequeue(rq, p); 346 347 if (WARN_ON_ONCE(p->scx.flags & SCX_TASK_REENQ_REASON_MASK)) 348 p->scx.flags &= ~SCX_TASK_REENQ_REASON_MASK; 349 p->scx.flags |= SCX_TASK_REENQ_CAP; 350 351 list_add_tail(&p->scx.dsq_list.node, &tasks); 352 } 353 354 list_for_each_entry_safe(p, n, &tasks, scx.dsq_list.node) { 355 list_del_init(&p->scx.dsq_list.node); 356 357 scx_do_enqueue_task(rq, p, SCX_ENQ_REENQ, -1); 358 359 p->scx.flags &= ~SCX_TASK_REENQ_REASON_MASK; 360 } 361 } 362 363 /* record a caps change, see struct scx_caps_updated */ 364 static void caps_updated_record(struct scx_pshard *ps, const struct scx_cmask *cids, u64 caps, 365 struct list_head *to_deliver) 366 { 367 struct scx_caps_updated *cu = &ps->caps_updated; 368 369 guard(raw_spinlock)(&cu->lock); 370 scx_cmask_or(&cu->cmask, cids); 371 cu->caps |= caps; 372 if (list_empty(&cu->node_in_flight)) 373 list_add_tail(&cu->node_in_flight, to_deliver); 374 } 375 376 /* deliver queued caps_updated callbacks, see struct scx_caps_updated */ 377 static void caps_updated_deliver(struct list_head *to_deliver) 378 { 379 struct scx_caps_updated *cu, *tmp; 380 381 list_for_each_entry_safe(cu, tmp, to_deliver, node_in_flight) { 382 struct scx_pshard *ps = container_of(cu, struct scx_pshard, caps_updated); 383 struct scx_sched *sch = ps->sch; 384 385 while (true) { 386 u64 caps = 0; 387 388 /* 389 * During enable, has_op is set after ops.sub_attach(), 390 * so !has_op means the op is absent or the sched isn't 391 * live yet - e.g. caps grant from ops.sub_attach(). 392 * Either way don't consume - leave for 393 * scx_sub_seed_caps() to deliver once live. 394 */ 395 scoped_guard (raw_spinlock, &cu->lock) { 396 if (cu->caps && SCX_HAS_OP(sch, sub_caps_updated) && 397 likely(!READ_ONCE(sch->aborting))) { 398 struct scx_cmask_ref ref; 399 400 caps = cu->caps; 401 scx_cmask_ref_init_kern(sch, cu->cmask_arena_out, 402 ps->base, ps->nr_cids, &ref); 403 scx_cmask_ref_copy(&ref, &cu->cmask); 404 scx_cmask_clear(&cu->cmask); 405 cu->caps = 0; 406 } else { 407 list_del_init(&cu->node_in_flight); 408 } 409 } 410 if (!caps) 411 break; 412 413 /* caps != 0 only when deliverable (has_op, above) */ 414 SCX_CALL_OP(sch, sub_caps_updated, NULL, 415 scx_kaddr_to_arena(sch, cu->cmask_arena_out), 416 caps); 417 } 418 } 419 } 420 421 /* 422 * Deliver caps owed to @sch that couldn't be delivered earlier (e.g. a grant 423 * taken during its sub_attach(), before has_op was set). Called once @sch is 424 * enabled. 425 */ 426 static void scx_sub_seed_caps(struct scx_sched *sch) 427 { 428 LIST_HEAD(to_deliver); 429 s32 si; 430 431 guard(irqsave)(); 432 433 for (si = 0; si < sch->nr_pshards; si++) { 434 struct scx_pshard *ps = sch->pshard[si]; 435 struct scx_caps_updated *cu = &ps->caps_updated; 436 437 scoped_guard (raw_spinlock, &cu->lock) { 438 if (cu->caps && list_empty(&cu->node_in_flight)) 439 list_add_tail(&cu->node_in_flight, &to_deliver); 440 } 441 } 442 caps_updated_deliver(&to_deliver); 443 } 444 445 static u64 calc_effective_caps(struct scx_pshard *ps, s32 cid) 446 { 447 u64 ecaps = 0; 448 u32 cap_bit; 449 450 for (cap_bit = 0; cap_bit < __SCX_NR_CAPS; cap_bit++) 451 if (scx_cmask_test(cid, &ps->caps[cap_bit].cmask)) 452 ecaps |= BIT_U64(cap_bit) | scx_caps_implied(BIT_U64(cap_bit)); 453 return ecaps; 454 } 455 456 /** 457 * queue_sync_ecaps - Queue ecaps update for a (sch, cid) pair 458 * @sch: sched to update 459 * @cid: cid to update 460 * 461 * Queue an ecaps update for @sch's @cid and kick the cpu so that it syncs in 462 * balance_one(). 463 */ 464 static void queue_sync_ecaps(struct scx_sched *sch, s32 cid) 465 { 466 s32 cpu = __scx_cid_to_cpu(cid); 467 struct scx_sched_pcpu *pcpu = per_cpu_ptr(sch->pcpu, cpu); 468 469 /* 470 * Pairs with smp_mb() in scx_process_sync_ecaps(). Either the check 471 * below sees the node off the list and queues it, or the in-flight sync 472 * sees the caps[] update made before this call. 473 */ 474 smp_mb(); 475 476 /* @cid's pshard->lock excludes concurrent queueing attempts */ 477 if (llist_on_list(&pcpu->ecaps_to_sync_node)) 478 return; 479 if (llist_add(&pcpu->ecaps_to_sync_node, &cpu_rq(cpu)->scx.ecaps_to_sync)) 480 scx_kick_cpu(sch->ancestors[0], cpu, 0); 481 } 482 483 /* discard @rq's queued ecaps syncs */ 484 static void discard_queued_syncs(struct rq *rq) 485 { 486 struct llist_node *pos, *tmp; 487 488 lockdep_assert_rq_held(rq); 489 490 llist_for_each_safe(pos, tmp, llist_del_all(&rq->scx.ecaps_to_sync)) 491 init_llist_node(pos); 492 } 493 494 /** 495 * scx_process_sync_ecaps - Sync this cpu's ecaps to pshard->caps[] 496 * @rq: the cid's cpu rq 497 * @prev: @rq's previous task from the in-progress balance 498 * 499 * pshard->caps[] is the target configuration. pcpu->ecaps is the effective 500 * transposed copy owned by the cid's cpu and written only here under @rq's 501 * lock. 502 * 503 * A sched that newly gains baseline access here is owed an update_idle() so it 504 * learns the cid's idle state. Such a gain arms the per-rq 505 * %SCX_RQ_SUB_IDLE_RENOTIFY gate so the next idle pick delivers it. 506 */ 507 void scx_process_sync_ecaps(struct rq *rq, struct task_struct *prev) 508 { 509 s32 cpu = cpu_of(rq); 510 s32 cid, shard; 511 struct llist_node *batch, *pos, *tmp; 512 u64 lost_all = 0; 513 514 lockdep_assert_rq_held(rq); 515 516 if (!scx_has_subs() || likely(llist_empty(&rq->scx.ecaps_to_sync))) 517 return; 518 519 /* 520 * ecaps are zeroed while the cpu is inactive and must stay zero. 521 * Discard queued syncs instead of processing them - the 522 * scx_online_ecaps() reseed re-syncs every sched on activation. 523 * cpu_active() clears before the offline zeroing and sets before the 524 * reseed is queued, so this test can neither miss a racing sync nor 525 * eat the reseed. 526 */ 527 if (unlikely(!cpu_active(cpu))) { 528 discard_queued_syncs(rq); 529 return; 530 } 531 532 /* @cid is valid here: the cpu is active with queued syncs */ 533 cid = __scx_cpu_to_cid(cpu); 534 shard = rcu_dereference_all(scx_cid_to_shard)[cid]; 535 536 batch = llist_del_all(&rq->scx.ecaps_to_sync); 537 llist_for_each_safe(pos, tmp, batch) { 538 struct scx_sched_pcpu *pcpu = 539 container_of(pos, struct scx_sched_pcpu, ecaps_to_sync_node); 540 struct scx_pshard *ps = pcpu->sch->pshard[shard]; 541 u64 old, ecaps, lost, gained; 542 543 init_llist_node(pos); 544 545 /* pairs with smp_mb() in queue_sync_ecaps(), see there */ 546 smp_mb(); 547 548 old = READ_ONCE(pcpu->ecaps); 549 ecaps = calc_effective_caps(ps, cid); 550 WRITE_ONCE(pcpu->ecaps, ecaps); 551 552 lost = old & ~ecaps; 553 gained = ecaps & ~old; 554 lost_all |= lost; 555 556 /* 557 * Tell the sched its effective caps on this cid changed. The 558 * invocation is equivalent to the dispatch path and may drop 559 * and re-acquire the rq lock temporarily while the rest of 560 * @batch is held privately, see scx_discard_ecaps_to_sync(). 561 */ 562 if (ecaps != pcpu->reported_ecaps && 563 SCX_HAS_OP(pcpu->sch, sub_ecaps_updated) && 564 !scx_bypassing(pcpu->sch, cpu)) { 565 struct scx_dsp_ctx *dspc = &pcpu->dsp_ctx; 566 567 dspc->rq = rq; 568 /* stash @prev so nested dispatches can access it */ 569 rq->scx.sub_dispatch_prev = prev; 570 SCX_CALL_OP(pcpu->sch, sub_ecaps_updated, rq, scx_cpu_arg(cpu), 571 pcpu->reported_ecaps, ecaps); 572 rq->scx.sub_dispatch_prev = NULL; 573 scx_flush_dispatch_buf(pcpu->sch, rq); 574 pcpu->reported_ecaps = ecaps; 575 } 576 577 /* 578 * Gaining baseline access owes an update_idle() so the sched 579 * learns the cpu's idle state. Arm the per-rq gate so the next 580 * idle pick flushes it. Losing access drops any pending notify. 581 */ 582 if (gained & SCX_CAP_BASE) { 583 pcpu->idle_renotify = true; 584 rq->scx.flags |= SCX_RQ_SUB_IDLE_RENOTIFY; 585 } else if (lost & SCX_CAP_BASE) { 586 pcpu->idle_renotify = false; 587 } 588 } 589 590 /* 591 * Losing a cap can strand already-queued tasks. Schedule a reenq scan 592 * to move the now-capless ones off the local DSQ. The scan tests 593 * against the effective caps and thus must come after the ecaps sync. 594 */ 595 if (lost_all & SCX_CAPS_REENQ_ON_LOSS) 596 scx_schedule_reenq_local(rq, SCX_REENQ_CAP_REVOKE); 597 } 598 599 /** 600 * scx_unbypass_replay_ecaps - Replay a bypass-suppressed ecaps notification 601 * @rq: rq of the cpu leaving bypass 602 * @sch: scheduler that just left bypass on @rq's cpu 603 * 604 * scx_process_sync_ecaps() consumes syncs while bypassing without delivering 605 * ops.sub_ecaps_updated(), leaving reported_ecaps stale. Nothing re-queues a 606 * sync when bypass lifts, so without a replay a cid that never changes again 607 * would never be notified. The attach-time initial grants are the acute case 608 * as they are consumed during the enable bypass window. Re-queue a sync for 609 * any undelivered delta so the next balance delivers it. 610 */ 611 void scx_unbypass_replay_ecaps(struct rq *rq, struct scx_sched *sch) 612 { 613 s32 cpu = cpu_of(rq); 614 struct scx_sched_pcpu *pcpu = per_cpu_ptr(sch->pcpu, cpu); 615 struct scx_pshard *ps; 616 s32 cid; 617 618 lockdep_assert_rq_held(rq); 619 620 /* root holds every cap and never uses ecaps */ 621 if (!sch->level) 622 return; 623 624 if (READ_ONCE(pcpu->ecaps) == pcpu->reported_ecaps) 625 return; 626 627 cid = __scx_cpu_to_cid(cpu); 628 ps = sch->pshard[rcu_dereference_all(scx_cid_to_shard)[cid]]; 629 630 guard(raw_spinlock)(&ps->lock); 631 queue_sync_ecaps(sch, cid); 632 } 633 634 /* 635 * A cpu came back. Re-seed each sub-sched's ecaps on the cpu's cid. The sync 636 * recomputes effective caps from the pshard and fires ops.sub_ecaps_updated() 637 * only on a real change since offline. 638 */ 639 void scx_online_ecaps(struct rq *rq) 640 { 641 struct scx_sched *root, *pos; 642 s32 cid, shard; 643 644 /* 645 * Only a live hierarchy can have ecaps to reseed. This also keeps the 646 * table reads below away from an enable that failed before publishing 647 * the tables. A concurrent disable can't retire them, see 648 * handle_hotplug(). 649 */ 650 if (!scx_enabled()) 651 return; 652 653 guard(rq_lock_irqsave)(rq); 654 655 root = scx_root_protected(); 656 cid = __scx_cpu_to_cid(cpu_of(rq)); 657 shard = rcu_dereference_all(scx_cid_to_shard)[cid]; 658 659 scx_for_each_descendant_pre(pos, root) { 660 struct scx_pshard *ps; 661 662 /* root holds every cap and never uses ecaps */ 663 if (!pos->level) 664 continue; 665 666 ps = pos->pshard[shard]; 667 guard(raw_spinlock)(&ps->lock); 668 queue_sync_ecaps(pos, cid); 669 } 670 } 671 672 /* 673 * A cpu is going down. Zero each sub-sched's in-effect ecaps so cap checks 674 * treat the cpu as capless while offline. Pending and late-queued syncs are 675 * discarded at consumption by scx_process_sync_ecaps() while the cpu is 676 * inactive. Leave reported_ecaps. Ownership is unchanged, so the 677 * scx_online_ecaps() reseed reports only a genuine delta. No callback fires 678 * here. 679 */ 680 void scx_offline_ecaps(struct rq *rq) 681 { 682 s32 cpu = cpu_of(rq); 683 struct scx_sched *root, *pos; 684 685 guard(rq_lock_irqsave)(rq); 686 687 root = scx_root_protected(); 688 689 scx_for_each_descendant_pre(pos, root) { 690 /* root holds every cap and never uses ecaps */ 691 if (!pos->level) 692 continue; 693 694 WRITE_ONCE(per_cpu_ptr(pos->pcpu, cpu)->ecaps, 0); 695 } 696 } 697 698 /* 699 * @pcpu's sched was unhashed before the grace period, so nothing re-queues its 700 * sync node. Remove the node from @rq's pending list so the pcpu can be freed. 701 */ 702 void scx_discard_ecaps_to_sync(s32 cpu, struct scx_sched_pcpu *pcpu) 703 { 704 struct rq *rq = cpu_rq(cpu); 705 struct llist_node *head = NULL, *tail = NULL; 706 struct llist_node *pos, *tmp; 707 708 /* 709 * llist can't unlink a single node. Take all queued nodes, drop @pcpu's 710 * and resplice the rest. Nodes in the taken batch read as on-list 711 * throughout, so queue_sync_ecaps() stays correct. 712 */ 713 if (llist_on_list(&pcpu->ecaps_to_sync_node)) { 714 scoped_guard (rq_lock_irqsave, rq) { 715 llist_for_each_safe(pos, tmp, llist_del_all(&rq->scx.ecaps_to_sync)) { 716 if (pos == &pcpu->ecaps_to_sync_node) { 717 init_llist_node(pos); 718 } else { 719 pos->next = head; 720 head = pos; 721 if (!tail) 722 tail = pos; 723 } 724 } 725 if (head) 726 llist_add_batch(head, tail, &rq->scx.ecaps_to_sync); 727 } 728 } 729 730 /* 731 * An in-flight scx_process_sync_ecaps() batch may still hold the node 732 * privately across dispatch-induced rq unlocks, reading as on-list. 733 * 734 * Because a bypassing sched gets no op call, init_llist_node() and all 735 * @pcpu accesses share one contiguous lock hold, off-list under the rq 736 * lock means @pcpu won't be accessed again. 737 */ 738 while (true) { 739 scoped_guard (rq_lock_irqsave, rq) { 740 if (!llist_on_list(&pcpu->ecaps_to_sync_node)) 741 return; 742 } 743 cpu_relax(); 744 } 745 } 746 747 /** 748 * scx_discard_stale_ecaps_syncs - Discard ecaps syncs from earlier schedulers 749 * 750 * To be called during root enable before the scheduler goes live. An earlier 751 * root's sub-sched may not have gone through its RCU free path yet (e.g. a 752 * still-open link fd defers it) and can leave queued ecaps syncs behind. 753 * Processing them would decode the dead sched's pshards with the current cid 754 * layout. Discard them instead. The backing scx_sched_pcpu's are still 755 * allocated as the free path removes ecaps_to_sync_node before freeing. 756 */ 757 void scx_discard_stale_ecaps_syncs(void) 758 { 759 s32 cpu; 760 761 for_each_possible_cpu(cpu) { 762 struct rq *rq = cpu_rq(cpu); 763 764 guard(rq_lock_irqsave)(rq); 765 discard_queued_syncs(rq); 766 } 767 } 768 769 static DECLARE_WAIT_QUEUE_HEAD(scx_unlink_waitq); 770 771 void drain_descendants(struct scx_sched *sch) 772 { 773 /* 774 * Child scheds that finished the critical part of disabling will take 775 * themselves off @sch->children. Wait for it to drain. As propagation 776 * is recursive, empty @sch->children means that all proper descendant 777 * scheds reached unlinking stage. 778 */ 779 wait_event(scx_unlink_waitq, list_empty(&sch->children)); 780 } 781 782 /** 783 * scx_rehome_task - Move a task to a sched it has been initialized for 784 * @to: sched taking over @p, @p's init on it already complete 785 * @p: task to re-home 786 * 787 * Exit @p from its current sched and switch it over to @to, overriding the 788 * state to %SCX_TASK_READY to account for the already completed init. A task 789 * on a non-ext class, possible under an %SCX_OPS_SWITCH_PARTIAL root, stays 790 * %READY and is enabled by switching_to_scx() if it switches over. 791 */ 792 static void scx_rehome_task(struct scx_sched *to, struct task_struct *p) 793 { 794 lockdep_assert_held(&p->pi_lock); 795 lockdep_assert_rq_held(task_rq(p)); 796 797 scoped_guard (sched_change, p, DEQUEUE_SAVE | DEQUEUE_MOVE) { 798 scx_disable_and_exit_task(scx_task_sched(p), p); 799 scx_set_task_state(p, SCX_TASK_INIT_BEGIN); 800 scx_set_task_state(p, SCX_TASK_INIT); 801 scx_set_task_sched(p, to); 802 scx_set_task_state(p, SCX_TASK_READY); 803 if (p->sched_class == &ext_sched_class) 804 scx_enable_task(to, p); 805 } 806 } 807 808 /** 809 * scx_punt_task - Hand a task to a failed sched without initialization 810 * @to: failed and bypassed sched taking custody of @p 811 * @p: task to punt 812 * 813 * Take @p off its current sched and put it on @to at %SCX_TASK_NONE. @to is 814 * dying and its teardown will re-home @p properly. 815 * 816 * Used when @to must take over @p but failed to initialize it. Bypass keeps 817 * scheduling decisions away from @to but @p can still trigger its task ops, 818 * which may confuse the BPF side. @to is dying anyway. The exit paths skip 819 * %NONE tasks (see __scx_disable_and_exit_task() and switched_from_scx()). 820 */ 821 static void scx_punt_task(struct scx_sched *to, struct task_struct *p) 822 { 823 lockdep_assert_held(&p->pi_lock); 824 lockdep_assert_rq_held(task_rq(p)); 825 WARN_ON_ONCE(!READ_ONCE(to->bypass_depth)); 826 827 scoped_guard (sched_change, p, DEQUEUE_SAVE | DEQUEUE_MOVE) { 828 scx_disable_and_exit_task(scx_task_sched(p), p); 829 scx_set_task_sched(p, to); 830 } 831 } 832 833 static void scx_fail_parent(struct scx_sched *sch, 834 struct task_struct *failed, s32 fail_code) 835 { 836 struct scx_sched *parent = scx_parent(sch); 837 struct scx_task_iter sti; 838 struct task_struct *p; 839 840 scx_error(parent, "ops.init_task() failed (%d) for %s[%d] while disabling a sub-scheduler", 841 fail_code, failed->comm, failed->pid); 842 843 /* 844 * Once $parent is bypassed, tasks can be punted into it. This may 845 * cause downstream failures on the BPF side but $parent is dying 846 * anyway. 847 */ 848 scx_bypass(parent, true); 849 850 scx_task_iter_start(&sti, sch->cgrp); 851 while ((p = scx_task_iter_next_locked(&sti))) { 852 if (scx_task_on_sched(parent, p)) 853 continue; 854 855 scx_punt_task(parent, p); 856 } 857 scx_task_iter_stop(&sti); 858 } 859 860 #ifdef CONFIG_EXT_GROUP_SCHED 861 /** 862 * scx_cgroup_claim_subtree - Claim the subtree's cgroups for an enabling sub 863 * @sch: sub-scheduler being enabled 864 * 865 * Called while enabling @sch, after the subtree's cgrp->scx_sched's are pointed 866 * at @sch and before any task is claimed. This mirrors root enable's 867 * cgroups-before-tasks order. The ops.init_task() args are task_group-granular 868 * and can still reference a cgroup outside the handed-over set when the cpu 869 * controller is coarser than the sub topology or mounted on cgroup1. 870 * 871 * First init each of the parent sched's subtree cgroups on @sch, and only then 872 * exit them from the parent, so that a failed init can be unwound with the 873 * parent untouched. The both-inited transient is invisible outside 874 * scx_cgroup_lock(). %SCX_TG_SUB_INIT tracks the first pass's progress. 875 * %SCX_TG_INITED stays set throughout, except for a task_group whose 876 * ops.cgroup_init() failed on the parent (see scx_cgroup_return_subtree()): 877 * there is nothing to exit from the parent and %SCX_TG_INITED is set back with 878 * the transfer. 879 * 880 * Dying but not yet offlined task_groups are included: a removed cgroup keeps 881 * hosting scheduling events until its dying tasks finish their final context 882 * switches, so it still needs to be inited on a sched, and its offline-time 883 * ops.cgroup_exit() follows the last of those events. 884 * 885 * Return 0 on success, -errno on failure. On failure, @sch has been 886 * scx_error()'d and is left with no cgroups. 887 */ 888 static s32 scx_cgroup_claim_subtree(struct scx_sched *sch) 889 { 890 struct cgroup *sub_cgrp = sch_cgroup(sch); 891 struct cgroup_subsys_state *ecss = cgroup_e_css(sub_cgrp, &cpu_cgrp_subsys); 892 struct scx_sched *parent = scx_parent(sch); 893 struct cgroup_subsys_state *css; 894 int ret; 895 896 css_for_each_descendant_pre(css, ecss) { 897 struct task_group *tg = css_tg(css); 898 struct scx_cgroup_init_args args = { 899 .weight = tg->scx.weight, 900 .bw_period_us = tg->scx.bw_period_us, 901 .bw_quota_us = tg->scx.bw_quota_us, 902 .bw_burst_us = tg->scx.bw_burst_us, 903 }; 904 905 if (tg->scx.sched != parent || 906 !cgroup_is_descendant(css->cgroup, sub_cgrp)) 907 continue; 908 909 if (SCX_HAS_OP(sch, cgroup_init)) { 910 ret = SCX_CALL_OP_RET(sch, cgroup_init, NULL, css->cgroup, &args); 911 if (ret) { 912 scx_error(sch, "ops.cgroup_init() failed (%d)", ret); 913 goto err; 914 } 915 } 916 tg->scx.flags |= SCX_TG_SUB_INIT; 917 } 918 919 css_for_each_descendant_post(css, ecss) { 920 struct task_group *tg = css_tg(css); 921 922 /* 923 * SUB_INIT is pass 1's progress mark: pass 2 and the err path 924 * must visit exactly the tgs pass 1 inited. 925 */ 926 if (!(tg->scx.flags & SCX_TG_SUB_INIT)) 927 continue; 928 929 /* skip the exit if the parent's ops.cgroup_init() failed */ 930 if ((tg->scx.flags & SCX_TG_INITED) && SCX_HAS_OP(parent, cgroup_exit)) 931 SCX_CALL_OP(parent, cgroup_exit, NULL, css->cgroup); 932 tg->scx.sched = sch; 933 tg->scx.flags |= SCX_TG_INITED; 934 tg->scx.flags &= ~SCX_TG_SUB_INIT; 935 } 936 937 return 0; 938 939 err: 940 css_for_each_descendant_post(css, ecss) { 941 struct task_group *tg = css_tg(css); 942 943 if (!(tg->scx.flags & SCX_TG_SUB_INIT)) 944 continue; 945 946 if (SCX_HAS_OP(sch, cgroup_exit)) 947 SCX_CALL_OP(sch, cgroup_exit, NULL, css->cgroup); 948 tg->scx.flags &= ~SCX_TG_SUB_INIT; 949 } 950 return ret; 951 } 952 953 /** 954 * scx_cgroup_return_subtree - Return the subtree's cgroups to the parent sched 955 * @sch: sub-scheduler being disabled 956 * 957 * Called while disabling @sch, after the subtree's cgrp->scx_sched's are reset 958 * to the parent sched and before tasks are re-homed, mirroring root disable's 959 * cgroups-before-tasks teardown order. The reverse of 960 * scx_cgroup_claim_subtree(): exit @sch's cgroups from @sch, then init them on 961 * the parent with the current tg->scx.* values, resyncing settings that changed 962 * while @sch had them. 963 * 964 * When an init on the parent fails, the parent is failed - the same policy as 965 * task re-homing. The remaining task_groups are punted: they move to the parent 966 * anyway with %SCX_TG_INITED cleared, as ops.cgroup_init() failed or never ran 967 * for them. A punted task_group gets no cgroup ops. The dying parent's own 968 * disable moves it one sched up, initing it there. Root ends the chain: root 969 * teardown drops cgroup ops entirely and the next enable's bulk init re-inits 970 * every online task_group. 971 * 972 * The task re-home that follows still delivers ops.init_task() to the dying 973 * parent, including for tasks in punted cgroups it never inited - tolerated 974 * like the downstream failures of task punting (see scx_punt_task()). 975 */ 976 static void scx_cgroup_return_subtree(struct scx_sched *sch) 977 { 978 struct cgroup *sub_cgrp = sch_cgroup(sch); 979 struct cgroup_subsys_state *ecss = cgroup_e_css(sub_cgrp, &cpu_cgrp_subsys); 980 struct scx_sched *parent = scx_parent(sch); 981 struct cgroup_subsys_state *css; 982 bool parent_failed = false; 983 int ret; 984 985 css_for_each_descendant_post(css, ecss) { 986 struct task_group *tg = css_tg(css); 987 988 if (tg->scx.sched != sch || 989 !cgroup_is_descendant(css->cgroup, sub_cgrp)) 990 continue; 991 992 /* skip the exit if @sch's ops.cgroup_init() failed for the tg */ 993 if ((tg->scx.flags & SCX_TG_INITED) && SCX_HAS_OP(sch, cgroup_exit)) 994 SCX_CALL_OP(sch, cgroup_exit, NULL, css->cgroup); 995 tg->scx.sched = parent; 996 tg->scx.flags |= SCX_TG_SUB_INIT; 997 } 998 999 css_for_each_descendant_pre(css, ecss) { 1000 struct task_group *tg = css_tg(css); 1001 struct scx_cgroup_init_args args = { 1002 .weight = tg->scx.weight, 1003 .bw_period_us = tg->scx.bw_period_us, 1004 .bw_quota_us = tg->scx.bw_quota_us, 1005 .bw_burst_us = tg->scx.bw_burst_us, 1006 }; 1007 1008 /* the first pass must have transferred everything */ 1009 WARN_ON_ONCE(tg->scx.sched == sch); 1010 1011 /* 1012 * SUB_INIT distinguishes the tgs pass 1 moved. The sched test 1013 * can't: a tg punted to the parent by an earlier failure would 1014 * also match. 1015 */ 1016 if (!(tg->scx.flags & SCX_TG_SUB_INIT)) 1017 continue; 1018 tg->scx.flags &= ~(SCX_TG_SUB_INIT | SCX_TG_INITED); 1019 1020 /* 1021 * A re-init on $parent failed. The task_groups from here on are 1022 * punted: they stay on the dying $parent with INITED clear and 1023 * move onward when it disables. 1024 */ 1025 if (parent_failed) 1026 continue; 1027 1028 if (SCX_HAS_OP(parent, cgroup_init)) { 1029 ret = SCX_CALL_OP_RET(parent, cgroup_init, NULL, css->cgroup, &args); 1030 if (ret) { 1031 scx_error(parent, "ops.cgroup_init() failed (%d) while disabling a sub-scheduler", 1032 ret); 1033 parent_failed = true; 1034 continue; 1035 } 1036 } 1037 tg->scx.flags |= SCX_TG_INITED; 1038 } 1039 } 1040 #else 1041 static inline s32 scx_cgroup_claim_subtree(struct scx_sched *sch) { return 0; } 1042 static inline void scx_cgroup_return_subtree(struct scx_sched *sch) {} 1043 #endif 1044 1045 void scx_sub_disable(struct scx_sched *sch) 1046 { 1047 struct scx_sched *parent = scx_parent(sch); 1048 struct scx_task_iter sti; 1049 struct task_struct *p; 1050 int ret; 1051 1052 /* 1053 * Guarantee forward progress and wait for descendants to be disabled. 1054 * To limit disruptions, $parent is not bypassed. Tasks are fully 1055 * prepped and then inserted back into $parent. 1056 */ 1057 scx_bypass(sch, true); 1058 drain_descendants(sch); 1059 1060 /* 1061 * Here, every runnable task is guaranteed to make forward progress and 1062 * we can safely use blocking synchronization constructs. Actually 1063 * disable ops. 1064 */ 1065 mutex_lock(&scx_enable_mutex); 1066 percpu_down_write(&scx_fork_rwsem); 1067 scx_cgroup_lock(); 1068 1069 /* 1070 * An enable that failed before scx_link_sched() never owned a cgroup or 1071 * task and won't be waited on by an ancestor's drain_descendants(). 1072 * Nothing to reparent and walking the tasks can misbehave as the task 1073 * ownership invariant (either owned by self or parent) does not hold. 1074 */ 1075 if (list_empty(&sch->sibling)) 1076 goto dump; 1077 1078 set_cgroup_sched(sch_cgroup(sch), parent); 1079 1080 /* 1081 * Return the subtree's cgroups before re-homing tasks so that any 1082 * ops.init_task() on $parent only sees cgroups it has initialized. 1083 */ 1084 scx_cgroup_return_subtree(sch); 1085 1086 scx_task_iter_start(&sti, sch->cgrp); 1087 while ((p = scx_task_iter_next_locked(&sti))) { 1088 struct rq *rq; 1089 struct rq_flags rf; 1090 1091 /* filter out duplicate visits */ 1092 if (scx_task_on_sched(parent, p)) 1093 continue; 1094 1095 /* 1096 * By the time control reaches here, all linked descendant 1097 * schedulers should have been disabled. 1098 */ 1099 WARN_ON_ONCE(!scx_task_on_sched(sch, p)); 1100 1101 /* 1102 * @p is pinned by the iter: css_task_iter_next() takes a 1103 * reference and holds it until the next iter_next() call, so 1104 * @p->usage is guaranteed > 0. 1105 */ 1106 get_task_struct(p); 1107 1108 scx_task_iter_unlock(&sti); 1109 1110 /* 1111 * $p is READY or ENABLED on @sch. Initialize for $parent, 1112 * disable and exit from @sch, and then switch over to $parent. 1113 * 1114 * If a task fails to initialize for $parent, the only available 1115 * action is disabling $parent too. While this allows disabling 1116 * of a child sched to cause the parent scheduler to fail, the 1117 * failure can only originate from ops.init_task() of the 1118 * parent. A child can't directly affect the parent through its 1119 * own failures. 1120 */ 1121 ret = __scx_init_task(parent, p, NULL, false); 1122 if (ret) { 1123 scx_fail_parent(sch, p, ret); 1124 put_task_struct(p); 1125 break; 1126 } 1127 1128 rq = task_rq_lock(p, &rf); 1129 1130 if (scx_get_task_state(p) == SCX_TASK_DEAD) { 1131 /* 1132 * sched_ext_dead() raced us between __scx_init_task() 1133 * and this rq lock and ran exit_task() on @sch (the 1134 * sched @p was on at that point), not on $parent. 1135 * $parent's just-completed init is owed an exit_task() 1136 * and we issue it here. 1137 */ 1138 scx_sub_init_cancel_task(parent, p); 1139 task_rq_unlock(rq, p, &rf); 1140 put_task_struct(p); 1141 continue; 1142 } 1143 1144 scx_rehome_task(parent, p); 1145 1146 task_rq_unlock(rq, p, &rf); 1147 put_task_struct(p); 1148 } 1149 scx_task_iter_stop(&sti); 1150 1151 dump: 1152 scx_disable_dump(sch); 1153 1154 scx_cgroup_unlock(); 1155 percpu_up_write(&scx_fork_rwsem); 1156 1157 /* 1158 * All tasks are moved off of @sch but there may still be on-going 1159 * operations (e.g. ops.select_cpu()). Drain them by flushing RCU. Use 1160 * the expedited version as ancestors may be waiting in bypass mode. 1161 * Also, tell the parent that there is no need to keep running bypass 1162 * DSQs for us. 1163 */ 1164 synchronize_rcu_expedited(); 1165 scx_disable_bypass_dsp(sch); 1166 1167 scx_unlink_sched(sch); 1168 1169 mutex_unlock(&scx_enable_mutex); 1170 1171 /* 1172 * @sch is now unlinked from the parent's children list. Notify and call 1173 * ops.sub_detach/exit(). Note that ops.sub_detach/exit() must be called 1174 * after unlinking and releasing all locks. See scx_claim_exit(). 1175 */ 1176 wake_up_all(&scx_unlink_waitq); 1177 1178 if (parent->ops.sub_detach && sch->sub_attached) { 1179 struct scx_sub_detach_args sub_detach_args = { 1180 .ops = &sch->ops, 1181 .cgroup_path = sch->cgrp_path, 1182 }; 1183 SCX_CALL_OP(parent, sub_detach, NULL, 1184 &sub_detach_args); 1185 } 1186 1187 scx_log_sched_disable(sch); 1188 1189 if (sch->ops.exit) 1190 SCX_CALL_OP(sch, exit, NULL, sch->exit_info); 1191 1192 /* 1193 * @sch's non-ops programs such as timers and tracers can fire after 1194 * ops.exit(). Now that exit is complete, stop scx_prog_sched() from 1195 * resolving to @sch and drain in-flight resolvers. 1196 */ 1197 WRITE_ONCE(sch->dead, true); 1198 synchronize_rcu(); 1199 1200 if (sch->sub_kset) 1201 kobject_del(&sch->sub_kset->kobj); 1202 /* not added if enable failed before scx_sched_sysfs_add() */ 1203 if (sch->kobj.state_in_sysfs) 1204 kobject_del(&sch->kobj); 1205 } 1206 1207 /* verify that a scheduler can be attached to @cgrp and return the parent */ 1208 static struct scx_sched *find_parent_sched(struct cgroup *cgrp) 1209 { 1210 struct scx_sched *parent = scx_cgroup_sched(cgrp); 1211 struct scx_sched *pos; 1212 1213 lockdep_assert_held(&scx_sched_lock); 1214 1215 /* can't attach twice to the same cgroup */ 1216 if (parent->cgrp == cgrp) 1217 return ERR_PTR(-EBUSY); 1218 1219 /* does $parent allow sub-scheds? */ 1220 if (!parent->ops.sub_attach) 1221 return ERR_PTR(-EOPNOTSUPP); 1222 1223 /* can't insert between $parent and its exiting children */ 1224 list_for_each_entry(pos, &parent->children, sibling) 1225 if (cgroup_is_descendant(pos->cgrp, cgrp)) 1226 return ERR_PTR(-EBUSY); 1227 1228 return parent; 1229 } 1230 1231 static bool assert_task_ready_or_enabled(struct task_struct *p) 1232 { 1233 u32 state = scx_get_task_state(p); 1234 1235 switch (state) { 1236 case SCX_TASK_READY: 1237 case SCX_TASK_ENABLED: 1238 return true; 1239 default: 1240 WARN_ONCE(true, "sched_ext: Invalid task state %d for %s[%d] during enabling sub sched", 1241 state, p->comm, p->pid); 1242 return false; 1243 } 1244 } 1245 1246 void scx_sub_enable_workfn(struct kthread_work *work) 1247 { 1248 struct scx_enable_cmd *cmd = container_of(work, struct scx_enable_cmd, work); 1249 struct sched_ext_ops *ops = cmd->ops; 1250 struct cgroup *cgrp; 1251 struct scx_sched *parent, *sch; 1252 struct scx_task_iter sti; 1253 struct task_struct *p; 1254 s32 i, ret; 1255 1256 mutex_lock(&scx_enable_mutex); 1257 1258 if (!scx_enabled()) { 1259 ret = -ENODEV; 1260 goto out_unlock; 1261 } 1262 1263 /* See scx_root_enable_workfn() for the @ops->priv check. */ 1264 if (rcu_access_pointer(ops->priv)) { 1265 ret = -EBUSY; 1266 goto out_unlock; 1267 } 1268 1269 cgrp = cgroup_get_from_id(ops->sub_cgroup_id); 1270 if (IS_ERR(cgrp)) { 1271 ret = PTR_ERR(cgrp); 1272 goto out_unlock; 1273 } 1274 1275 raw_spin_lock_irq(&scx_sched_lock); 1276 parent = find_parent_sched(cgrp); 1277 if (IS_ERR(parent)) { 1278 raw_spin_unlock_irq(&scx_sched_lock); 1279 ret = PTR_ERR(parent); 1280 goto out_put_cgrp; 1281 } 1282 kobject_get(&parent->kobj); 1283 raw_spin_unlock_irq(&scx_sched_lock); 1284 1285 /* 1286 * Flip the hot-path gates before ops->priv is published - the sub's 1287 * programs can e.g. kick cpus from that point on. The matching dec is 1288 * at the end of scx_sched_free_rcu_work(). 1289 */ 1290 static_branch_inc(&__scx_has_subs); 1291 1292 /* scx_alloc_and_add_sched() consumes @cgrp whether it succeeds or not */ 1293 sch = scx_alloc_and_add_sched(cmd, cgrp, parent); 1294 kobject_put(&parent->kobj); 1295 if (IS_ERR(sch)) { 1296 static_branch_dec(&__scx_has_subs); 1297 ret = PTR_ERR(sch); 1298 goto out_unlock; 1299 } 1300 1301 /* 1302 * Validate before scx_link_sched() publishes @sch, so an invalid sub 1303 * never becomes visible with an unallocated pshard. 1304 */ 1305 ret = scx_validate_ops(sch, ops); 1306 if (ret) 1307 goto err_disable; 1308 1309 /* 1310 * Allocate pshard[] before scx_link_sched() publishes @sch into the 1311 * parent's RCU children list. A concurrent revoke walking the tree 1312 * would otherwise dereference sch->pshard[si] while it's still NULL. 1313 * Unlike the root path, the cid shard layout is stable at this point. 1314 * 1315 * scx_alloc_pshards() skips allocation when @sch's arena pool isn't 1316 * initialized, so scx_arena_pool_init() must run first. 1317 */ 1318 ret = scx_arena_pool_init(sch); 1319 if (ret) 1320 goto err_disable; 1321 1322 ret = scx_alloc_pshards(sch); 1323 if (ret) 1324 goto err_disable; 1325 1326 ret = scx_link_sched(sch); 1327 if (ret) 1328 goto err_disable; 1329 1330 ret = scx_sched_sysfs_add(sch); 1331 if (ret) 1332 goto err_disable; 1333 1334 if (sch->level >= SCX_SUB_MAX_DEPTH) { 1335 scx_error(sch, "max nesting depth %d violated", 1336 SCX_SUB_MAX_DEPTH); 1337 ret = -EINVAL; 1338 goto err_disable; 1339 } 1340 1341 if (sch->ops.init) { 1342 ret = SCX_CALL_OP_RET(sch, init, NULL); 1343 if (ret) { 1344 ret = scx_ops_sanitize_err(sch, "init", ret); 1345 scx_error(sch, "ops.init() failed (%d)", ret); 1346 goto err_disable; 1347 } 1348 sch->exit_info->flags |= SCX_EFLAG_INITIALIZED; 1349 } 1350 1351 ret = scx_set_cmask_scratch_alloc(sch); 1352 if (ret) 1353 goto err_disable; 1354 1355 struct scx_sub_attach_args sub_attach_args = { 1356 .ops = &sch->ops, 1357 .cgroup_path = sch->cgrp_path, 1358 }; 1359 1360 ret = SCX_CALL_OP_RET(parent, sub_attach, NULL, 1361 &sub_attach_args); 1362 if (ret) { 1363 ret = scx_ops_sanitize_err(sch, "sub_attach", ret); 1364 scx_error(sch, "parent rejected (%d)", ret); 1365 goto err_disable; 1366 } 1367 sch->sub_attached = true; 1368 1369 scx_bypass(sch, true); 1370 1371 for (i = SCX_OPI_BEGIN; i < SCX_OPI_END; i++) 1372 if (((void (**)(void))ops)[i]) 1373 set_bit(i, sch->has_op); 1374 1375 percpu_down_write(&scx_fork_rwsem); 1376 scx_cgroup_lock(); 1377 1378 /* 1379 * Set cgroup->scx_sched's and check CSS_ONLINE. Either we see 1380 * !CSS_ONLINE or scx_cgroup_lifetime_notify() sees and shoots us down. 1381 */ 1382 set_cgroup_sched(sch_cgroup(sch), sch); 1383 if (!(cgrp->self.flags & CSS_ONLINE)) { 1384 scx_error(sch, "cgroup is not online"); 1385 ret = -ENODEV; 1386 goto err_unlock_and_disable; 1387 } 1388 1389 /* 1390 * Take over the subtree's cgroups before any task is claimed, 1391 * mirroring root enable's cgroups-before-tasks order. 1392 */ 1393 ret = scx_cgroup_claim_subtree(sch); 1394 if (ret) 1395 goto err_unlock_and_disable; 1396 1397 /* 1398 * Initialize tasks for the new child $sch without exiting them for 1399 * $parent so that the tasks can always be reverted back to $parent 1400 * sched on child init failure. 1401 */ 1402 WARN_ON_ONCE(scx_enabling_sub_sched); 1403 scx_enabling_sub_sched = sch; 1404 1405 scx_task_iter_start(&sti, sch->cgrp); 1406 while ((p = scx_task_iter_next_locked(&sti))) { 1407 struct rq *rq; 1408 struct rq_flags rf; 1409 1410 /* 1411 * Task iteration may visit the same task twice when racing 1412 * against exiting. Use %SCX_TASK_SUB_INIT to mark tasks which 1413 * finished __scx_init_task() and skip if set. 1414 * 1415 * A task may exit and get freed between __scx_init_task() 1416 * completion and scx_enable_task(). In such cases, 1417 * scx_disable_and_exit_task() must exit the task for both the 1418 * parent and child scheds. 1419 */ 1420 if (p->scx.flags & SCX_TASK_SUB_INIT) 1421 continue; 1422 1423 /* @p is pinned by the iter; see scx_sub_disable() */ 1424 get_task_struct(p); 1425 1426 if (!assert_task_ready_or_enabled(p)) { 1427 ret = -EINVAL; 1428 goto abort; 1429 } 1430 1431 scx_task_iter_unlock(&sti); 1432 1433 /* 1434 * As $p is still on $parent, it can't be transitioned to INIT. 1435 * Let's worry about task state later. Use __scx_init_task(). 1436 */ 1437 ret = __scx_init_task(sch, p, NULL, false); 1438 if (ret) 1439 goto abort; 1440 1441 rq = task_rq_lock(p, &rf); 1442 1443 if (scx_get_task_state(p) == SCX_TASK_DEAD) { 1444 /* 1445 * sched_ext_dead() raced us between __scx_init_task() 1446 * and this rq lock and ran exit_task() on $parent (the 1447 * sched @p was on at that point), not on @sch. @sch's 1448 * just-completed init is owed an exit_task() and we 1449 * issue it here. 1450 */ 1451 scx_sub_init_cancel_task(sch, p); 1452 task_rq_unlock(rq, p, &rf); 1453 put_task_struct(p); 1454 continue; 1455 } 1456 1457 p->scx.flags |= SCX_TASK_SUB_INIT; 1458 task_rq_unlock(rq, p, &rf); 1459 1460 put_task_struct(p); 1461 } 1462 scx_task_iter_stop(&sti); 1463 1464 /* 1465 * All tasks are prepped. Disable/exit tasks for $parent and enable for 1466 * the new @sch. 1467 */ 1468 scx_task_iter_start(&sti, sch->cgrp); 1469 while ((p = scx_task_iter_next_locked(&sti))) { 1470 /* 1471 * Use clearing of %SCX_TASK_SUB_INIT to detect and skip 1472 * duplicate iterations. 1473 */ 1474 if (!(p->scx.flags & SCX_TASK_SUB_INIT)) 1475 continue; 1476 1477 scoped_guard (sched_change, p, DEQUEUE_SAVE | DEQUEUE_MOVE) { 1478 /* 1479 * $p must be either READY or ENABLED. If ENABLED, 1480 * __scx_disabled_and_exit_task() first disables and 1481 * makes it READY. However, after exiting $p, it will 1482 * leave $p as READY. 1483 */ 1484 assert_task_ready_or_enabled(p); 1485 __scx_disable_and_exit_task(parent, p); 1486 1487 /* 1488 * $p is now only initialized for @sch and READY, which 1489 * is what we want. Assign it to @sch and, if it's on 1490 * the ext class, enable. A non-ext task, possible under 1491 * an %SCX_OPS_SWITCH_PARTIAL root, stays READY and is 1492 * enabled by switching_to_scx() if it switches over. 1493 */ 1494 scx_set_task_sched(p, sch); 1495 if (p->sched_class == &ext_sched_class) 1496 scx_enable_task(sch, p); 1497 1498 p->scx.flags &= ~SCX_TASK_SUB_INIT; 1499 } 1500 } 1501 scx_task_iter_stop(&sti); 1502 1503 scx_enabling_sub_sched = NULL; 1504 1505 scx_cgroup_unlock(); 1506 percpu_up_write(&scx_fork_rwsem); 1507 1508 scx_bypass(sch, false); 1509 1510 /* @sch is enabled; deliver any caps owed since its sub_attach() */ 1511 scx_sub_seed_caps(sch); 1512 1513 pr_info("sched_ext: BPF sub-scheduler \"%s\" enabled\n", sch->ops.name); 1514 kobject_uevent(&sch->kobj, KOBJ_ADD); 1515 ret = 0; 1516 goto out_unlock; 1517 1518 out_put_cgrp: 1519 cgroup_put(cgrp); 1520 out_unlock: 1521 mutex_unlock(&scx_enable_mutex); 1522 cmd->ret = ret; 1523 return; 1524 1525 abort: 1526 put_task_struct(p); 1527 scx_task_iter_stop(&sti); 1528 1529 /* 1530 * Undo __scx_init_task() for tasks we marked. scx_enable_task() never 1531 * ran for @sch on them, so calling scx_disable_task() here would invoke 1532 * ops.disable() without a matching ops.enable(). scx_enabling_sub_sched 1533 * must stay set until SUB_INIT is cleared from every marked task - 1534 * scx_disable_and_exit_task() reads it when a task exits concurrently. 1535 */ 1536 scx_task_iter_start(&sti, sch->cgrp); 1537 while ((p = scx_task_iter_next_locked(&sti))) { 1538 if (p->scx.flags & SCX_TASK_SUB_INIT) { 1539 scx_sub_init_cancel_task(sch, p); 1540 p->scx.flags &= ~SCX_TASK_SUB_INIT; 1541 } 1542 } 1543 scx_task_iter_stop(&sti); 1544 scx_enabling_sub_sched = NULL; 1545 err_unlock_and_disable: 1546 /* we'll soon enter disable path, keep bypass on */ 1547 scx_cgroup_unlock(); 1548 percpu_up_write(&scx_fork_rwsem); 1549 err_disable: 1550 mutex_unlock(&scx_enable_mutex); 1551 /* 1552 * Some enable failures only return an errno (e.g. -ENOMEM from an 1553 * allocation) without calling scx_error(). Record it so 1554 * scx_flush_disable_work() runs the disable and ops.exit() fires. 1555 */ 1556 scx_error(sch, "scx_sub_enable() failed (%d)", ret); 1557 scx_flush_disable_work(sch); 1558 cmd->ret = 0; 1559 } 1560 1561 /** 1562 * scx_cgroup_task_migrating - Prepare a task for a cgroup migration 1563 * @ctx: migration being prepared 1564 * 1565 * A task's sched must match its cgroup's owner, so a migration that crosses a 1566 * sched boundary re-homes the task once committed. Run the fallible part here, 1567 * before the migration commits: initialize the task for the destination sched. 1568 * A rejection fails the cgroup.procs write. 1569 */ 1570 static s32 scx_cgroup_task_migrating(struct cgroup_task_migrate_ctx *ctx) 1571 { 1572 struct task_struct *p = ctx->task; 1573 struct scx_sched *to; 1574 int ret; 1575 1576 /* 1577 * Cleared under scx_cgroup_lock() before root disable starts tearing 1578 * down tasks. As cgroup_mutex is held, a set flag guarantees that the 1579 * teardown loop is not running concurrently. 1580 */ 1581 if (!scx_cgroup_enabled) 1582 return NOTIFY_OK; 1583 1584 to = scx_cgroup_sched(ctx->dst_dcgrp); 1585 if (scx_task_on_sched(to, p)) 1586 return NOTIFY_OK; 1587 1588 ret = __scx_init_task(to, p, ctx->dst_dcgrp, false); 1589 if (ret) 1590 return notifier_from_errno(ret); 1591 1592 return NOTIFY_OK; 1593 } 1594 1595 /** 1596 * scx_cgroup_task_migrated - Re-home a task that changed cgroups 1597 * @ctx: committed migration 1598 * 1599 * Move the task to its new cgroup's sched, which scx_cgroup_task_migrating() 1600 * already initialized it for. Can't fail. 1601 * 1602 * This is safe against all phases of the destination sched's destruction. A 1603 * disable resets cgroup ownership to the parent and re-homes tasks in one 1604 * scx_cgroup_lock() section. If that section already ran, the destination would 1605 * be the parent. Otherwise, the re-home loop is still ahead and guaranteed to 1606 * visit the task, now in the destination cgroup. 1607 */ 1608 static void scx_cgroup_task_migrated(struct cgroup_task_migrate_ctx *ctx) 1609 { 1610 struct task_struct *p = ctx->task; 1611 struct scx_sched *to; 1612 struct rq *rq; 1613 struct rq_flags rf; 1614 1615 if (!scx_cgroup_enabled) 1616 return; 1617 1618 to = scx_cgroup_sched(ctx->dst_dcgrp); 1619 if (scx_task_on_sched(to, p)) 1620 return; 1621 1622 rq = task_rq_lock(p, &rf); 1623 scx_rehome_task(to, p); 1624 task_rq_unlock(rq, p, &rf); 1625 } 1626 1627 /** 1628 * scx_cgroup_task_migrate_canceled - Undo migration preparation 1629 * @ctx: canceled migration 1630 * 1631 * The migration failed after scx_cgroup_task_migrating() initialized the task 1632 * for the destination sched. The task stays on its current sched in the source 1633 * cgroup. Undo the destination's init. 1634 */ 1635 static void scx_cgroup_task_migrate_canceled(struct cgroup_task_migrate_ctx *ctx) 1636 { 1637 struct task_struct *p = ctx->task; 1638 struct scx_sched *to; 1639 struct rq *rq; 1640 struct rq_flags rf; 1641 1642 if (!scx_cgroup_enabled) 1643 return; 1644 1645 to = scx_cgroup_sched(ctx->dst_dcgrp); 1646 if (scx_task_on_sched(to, p)) 1647 return; 1648 1649 rq = task_rq_lock(p, &rf); 1650 scx_sub_init_cancel_task(to, p); 1651 task_rq_unlock(rq, p, &rf); 1652 } 1653 1654 static s32 scx_cgroup_lifetime_notify(struct notifier_block *nb, 1655 unsigned long action, void *data) 1656 { 1657 struct cgroup *cgrp = data; 1658 struct cgroup *parent = cgroup_parent(cgrp); 1659 struct scx_sched *sch; 1660 1661 if (!cgroup_on_dfl(cgrp)) 1662 return NOTIFY_OK; 1663 1664 switch (action) { 1665 case CGROUP_LIFETIME_ONLINE: 1666 /* inherit ->scx_sched from $parent */ 1667 if (parent) 1668 rcu_assign_pointer(cgrp->scx_sched, scx_cgroup_sched(parent)); 1669 break; 1670 case CGROUP_LIFETIME_OFFLINE: 1671 /* if there is a sched attached, shoot it down */ 1672 sch = scx_cgroup_sched(cgrp); 1673 if (sch && sch->cgrp == cgrp) 1674 scx_exit(sch, SCX_EXIT_UNREG_KERN, 1675 SCX_ECODE_RSN_CGROUP_OFFLINE, 1676 "cgroup %llu going offline", cgroup_id(cgrp)); 1677 break; 1678 } 1679 1680 return NOTIFY_OK; 1681 } 1682 1683 static struct notifier_block scx_cgroup_lifetime_nb = { 1684 .notifier_call = scx_cgroup_lifetime_notify, 1685 }; 1686 1687 static s32 scx_cgroup_task_notify(struct notifier_block *nb, 1688 unsigned long action, void *data) 1689 { 1690 struct cgroup_task_migrate_ctx *ctx = data; 1691 1692 switch (action) { 1693 case CGROUP_TASK_MIGRATING: 1694 return scx_cgroup_task_migrating(ctx); 1695 case CGROUP_TASK_MIGRATED: 1696 scx_cgroup_task_migrated(ctx); 1697 break; 1698 case CGROUP_TASK_MIGRATE_CANCELED: 1699 scx_cgroup_task_migrate_canceled(ctx); 1700 break; 1701 } 1702 1703 return NOTIFY_OK; 1704 } 1705 1706 static struct notifier_block scx_cgroup_task_nb = { 1707 .notifier_call = scx_cgroup_task_notify, 1708 }; 1709 1710 static s32 __init scx_cgroup_notifier_init(void) 1711 { 1712 s32 ret; 1713 1714 ret = blocking_notifier_chain_register(&cgroup_lifetime_notifier, 1715 &scx_cgroup_lifetime_nb); 1716 if (ret) 1717 return ret; 1718 1719 return blocking_notifier_chain_register(&cgroup_task_notifier, 1720 &scx_cgroup_task_nb); 1721 } 1722 core_initcall(scx_cgroup_notifier_init); 1723 1724 static void scx_pstack_recursion(struct bpf_prog *prog, const char *op) 1725 { 1726 struct scx_sched *sch; 1727 1728 guard(rcu)(); 1729 sch = scx_prog_sched(prog->aux); 1730 if (unlikely(!sch)) 1731 return; 1732 1733 scx_error(sch, "%s recursion detected", op); 1734 } 1735 1736 void scx_pstack_recursion_on_dispatch(struct bpf_prog *prog) 1737 { 1738 scx_pstack_recursion(prog, "dispatch"); 1739 } 1740 1741 void scx_pstack_recursion_on_caps_updated(struct bpf_prog *prog) 1742 { 1743 scx_pstack_recursion(prog, "sub_caps_updated"); 1744 } 1745 1746 __bpf_kfunc_start_defs(); 1747 1748 /** 1749 * scx_bpf_sub_dispatch - Trigger dispatching on a child scheduler 1750 * @cgroup_id: cgroup ID of the child scheduler to dispatch 1751 * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs 1752 * 1753 * Allows a parent scheduler to trigger dispatching on one of its direct 1754 * child schedulers. The child scheduler runs its dispatch operation to 1755 * move tasks from dispatch queues to the local runqueue. 1756 * 1757 * Returns: true on success, false if cgroup_id is invalid, not a direct 1758 * child, or caller lacks dispatch permission. 1759 */ 1760 __bpf_kfunc bool scx_bpf_sub_dispatch(u64 cgroup_id, const struct bpf_prog_aux *aux) 1761 { 1762 struct rq *this_rq = this_rq(); 1763 struct scx_sched *parent, *child; 1764 1765 guard(rcu)(); 1766 parent = scx_prog_sched(aux); 1767 if (unlikely(!parent)) 1768 return false; 1769 1770 child = scx_find_sub_sched(cgroup_id); 1771 1772 if (unlikely(!child)) 1773 return false; 1774 1775 if (unlikely(scx_parent(child) != parent)) { 1776 scx_error(parent, "trying to dispatch a distant sub-sched on cgroup %llu", 1777 cgroup_id); 1778 return false; 1779 } 1780 1781 /* 1782 * Skip a child that does not effectively hold the base cap on this cpu: 1783 * its inserts would only be rejected. ecaps are synced at the top of 1784 * balance_one() before dispatch, so this reflects the in-effect state. 1785 */ 1786 if (scx_missing_caps(child, cpu_of(this_rq), SCX_CAP_BASE)) 1787 return false; 1788 1789 return scx_dispatch_sched(child, this_rq, this_rq->scx.sub_dispatch_prev, 1790 true); 1791 } 1792 1793 /* Validate common inputs. On success, *parent_out and *child_out are set. */ 1794 static s32 sub_cap_preamble(u64 cgroup_id, u64 caps, const struct bpf_prog_aux *aux, 1795 struct scx_sched **parent_out, struct scx_sched **child_out) 1796 { 1797 struct scx_sched *parent, *child; 1798 1799 parent = scx_prog_sched(aux); 1800 if (unlikely(!parent)) 1801 return -ENODEV; 1802 1803 if (!scx_is_cid_type()) { 1804 scx_error(parent, "sub-cap kfuncs require a cid-form scheduler"); 1805 return -EOPNOTSUPP; 1806 } 1807 1808 child = scx_find_sub_sched(cgroup_id); 1809 if (unlikely(!child)) 1810 return -ENODEV; 1811 1812 if (unlikely(scx_parent(child) != parent)) { 1813 scx_error(parent, "%s: sub-%llu is not a direct child", 1814 parent->cgrp_path, cgroup_id); 1815 return -EINVAL; 1816 } 1817 1818 if (unlikely(caps & ~__SCX_CAP_ALL)) { 1819 scx_error(parent, "invalid caps 0x%llx", caps); 1820 return -EINVAL; 1821 } 1822 1823 *parent_out = parent; 1824 *child_out = child; 1825 return 0; 1826 } 1827 1828 /** 1829 * scx_bpf_sub_grant - Grant @caps on @cmask__ign's cids to a direct child 1830 * @cgroup_id: cgroup id of the direct child sub-sched 1831 * @caps: bitmask of SCX_CAP_* to grant 1832 * @cmask__ign: cid cmask to grant @caps on (arena pointer) 1833 * @denied_out__ign: optional arena cmask accumulating refused cids 1834 * @aux: implicit BPF argument 1835 * 1836 * A cid in @cmask__ign is granted to the child only if the parent holds every 1837 * requested cap on it. Refused cids are OR'd into @denied_out__ign when 1838 * provided. Refusals outside @denied_out__ign's range are not recorded. 1839 * 1840 * All-or-nothing keeps the caller-visible result binary per cid, so 1841 * @denied_out__ign is one mask to interpret rather than a per-cap matrix. 1842 * 1843 * Return 0 on full success, -EPERM if any cid was refused, or a negative 1844 * errno on other failures. 1845 */ 1846 __bpf_kfunc s32 scx_bpf_sub_grant(u64 cgroup_id, u64 caps, 1847 const struct scx_cmask *cmask__ign, 1848 struct scx_cmask *denied_out__ign, 1849 const struct bpf_prog_aux *aux) 1850 { 1851 struct scx_cmask_ref ref, denied_ref; 1852 struct scx_sched *parent, *child; 1853 bool any_denied = false; 1854 LIST_HEAD(to_deliver); 1855 s32 si, ret; 1856 1857 guard(irqsave)(); 1858 1859 ret = sub_cap_preamble(cgroup_id, caps, aux, &parent, &child); 1860 if (ret) 1861 return ret; 1862 1863 ret = scx_cmask_ref_init(parent, cmask__ign, &ref); 1864 if (ret) { 1865 scx_error(parent, "invalid cmask (%d)", ret); 1866 return ret; 1867 } 1868 1869 if (denied_out__ign) { 1870 ret = scx_cmask_ref_init(parent, denied_out__ign, &denied_ref); 1871 if (ret) { 1872 scx_error(parent, "invalid denied_out (%d)", ret); 1873 return ret; 1874 } 1875 } 1876 1877 /* apply the grant one shard at a time */ 1878 for (si = ref.shard_first; si < ref.shard_end; si++) { 1879 SCX_CMASK_DEFINE_SHARD(slice, 0, SCX_CID_SHARD_MAX_CPUS); 1880 struct scx_pshard *pps = parent->pshard[si]; 1881 struct scx_pshard *cps = child->pshard[si]; 1882 u64 granted_caps = 0; 1883 u32 cap_bit; 1884 1885 scx_cmask_ref_shard(&ref, si, slice); 1886 if (scx_cmask_empty(slice)) 1887 continue; 1888 1889 SCX_CMASK_DEFINE_SHARD(granted_cids, slice->base, slice->nr_cids); 1890 SCX_CMASK_DEFINE_SHARD(changed_cids, slice->base, slice->nr_cids); 1891 SCX_CMASK_DEFINE_SHARD(delta, slice->base, slice->nr_cids); 1892 1893 scx_cmask_copy(granted_cids, slice); 1894 1895 scoped_guard (raw_spinlock, &pps->lock) { 1896 guard(raw_spinlock_nested)(&cps->lock); 1897 1898 /* 1899 * Narrow granted_cids to cids the parent holds every 1900 * requested cap on. All-or-nothing per cid. 1901 */ 1902 scx_for_each_cap_bit(cap_bit, caps) 1903 scx_cmask_and(granted_cids, &pps->caps[cap_bit].cmask); 1904 1905 /* 1906 * For each requested cap, fold the newly-set cids into 1907 * the child and accumulate the delta. 1908 */ 1909 scx_for_each_cap_bit(cap_bit, caps) { 1910 struct scx_cmask *ccm = &cps->caps[cap_bit].cmask; 1911 1912 scx_cmask_copy(delta, granted_cids); 1913 scx_cmask_andnot(delta, ccm); 1914 if (scx_cmask_empty(delta)) 1915 continue; 1916 1917 scx_cmask_or(ccm, delta); 1918 scx_cmask_or(changed_cids, delta); 1919 granted_caps |= BIT_U64(cap_bit); 1920 } 1921 1922 if (granted_caps) { 1923 s32 cid; 1924 1925 caps_updated_record(cps, changed_cids, granted_caps, 1926 &to_deliver); 1927 /* 1928 * The sync arms an update_idle() re-notify if 1929 * the cid gains baseline access, so the holder 1930 * learns of an already-idle cid. 1931 */ 1932 scx_cmask_for_each_cid(cid, changed_cids) 1933 queue_sync_ecaps(child, cid); 1934 } 1935 } 1936 1937 /* record cids that didn't make it through into @denied_out */ 1938 if (!scx_cmask_subset(slice, granted_cids)) { 1939 any_denied = true; 1940 if (denied_out__ign) { 1941 SCX_CMASK_DEFINE_SHARD(denied, slice->base, slice->nr_cids); 1942 1943 scx_cmask_copy(denied, slice); 1944 scx_cmask_andnot(denied, granted_cids); 1945 scx_cmask_ref_or(&denied_ref, denied); 1946 } 1947 } 1948 } 1949 1950 caps_updated_deliver(&to_deliver); 1951 1952 return any_denied ? -EPERM : 0; 1953 } 1954 1955 /** 1956 * scx_bpf_sub_revoke - Revoke @caps on @cmask__ign's cids from @child 1957 * @cgroup_id: cgroup id of the direct child sub-sched 1958 * @caps: bitmask of SCX_CAP_* to revoke 1959 * @cmask__ign: cid cmask to revoke @caps on (arena pointer) 1960 * @aux: implicit BPF argument 1961 * 1962 * Clear @caps bits on @cmask__ign from the child named by @cgroup_id and all 1963 * its descendants. The origin parent's pshard lock is held across the subtree 1964 * walk so a concurrent grant from the origin parent observes the revoked 1965 * state. 1966 */ 1967 __bpf_kfunc void scx_bpf_sub_revoke(u64 cgroup_id, u64 caps, 1968 const struct scx_cmask *cmask__ign, 1969 const struct bpf_prog_aux *aux) 1970 { 1971 struct scx_cmask_ref ref; 1972 struct scx_sched *parent, *child, *pos; 1973 LIST_HEAD(to_deliver); 1974 s32 si, ret; 1975 1976 guard(irqsave)(); 1977 1978 if (sub_cap_preamble(cgroup_id, caps, aux, &parent, &child)) 1979 return; 1980 1981 ret = scx_cmask_ref_init(parent, cmask__ign, &ref); 1982 if (ret) { 1983 scx_error(parent, "invalid cmask (%d)", ret); 1984 return; 1985 } 1986 1987 /* per-shard, walk child's subtree and clear @caps */ 1988 for (si = ref.shard_first; si < ref.shard_end; si++) { 1989 SCX_CMASK_DEFINE_SHARD(slice, 0, SCX_CID_SHARD_MAX_CPUS); 1990 1991 scx_cmask_ref_shard(&ref, si, slice); 1992 if (scx_cmask_empty(slice)) 1993 continue; 1994 1995 /* 1996 * Pre-order with subtree skip: a descendant that cleared 1997 * nothing means no descendant of it can hold @caps on these 1998 * cids either. 1999 */ 2000 guard(raw_spinlock)(&parent->pshard[si]->lock); 2001 pos = scx_next_descendant_pre(NULL, child); 2002 while (pos) { 2003 struct scx_pshard *ps = pos->pshard[si]; 2004 SCX_CMASK_DEFINE_SHARD(changed_cids, slice->base, slice->nr_cids); 2005 SCX_CMASK_DEFINE_SHARD(delta, slice->base, slice->nr_cids); 2006 u64 revoked_caps = 0; 2007 u32 cap_bit; 2008 2009 scoped_guard (raw_spinlock_nested, &ps->lock) { 2010 /* 2011 * For each cap, clear lost cids and accumulate 2012 * the per-cap diff for notification. 2013 */ 2014 scx_for_each_cap_bit(cap_bit, caps) { 2015 struct scx_cmask *cm = &ps->caps[cap_bit].cmask; 2016 2017 scx_cmask_copy(delta, cm); 2018 scx_cmask_and(delta, slice); 2019 if (scx_cmask_empty(delta)) 2020 continue; 2021 2022 scx_cmask_andnot(cm, delta); 2023 scx_cmask_or(changed_cids, delta); 2024 revoked_caps |= BIT_U64(cap_bit); 2025 } 2026 2027 if (revoked_caps) { 2028 s32 cid; 2029 2030 caps_updated_record(ps, changed_cids, revoked_caps, 2031 &to_deliver); 2032 scx_cmask_for_each_cid(cid, changed_cids) 2033 queue_sync_ecaps(pos, cid); 2034 } 2035 } 2036 2037 if (revoked_caps) 2038 pos = scx_next_descendant_pre(pos, child); 2039 else 2040 pos = scx_skip_subtree_pre(pos, child); 2041 } 2042 } 2043 2044 caps_updated_deliver(&to_deliver); 2045 } 2046 2047 /** 2048 * scx_bpf_sub_caps - Read self's or a direct child's cap cmasks 2049 * @cgroup_id: 0 for self, or a direct child's cgroup id 2050 * @caps: one or more SCX_CAP_* bits 2051 * @out__ign: arena cmask to receive the union of @caps within its range 2052 * @aux: implicit BPF argument 2053 * 2054 * Read the cap cmasks granted on each cid for self (@cgroup_id 0) or a direct 2055 * child - the literal granted set. A sched can read only itself or a direct 2056 * child. 2057 * 2058 * Return 0, -ENODEV if @cgroup_id names no direct child, or -EINVAL on bad 2059 * inputs. 2060 */ 2061 __bpf_kfunc s32 scx_bpf_sub_caps(u64 cgroup_id, u64 caps, struct scx_cmask *out__ign, 2062 const struct bpf_prog_aux *aux) 2063 { 2064 struct scx_cmask_ref ref; 2065 struct scx_sched *sch, *target; 2066 struct scx_pshard **pshard; 2067 s32 si, ret; 2068 2069 guard(irqsave)(); 2070 2071 sch = scx_prog_sched(aux); 2072 if (unlikely(!sch)) 2073 return -ENODEV; 2074 2075 if (!scx_is_cid_type()) { 2076 scx_error(sch, "sub-cap kfuncs require a cid-form scheduler"); 2077 return -EOPNOTSUPP; 2078 } 2079 2080 if (unlikely(caps & ~__SCX_CAP_ALL)) { 2081 scx_error(sch, "invalid caps 0x%llx", caps); 2082 return -EINVAL; 2083 } 2084 2085 /* @cgroup_id 0 reads self, otherwise a direct child */ 2086 if (cgroup_id) { 2087 target = scx_find_sub_sched(cgroup_id); 2088 if (unlikely(!target)) 2089 return -ENODEV; 2090 if (unlikely(scx_parent(target) != sch)) { 2091 scx_error(sch, "%s: sub-%llu is not a direct child", 2092 sch->cgrp_path, cgroup_id); 2093 return -EINVAL; 2094 } 2095 } else { 2096 target = sch; 2097 } 2098 2099 /* 2100 * The target's caps storage may not be set up yet (e.g. a self-read 2101 * during ops.init_cids()). Pairs with the publish in 2102 * scx_alloc_pshards(): a non-NULL pshard has every element set and the 2103 * acquire also orders the cid table reads below against it. 2104 */ 2105 pshard = smp_load_acquire(&target->pshard); 2106 if (unlikely(!pshard)) { 2107 scx_error(sch, "scx_bpf_sub_caps() called before caps storage is initialized"); 2108 return -ENODEV; 2109 } 2110 2111 ret = scx_cmask_ref_init(sch, out__ign, &ref); 2112 if (ret) { 2113 scx_error(sch, "invalid out (%d)", ret); 2114 return ret; 2115 } 2116 2117 for (si = ref.shard_first; si < ref.shard_end; si++) { 2118 const struct scx_cid_shard *shard = 2119 &rcu_dereference_all(scx_cid_shard_ranges)[si]; 2120 SCX_CMASK_DEFINE_SHARD(local_out, shard->base_cid, shard->nr_cids); 2121 u32 cap_bit; 2122 2123 scx_for_each_cap_bit(cap_bit, caps) 2124 scx_cmask_or(local_out, &pshard[si]->caps[cap_bit].cmask); 2125 scx_cmask_ref_copy(&ref, local_out); 2126 } 2127 return 0; 2128 } 2129 2130 /** 2131 * scx_bpf_sub_kill_bstr - Kill a direct child sub-scheduler 2132 * @cgroup_id: cgroup id of the direct child to kill 2133 * @fmt: reason message format string 2134 * @data: format string parameters packaged using ___bpf_fill() macro 2135 * @data__sz: @data len, must end in '__sz' for the verifier 2136 * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs 2137 * 2138 * Evict a direct child sub-scheduler, disabling it with the supplied reason. 2139 * The child and its subtree are torn down asynchronously through the usual 2140 * disable path. 2141 * 2142 * Unlike scx_bpf_exit(), no exit code is taken: the child is a separate 2143 * scheduler with its own exit-code semantics, so a code chosen by the parent 2144 * would have no defined meaning. The reason string carries the intent. 2145 * 2146 * Return 0 on success or -ENODEV if @cgroup_id names no sub-scheduler, which 2147 * can race with the child detaching on its own and so is not a scheduler error. 2148 * Naming a sched that exists but is not a direct child aborts the parent. 2149 */ 2150 __printf(2, 0) 2151 __bpf_kfunc s32 scx_bpf_sub_kill_bstr(u64 cgroup_id, char *fmt, 2152 unsigned long long *data, u32 data__sz, 2153 const struct bpf_prog_aux *aux) 2154 { 2155 struct scx_sched *parent, *child; 2156 s32 ret; 2157 2158 guard(rcu)(); 2159 2160 parent = scx_prog_sched(aux); 2161 if (unlikely(!parent)) 2162 return -ENODEV; 2163 2164 if (!scx_is_cid_type()) { 2165 scx_error(parent, "sub-cap kfuncs require a cid-form scheduler"); 2166 return -EOPNOTSUPP; 2167 } 2168 2169 child = scx_find_sub_sched(cgroup_id); 2170 if (unlikely(!child)) 2171 return -ENODEV; 2172 2173 if (unlikely(scx_parent(child) != parent)) { 2174 scx_error(parent, "%s: sub-%llu is not a direct child", 2175 parent->cgrp_path, cgroup_id); 2176 return -EINVAL; 2177 } 2178 2179 guard(raw_spinlock_irqsave)(&scx_exit_bstr_buf_lock); 2180 ret = scx_bstr_format(parent, &scx_exit_bstr_buf, fmt, data, data__sz); 2181 if (ret < 0) 2182 return ret; 2183 scx_exit(child, SCX_EXIT_PARENT_KILL, 0, "%s", scx_exit_bstr_buf.line); 2184 return 0; 2185 } 2186 2187 __bpf_kfunc_end_defs(); 2188 2189 #endif /* CONFIG_EXT_SUB_SCHED */ 2190