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, and there's no repeat limit here. 323 * Rejection can't happen for root, and sub-scheds can be safely ejected after 324 * triggering the stall watchdog. 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(scx_root, 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 *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 cid = __scx_cpu_to_cid(cpu_of(rq)); 656 shard = rcu_dereference_all(scx_cid_to_shard)[cid]; 657 658 scx_for_each_descendant_pre(pos, scx_root) { 659 struct scx_pshard *ps; 660 661 /* root holds every cap and never uses ecaps */ 662 if (pos == scx_root) 663 continue; 664 665 ps = pos->pshard[shard]; 666 guard(raw_spinlock)(&ps->lock); 667 queue_sync_ecaps(pos, cid); 668 } 669 } 670 671 /* 672 * A cpu is going down. Zero each sub-sched's in-effect ecaps so cap checks 673 * treat the cpu as capless while offline. Pending and late-queued syncs are 674 * discarded at consumption by scx_process_sync_ecaps() while the cpu is 675 * inactive. Leave reported_ecaps. Ownership is unchanged, so the 676 * scx_online_ecaps() reseed reports only a genuine delta. No callback fires 677 * here. 678 */ 679 void scx_offline_ecaps(struct rq *rq) 680 { 681 s32 cpu = cpu_of(rq); 682 struct scx_sched *pos; 683 684 guard(rq_lock_irqsave)(rq); 685 686 scx_for_each_descendant_pre(pos, scx_root) { 687 /* root holds every cap and never uses ecaps */ 688 if (pos == scx_root) 689 continue; 690 691 WRITE_ONCE(per_cpu_ptr(pos->pcpu, cpu)->ecaps, 0); 692 } 693 } 694 695 /* 696 * @pcpu's sched was unhashed before the grace period, so nothing re-queues its 697 * sync node. Remove the node from @rq's pending list so the pcpu can be freed. 698 */ 699 void scx_discard_ecaps_to_sync(s32 cpu, struct scx_sched_pcpu *pcpu) 700 { 701 struct rq *rq = cpu_rq(cpu); 702 struct llist_node *head = NULL, *tail = NULL; 703 struct llist_node *pos, *tmp; 704 705 /* 706 * llist can't unlink a single node. Take all queued nodes, drop @pcpu's 707 * and resplice the rest. Nodes in the taken batch read as on-list 708 * throughout, so queue_sync_ecaps() stays correct. 709 */ 710 if (llist_on_list(&pcpu->ecaps_to_sync_node)) { 711 scoped_guard (rq_lock_irqsave, rq) { 712 llist_for_each_safe(pos, tmp, llist_del_all(&rq->scx.ecaps_to_sync)) { 713 if (pos == &pcpu->ecaps_to_sync_node) { 714 init_llist_node(pos); 715 } else { 716 pos->next = head; 717 head = pos; 718 if (!tail) 719 tail = pos; 720 } 721 } 722 if (head) 723 llist_add_batch(head, tail, &rq->scx.ecaps_to_sync); 724 } 725 } 726 727 /* 728 * An in-flight scx_process_sync_ecaps() batch may still hold the node 729 * privately across dispatch-induced rq unlocks, reading as on-list. 730 * 731 * Because a bypassing sched gets no op call, init_llist_node() and all 732 * @pcpu accesses share one contiguous lock hold, off-list under the rq 733 * lock means @pcpu won't be accessed again. 734 */ 735 while (true) { 736 scoped_guard (rq_lock_irqsave, rq) { 737 if (!llist_on_list(&pcpu->ecaps_to_sync_node)) 738 return; 739 } 740 cpu_relax(); 741 } 742 } 743 744 /** 745 * scx_discard_stale_ecaps_syncs - Discard ecaps syncs from earlier schedulers 746 * 747 * To be called during root enable before the scheduler goes live. An earlier 748 * root's sub-sched may not have gone through its RCU free path yet (e.g. a 749 * still-open link fd defers it) and can leave queued ecaps syncs behind. 750 * Processing them would decode the dead sched's pshards with the current cid 751 * layout. Discard them instead. The backing scx_sched_pcpu's are still 752 * allocated as the free path removes ecaps_to_sync_node before freeing. 753 */ 754 void scx_discard_stale_ecaps_syncs(void) 755 { 756 s32 cpu; 757 758 for_each_possible_cpu(cpu) { 759 struct rq *rq = cpu_rq(cpu); 760 761 guard(rq_lock_irqsave)(rq); 762 discard_queued_syncs(rq); 763 } 764 } 765 766 static DECLARE_WAIT_QUEUE_HEAD(scx_unlink_waitq); 767 768 void drain_descendants(struct scx_sched *sch) 769 { 770 /* 771 * Child scheds that finished the critical part of disabling will take 772 * themselves off @sch->children. Wait for it to drain. As propagation 773 * is recursive, empty @sch->children means that all proper descendant 774 * scheds reached unlinking stage. 775 */ 776 wait_event(scx_unlink_waitq, list_empty(&sch->children)); 777 } 778 779 /** 780 * scx_rehome_task - Move a task to a sched it has been initialized for 781 * @to: sched taking over @p, @p's init on it already complete 782 * @p: task to re-home 783 * 784 * Exit @p from its current sched and switch it over to @to, overriding the 785 * state to %SCX_TASK_READY to account for the already completed init. A task 786 * on a non-ext class, possible under an %SCX_OPS_SWITCH_PARTIAL root, stays 787 * %READY and is enabled by switching_to_scx() if it switches over. 788 */ 789 static void scx_rehome_task(struct scx_sched *to, struct task_struct *p) 790 { 791 lockdep_assert_held(&p->pi_lock); 792 lockdep_assert_rq_held(task_rq(p)); 793 794 scoped_guard (sched_change, p, DEQUEUE_SAVE | DEQUEUE_MOVE) { 795 scx_disable_and_exit_task(scx_task_sched(p), p); 796 scx_set_task_state(p, SCX_TASK_INIT_BEGIN); 797 scx_set_task_state(p, SCX_TASK_INIT); 798 scx_set_task_sched(p, to); 799 scx_set_task_state(p, SCX_TASK_READY); 800 if (p->sched_class == &ext_sched_class) 801 scx_enable_task(to, p); 802 } 803 } 804 805 /** 806 * scx_punt_task - Hand a task to a failed sched without initialization 807 * @to: failed and bypassed sched taking custody of @p 808 * @p: task to punt 809 * 810 * Take @p off its current sched and put it on @to at %SCX_TASK_NONE. @to is 811 * dying and its teardown will re-home @p properly. 812 * 813 * Used when @to must take over @p but failed to initialize it. Bypass keeps 814 * scheduling decisions away from @to but @p can still trigger its task ops, 815 * which may confuse the BPF side. @to is dying anyway. The exit paths skip 816 * %NONE tasks (see __scx_disable_and_exit_task() and switched_from_scx()). 817 */ 818 static void scx_punt_task(struct scx_sched *to, struct task_struct *p) 819 { 820 lockdep_assert_held(&p->pi_lock); 821 lockdep_assert_rq_held(task_rq(p)); 822 WARN_ON_ONCE(!READ_ONCE(to->bypass_depth)); 823 824 scoped_guard (sched_change, p, DEQUEUE_SAVE | DEQUEUE_MOVE) { 825 scx_disable_and_exit_task(scx_task_sched(p), p); 826 scx_set_task_sched(p, to); 827 } 828 } 829 830 static void scx_fail_parent(struct scx_sched *sch, 831 struct task_struct *failed, s32 fail_code) 832 { 833 struct scx_sched *parent = scx_parent(sch); 834 struct scx_task_iter sti; 835 struct task_struct *p; 836 837 scx_error(parent, "ops.init_task() failed (%d) for %s[%d] while disabling a sub-scheduler", 838 fail_code, failed->comm, failed->pid); 839 840 /* 841 * Once $parent is bypassed, tasks can be punted into it. This may 842 * cause downstream failures on the BPF side but $parent is dying 843 * anyway. 844 */ 845 scx_bypass(parent, true); 846 847 scx_task_iter_start(&sti, sch->cgrp); 848 while ((p = scx_task_iter_next_locked(&sti))) { 849 if (scx_task_on_sched(parent, p)) 850 continue; 851 852 scx_punt_task(parent, p); 853 } 854 scx_task_iter_stop(&sti); 855 } 856 857 #ifdef CONFIG_EXT_GROUP_SCHED 858 /** 859 * scx_cgroup_claim_subtree - Claim the subtree's cgroups for an enabling sub 860 * @sch: sub-scheduler being enabled 861 * 862 * Called while enabling @sch, after the subtree's cgrp->scx_sched's are pointed 863 * at @sch and before any task is claimed. This mirrors root enable's 864 * cgroups-before-tasks order. The ops.init_task() args are task_group-granular 865 * and can still reference a cgroup outside the handed-over set when the cpu 866 * controller is coarser than the sub topology or mounted on cgroup1. 867 * 868 * First init each of the parent sched's subtree cgroups on @sch, and only then 869 * exit them from the parent, so that a failed init can be unwound with the 870 * parent untouched. The both-inited transient is invisible outside 871 * scx_cgroup_lock(). %SCX_TG_SUB_INIT tracks the first pass's progress. 872 * %SCX_TG_INITED stays set throughout, except for a task_group whose 873 * ops.cgroup_init() failed on the parent (see scx_cgroup_return_subtree()): 874 * there is nothing to exit from the parent and %SCX_TG_INITED is set back with 875 * the transfer. 876 * 877 * Dying but not yet offlined task_groups are included: a removed cgroup keeps 878 * hosting scheduling events until its dying tasks finish their final context 879 * switches, so it still needs to be inited on a sched, and its offline-time 880 * ops.cgroup_exit() follows the last of those events. 881 * 882 * Return 0 on success, -errno on failure. On failure, @sch has been 883 * scx_error()'d and is left with no cgroups. 884 */ 885 static s32 scx_cgroup_claim_subtree(struct scx_sched *sch) 886 { 887 struct cgroup *sub_cgrp = sch_cgroup(sch); 888 struct cgroup_subsys_state *ecss = cgroup_e_css(sub_cgrp, &cpu_cgrp_subsys); 889 struct scx_sched *parent = scx_parent(sch); 890 struct cgroup_subsys_state *css; 891 int ret; 892 893 css_for_each_descendant_pre(css, ecss) { 894 struct task_group *tg = css_tg(css); 895 struct scx_cgroup_init_args args = { 896 .weight = tg->scx.weight, 897 .bw_period_us = tg->scx.bw_period_us, 898 .bw_quota_us = tg->scx.bw_quota_us, 899 .bw_burst_us = tg->scx.bw_burst_us, 900 }; 901 902 if (tg->scx.sched != parent || 903 !cgroup_is_descendant(css->cgroup, sub_cgrp)) 904 continue; 905 906 if (SCX_HAS_OP(sch, cgroup_init)) { 907 ret = SCX_CALL_OP_RET(sch, cgroup_init, NULL, css->cgroup, &args); 908 if (ret) { 909 scx_error(sch, "ops.cgroup_init() failed (%d)", ret); 910 goto err; 911 } 912 } 913 tg->scx.flags |= SCX_TG_SUB_INIT; 914 } 915 916 css_for_each_descendant_post(css, ecss) { 917 struct task_group *tg = css_tg(css); 918 919 /* 920 * SUB_INIT is pass 1's progress mark: pass 2 and the err path 921 * must visit exactly the tgs pass 1 inited. 922 */ 923 if (!(tg->scx.flags & SCX_TG_SUB_INIT)) 924 continue; 925 926 /* skip the exit if the parent's ops.cgroup_init() failed */ 927 if ((tg->scx.flags & SCX_TG_INITED) && SCX_HAS_OP(parent, cgroup_exit)) 928 SCX_CALL_OP(parent, cgroup_exit, NULL, css->cgroup); 929 tg->scx.sched = sch; 930 tg->scx.flags |= SCX_TG_INITED; 931 tg->scx.flags &= ~SCX_TG_SUB_INIT; 932 } 933 934 return 0; 935 936 err: 937 css_for_each_descendant_post(css, ecss) { 938 struct task_group *tg = css_tg(css); 939 940 if (!(tg->scx.flags & SCX_TG_SUB_INIT)) 941 continue; 942 943 if (SCX_HAS_OP(sch, cgroup_exit)) 944 SCX_CALL_OP(sch, cgroup_exit, NULL, css->cgroup); 945 tg->scx.flags &= ~SCX_TG_SUB_INIT; 946 } 947 return ret; 948 } 949 950 /** 951 * scx_cgroup_return_subtree - Return the subtree's cgroups to the parent sched 952 * @sch: sub-scheduler being disabled 953 * 954 * Called while disabling @sch, after the subtree's cgrp->scx_sched's are reset 955 * to the parent sched and before tasks are re-homed, mirroring root disable's 956 * cgroups-before-tasks teardown order. The reverse of 957 * scx_cgroup_claim_subtree(): exit @sch's cgroups from @sch, then init them on 958 * the parent with the current tg->scx.* values, resyncing settings that changed 959 * while @sch had them. 960 * 961 * When an init on the parent fails, the parent is failed - the same policy as 962 * task re-homing. The remaining task_groups are punted: they move to the parent 963 * anyway with %SCX_TG_INITED cleared, as ops.cgroup_init() failed or never ran 964 * for them. A punted task_group gets no cgroup ops. The dying parent's own 965 * disable moves it one sched up, initing it there. Root ends the chain: root 966 * teardown drops cgroup ops entirely and the next enable's bulk init re-inits 967 * every online task_group. 968 * 969 * The task re-home that follows still delivers ops.init_task() to the dying 970 * parent, including for tasks in punted cgroups it never inited - tolerated 971 * like the downstream failures of task punting (see scx_punt_task()). 972 */ 973 static void scx_cgroup_return_subtree(struct scx_sched *sch) 974 { 975 struct cgroup *sub_cgrp = sch_cgroup(sch); 976 struct cgroup_subsys_state *ecss = cgroup_e_css(sub_cgrp, &cpu_cgrp_subsys); 977 struct scx_sched *parent = scx_parent(sch); 978 struct cgroup_subsys_state *css; 979 bool parent_failed = false; 980 int ret; 981 982 css_for_each_descendant_post(css, ecss) { 983 struct task_group *tg = css_tg(css); 984 985 if (tg->scx.sched != sch || 986 !cgroup_is_descendant(css->cgroup, sub_cgrp)) 987 continue; 988 989 /* skip the exit if @sch's ops.cgroup_init() failed for the tg */ 990 if ((tg->scx.flags & SCX_TG_INITED) && SCX_HAS_OP(sch, cgroup_exit)) 991 SCX_CALL_OP(sch, cgroup_exit, NULL, css->cgroup); 992 tg->scx.sched = parent; 993 tg->scx.flags |= SCX_TG_SUB_INIT; 994 } 995 996 css_for_each_descendant_pre(css, ecss) { 997 struct task_group *tg = css_tg(css); 998 struct scx_cgroup_init_args args = { 999 .weight = tg->scx.weight, 1000 .bw_period_us = tg->scx.bw_period_us, 1001 .bw_quota_us = tg->scx.bw_quota_us, 1002 .bw_burst_us = tg->scx.bw_burst_us, 1003 }; 1004 1005 /* the first pass must have transferred everything */ 1006 WARN_ON_ONCE(tg->scx.sched == sch); 1007 1008 /* 1009 * SUB_INIT distinguishes the tgs pass 1 moved. The sched test 1010 * can't: a tg punted to the parent by an earlier failure would 1011 * also match. 1012 */ 1013 if (!(tg->scx.flags & SCX_TG_SUB_INIT)) 1014 continue; 1015 tg->scx.flags &= ~(SCX_TG_SUB_INIT | SCX_TG_INITED); 1016 1017 /* 1018 * A re-init on $parent failed. The task_groups from here on are 1019 * punted: they stay on the dying $parent with INITED clear and 1020 * move onward when it disables. 1021 */ 1022 if (parent_failed) 1023 continue; 1024 1025 if (SCX_HAS_OP(parent, cgroup_init)) { 1026 ret = SCX_CALL_OP_RET(parent, cgroup_init, NULL, css->cgroup, &args); 1027 if (ret) { 1028 scx_error(parent, "ops.cgroup_init() failed (%d) while disabling a sub-scheduler", 1029 ret); 1030 parent_failed = true; 1031 continue; 1032 } 1033 } 1034 tg->scx.flags |= SCX_TG_INITED; 1035 } 1036 } 1037 #else 1038 static inline s32 scx_cgroup_claim_subtree(struct scx_sched *sch) { return 0; } 1039 static inline void scx_cgroup_return_subtree(struct scx_sched *sch) {} 1040 #endif 1041 1042 void scx_sub_disable(struct scx_sched *sch) 1043 { 1044 struct scx_sched *parent = scx_parent(sch); 1045 struct scx_task_iter sti; 1046 struct task_struct *p; 1047 int ret; 1048 1049 /* 1050 * Guarantee forward progress and wait for descendants to be disabled. 1051 * To limit disruptions, $parent is not bypassed. Tasks are fully 1052 * prepped and then inserted back into $parent. 1053 */ 1054 scx_bypass(sch, true); 1055 drain_descendants(sch); 1056 1057 /* 1058 * Here, every runnable task is guaranteed to make forward progress and 1059 * we can safely use blocking synchronization constructs. Actually 1060 * disable ops. 1061 */ 1062 mutex_lock(&scx_enable_mutex); 1063 percpu_down_write(&scx_fork_rwsem); 1064 scx_cgroup_lock(); 1065 1066 /* 1067 * An enable that failed before scx_link_sched() never owned a cgroup or 1068 * task and won't be waited on by an ancestor's drain_descendants(). 1069 * Nothing to reparent and walking the tasks can misbehave as the task 1070 * ownership invariant (either owned by self or parent) does not hold. 1071 */ 1072 if (list_empty(&sch->sibling)) 1073 goto dump; 1074 1075 set_cgroup_sched(sch_cgroup(sch), parent); 1076 1077 /* 1078 * Return the subtree's cgroups before re-homing tasks so that any 1079 * ops.init_task() on $parent only sees cgroups it has initialized. 1080 */ 1081 scx_cgroup_return_subtree(sch); 1082 1083 scx_task_iter_start(&sti, sch->cgrp); 1084 while ((p = scx_task_iter_next_locked(&sti))) { 1085 struct rq *rq; 1086 struct rq_flags rf; 1087 1088 /* filter out duplicate visits */ 1089 if (scx_task_on_sched(parent, p)) 1090 continue; 1091 1092 /* 1093 * By the time control reaches here, all linked descendant 1094 * schedulers should have been disabled. 1095 */ 1096 WARN_ON_ONCE(!scx_task_on_sched(sch, p)); 1097 1098 /* 1099 * @p is pinned by the iter: css_task_iter_next() takes a 1100 * reference and holds it until the next iter_next() call, so 1101 * @p->usage is guaranteed > 0. 1102 */ 1103 get_task_struct(p); 1104 1105 scx_task_iter_unlock(&sti); 1106 1107 /* 1108 * $p is READY or ENABLED on @sch. Initialize for $parent, 1109 * disable and exit from @sch, and then switch over to $parent. 1110 * 1111 * If a task fails to initialize for $parent, the only available 1112 * action is disabling $parent too. While this allows disabling 1113 * of a child sched to cause the parent scheduler to fail, the 1114 * failure can only originate from ops.init_task() of the 1115 * parent. A child can't directly affect the parent through its 1116 * own failures. 1117 */ 1118 ret = __scx_init_task(parent, p, NULL, false); 1119 if (ret) { 1120 scx_fail_parent(sch, p, ret); 1121 put_task_struct(p); 1122 break; 1123 } 1124 1125 rq = task_rq_lock(p, &rf); 1126 1127 if (scx_get_task_state(p) == SCX_TASK_DEAD) { 1128 /* 1129 * sched_ext_dead() raced us between __scx_init_task() 1130 * and this rq lock and ran exit_task() on @sch (the 1131 * sched @p was on at that point), not on $parent. 1132 * $parent's just-completed init is owed an exit_task() 1133 * and we issue it here. 1134 */ 1135 scx_sub_init_cancel_task(parent, p); 1136 task_rq_unlock(rq, p, &rf); 1137 put_task_struct(p); 1138 continue; 1139 } 1140 1141 scx_rehome_task(parent, p); 1142 1143 task_rq_unlock(rq, p, &rf); 1144 put_task_struct(p); 1145 } 1146 scx_task_iter_stop(&sti); 1147 1148 dump: 1149 scx_disable_dump(sch); 1150 1151 scx_cgroup_unlock(); 1152 percpu_up_write(&scx_fork_rwsem); 1153 1154 /* 1155 * All tasks are moved off of @sch but there may still be on-going 1156 * operations (e.g. ops.select_cpu()). Drain them by flushing RCU. Use 1157 * the expedited version as ancestors may be waiting in bypass mode. 1158 * Also, tell the parent that there is no need to keep running bypass 1159 * DSQs for us. 1160 */ 1161 synchronize_rcu_expedited(); 1162 scx_disable_bypass_dsp(sch); 1163 1164 scx_unlink_sched(sch); 1165 1166 mutex_unlock(&scx_enable_mutex); 1167 1168 /* 1169 * @sch is now unlinked from the parent's children list. Notify and call 1170 * ops.sub_detach/exit(). Note that ops.sub_detach/exit() must be called 1171 * after unlinking and releasing all locks. See scx_claim_exit(). 1172 */ 1173 wake_up_all(&scx_unlink_waitq); 1174 1175 if (parent->ops.sub_detach && sch->sub_attached) { 1176 struct scx_sub_detach_args sub_detach_args = { 1177 .ops = &sch->ops, 1178 .cgroup_path = sch->cgrp_path, 1179 }; 1180 SCX_CALL_OP(parent, sub_detach, NULL, 1181 &sub_detach_args); 1182 } 1183 1184 scx_log_sched_disable(sch); 1185 1186 if (sch->ops.exit) 1187 SCX_CALL_OP(sch, exit, NULL, sch->exit_info); 1188 1189 /* 1190 * @sch's non-ops programs such as timers and tracers can fire after 1191 * ops.exit(). Now that exit is complete, stop scx_prog_sched() from 1192 * resolving to @sch and drain in-flight resolvers. 1193 */ 1194 WRITE_ONCE(sch->dead, true); 1195 synchronize_rcu(); 1196 1197 if (sch->sub_kset) 1198 kobject_del(&sch->sub_kset->kobj); 1199 /* not added if enable failed before scx_sched_sysfs_add() */ 1200 if (sch->kobj.state_in_sysfs) 1201 kobject_del(&sch->kobj); 1202 } 1203 1204 /* verify that a scheduler can be attached to @cgrp and return the parent */ 1205 static struct scx_sched *find_parent_sched(struct cgroup *cgrp) 1206 { 1207 struct scx_sched *parent = cgrp->scx_sched; 1208 struct scx_sched *pos; 1209 1210 lockdep_assert_held(&scx_sched_lock); 1211 1212 /* can't attach twice to the same cgroup */ 1213 if (parent->cgrp == cgrp) 1214 return ERR_PTR(-EBUSY); 1215 1216 /* does $parent allow sub-scheds? */ 1217 if (!parent->ops.sub_attach) 1218 return ERR_PTR(-EOPNOTSUPP); 1219 1220 /* can't insert between $parent and its exiting children */ 1221 list_for_each_entry(pos, &parent->children, sibling) 1222 if (cgroup_is_descendant(pos->cgrp, cgrp)) 1223 return ERR_PTR(-EBUSY); 1224 1225 return parent; 1226 } 1227 1228 static bool assert_task_ready_or_enabled(struct task_struct *p) 1229 { 1230 u32 state = scx_get_task_state(p); 1231 1232 switch (state) { 1233 case SCX_TASK_READY: 1234 case SCX_TASK_ENABLED: 1235 return true; 1236 default: 1237 WARN_ONCE(true, "sched_ext: Invalid task state %d for %s[%d] during enabling sub sched", 1238 state, p->comm, p->pid); 1239 return false; 1240 } 1241 } 1242 1243 void scx_sub_enable_workfn(struct kthread_work *work) 1244 { 1245 struct scx_enable_cmd *cmd = container_of(work, struct scx_enable_cmd, work); 1246 struct sched_ext_ops *ops = cmd->ops; 1247 struct cgroup *cgrp; 1248 struct scx_sched *parent, *sch; 1249 struct scx_task_iter sti; 1250 struct task_struct *p; 1251 s32 i, ret; 1252 1253 mutex_lock(&scx_enable_mutex); 1254 1255 if (!scx_enabled()) { 1256 ret = -ENODEV; 1257 goto out_unlock; 1258 } 1259 1260 /* See scx_root_enable_workfn() for the @ops->priv check. */ 1261 if (rcu_access_pointer(ops->priv)) { 1262 ret = -EBUSY; 1263 goto out_unlock; 1264 } 1265 1266 cgrp = cgroup_get_from_id(ops->sub_cgroup_id); 1267 if (IS_ERR(cgrp)) { 1268 ret = PTR_ERR(cgrp); 1269 goto out_unlock; 1270 } 1271 1272 raw_spin_lock_irq(&scx_sched_lock); 1273 parent = find_parent_sched(cgrp); 1274 if (IS_ERR(parent)) { 1275 raw_spin_unlock_irq(&scx_sched_lock); 1276 ret = PTR_ERR(parent); 1277 goto out_put_cgrp; 1278 } 1279 kobject_get(&parent->kobj); 1280 raw_spin_unlock_irq(&scx_sched_lock); 1281 1282 /* 1283 * Flip the hot-path gates before ops->priv is published - the sub's 1284 * programs can e.g. kick cpus from that point on. The matching dec is 1285 * at the end of scx_sched_free_rcu_work(). 1286 */ 1287 static_branch_inc(&__scx_has_subs); 1288 1289 /* scx_alloc_and_add_sched() consumes @cgrp whether it succeeds or not */ 1290 sch = scx_alloc_and_add_sched(cmd, cgrp, parent); 1291 kobject_put(&parent->kobj); 1292 if (IS_ERR(sch)) { 1293 static_branch_dec(&__scx_has_subs); 1294 ret = PTR_ERR(sch); 1295 goto out_unlock; 1296 } 1297 1298 /* 1299 * Validate before scx_link_sched() publishes @sch, so an invalid sub 1300 * never becomes visible with an unallocated pshard. 1301 */ 1302 ret = scx_validate_ops(sch, ops); 1303 if (ret) 1304 goto err_disable; 1305 1306 /* 1307 * Allocate pshard[] before scx_link_sched() publishes @sch into the 1308 * parent's RCU children list. A concurrent revoke walking the tree 1309 * would otherwise dereference sch->pshard[si] while it's still NULL. 1310 * Unlike the root path, the cid shard layout is stable at this point. 1311 * 1312 * scx_alloc_pshards() skips allocation when @sch's arena pool isn't 1313 * initialized, so scx_arena_pool_init() must run first. 1314 */ 1315 ret = scx_arena_pool_init(sch); 1316 if (ret) 1317 goto err_disable; 1318 1319 ret = scx_alloc_pshards(sch); 1320 if (ret) 1321 goto err_disable; 1322 1323 ret = scx_link_sched(sch); 1324 if (ret) 1325 goto err_disable; 1326 1327 ret = scx_sched_sysfs_add(sch); 1328 if (ret) 1329 goto err_disable; 1330 1331 if (sch->level >= SCX_SUB_MAX_DEPTH) { 1332 scx_error(sch, "max nesting depth %d violated", 1333 SCX_SUB_MAX_DEPTH); 1334 goto err_disable; 1335 } 1336 1337 if (sch->ops.init) { 1338 ret = SCX_CALL_OP_RET(sch, init, NULL); 1339 if (ret) { 1340 ret = scx_ops_sanitize_err(sch, "init", ret); 1341 scx_error(sch, "ops.init() failed (%d)", ret); 1342 goto err_disable; 1343 } 1344 sch->exit_info->flags |= SCX_EFLAG_INITIALIZED; 1345 } 1346 1347 ret = scx_set_cmask_scratch_alloc(sch); 1348 if (ret) 1349 goto err_disable; 1350 1351 struct scx_sub_attach_args sub_attach_args = { 1352 .ops = &sch->ops, 1353 .cgroup_path = sch->cgrp_path, 1354 }; 1355 1356 ret = SCX_CALL_OP_RET(parent, sub_attach, NULL, 1357 &sub_attach_args); 1358 if (ret) { 1359 ret = scx_ops_sanitize_err(sch, "sub_attach", ret); 1360 scx_error(sch, "parent rejected (%d)", ret); 1361 goto err_disable; 1362 } 1363 sch->sub_attached = true; 1364 1365 scx_bypass(sch, true); 1366 1367 for (i = SCX_OPI_BEGIN; i < SCX_OPI_END; i++) 1368 if (((void (**)(void))ops)[i]) 1369 set_bit(i, sch->has_op); 1370 1371 percpu_down_write(&scx_fork_rwsem); 1372 scx_cgroup_lock(); 1373 1374 /* 1375 * Set cgroup->scx_sched's and check CSS_ONLINE. Either we see 1376 * !CSS_ONLINE or scx_cgroup_lifetime_notify() sees and shoots us down. 1377 */ 1378 set_cgroup_sched(sch_cgroup(sch), sch); 1379 if (!(cgrp->self.flags & CSS_ONLINE)) { 1380 scx_error(sch, "cgroup is not online"); 1381 goto err_unlock_and_disable; 1382 } 1383 1384 /* 1385 * Take over the subtree's cgroups before any task is claimed, 1386 * mirroring root enable's cgroups-before-tasks order. 1387 */ 1388 ret = scx_cgroup_claim_subtree(sch); 1389 if (ret) 1390 goto err_unlock_and_disable; 1391 1392 /* 1393 * Initialize tasks for the new child $sch without exiting them for 1394 * $parent so that the tasks can always be reverted back to $parent 1395 * sched on child init failure. 1396 */ 1397 WARN_ON_ONCE(scx_enabling_sub_sched); 1398 scx_enabling_sub_sched = sch; 1399 1400 scx_task_iter_start(&sti, sch->cgrp); 1401 while ((p = scx_task_iter_next_locked(&sti))) { 1402 struct rq *rq; 1403 struct rq_flags rf; 1404 1405 /* 1406 * Task iteration may visit the same task twice when racing 1407 * against exiting. Use %SCX_TASK_SUB_INIT to mark tasks which 1408 * finished __scx_init_task() and skip if set. 1409 * 1410 * A task may exit and get freed between __scx_init_task() 1411 * completion and scx_enable_task(). In such cases, 1412 * scx_disable_and_exit_task() must exit the task for both the 1413 * parent and child scheds. 1414 */ 1415 if (p->scx.flags & SCX_TASK_SUB_INIT) 1416 continue; 1417 1418 /* @p is pinned by the iter; see scx_sub_disable() */ 1419 get_task_struct(p); 1420 1421 if (!assert_task_ready_or_enabled(p)) { 1422 ret = -EINVAL; 1423 goto abort; 1424 } 1425 1426 scx_task_iter_unlock(&sti); 1427 1428 /* 1429 * As $p is still on $parent, it can't be transitioned to INIT. 1430 * Let's worry about task state later. Use __scx_init_task(). 1431 */ 1432 ret = __scx_init_task(sch, p, NULL, false); 1433 if (ret) 1434 goto abort; 1435 1436 rq = task_rq_lock(p, &rf); 1437 1438 if (scx_get_task_state(p) == SCX_TASK_DEAD) { 1439 /* 1440 * sched_ext_dead() raced us between __scx_init_task() 1441 * and this rq lock and ran exit_task() on $parent (the 1442 * sched @p was on at that point), not on @sch. @sch's 1443 * just-completed init is owed an exit_task() and we 1444 * issue it here. 1445 */ 1446 scx_sub_init_cancel_task(sch, p); 1447 task_rq_unlock(rq, p, &rf); 1448 put_task_struct(p); 1449 continue; 1450 } 1451 1452 p->scx.flags |= SCX_TASK_SUB_INIT; 1453 task_rq_unlock(rq, p, &rf); 1454 1455 put_task_struct(p); 1456 } 1457 scx_task_iter_stop(&sti); 1458 1459 /* 1460 * All tasks are prepped. Disable/exit tasks for $parent and enable for 1461 * the new @sch. 1462 */ 1463 scx_task_iter_start(&sti, sch->cgrp); 1464 while ((p = scx_task_iter_next_locked(&sti))) { 1465 /* 1466 * Use clearing of %SCX_TASK_SUB_INIT to detect and skip 1467 * duplicate iterations. 1468 */ 1469 if (!(p->scx.flags & SCX_TASK_SUB_INIT)) 1470 continue; 1471 1472 scoped_guard (sched_change, p, DEQUEUE_SAVE | DEQUEUE_MOVE) { 1473 /* 1474 * $p must be either READY or ENABLED. If ENABLED, 1475 * __scx_disabled_and_exit_task() first disables and 1476 * makes it READY. However, after exiting $p, it will 1477 * leave $p as READY. 1478 */ 1479 assert_task_ready_or_enabled(p); 1480 __scx_disable_and_exit_task(parent, p); 1481 1482 /* 1483 * $p is now only initialized for @sch and READY, which 1484 * is what we want. Assign it to @sch and, if it's on 1485 * the ext class, enable. A non-ext task, possible under 1486 * an %SCX_OPS_SWITCH_PARTIAL root, stays READY and is 1487 * enabled by switching_to_scx() if it switches over. 1488 */ 1489 scx_set_task_sched(p, sch); 1490 if (p->sched_class == &ext_sched_class) 1491 scx_enable_task(sch, p); 1492 1493 p->scx.flags &= ~SCX_TASK_SUB_INIT; 1494 } 1495 } 1496 scx_task_iter_stop(&sti); 1497 1498 scx_enabling_sub_sched = NULL; 1499 1500 scx_cgroup_unlock(); 1501 percpu_up_write(&scx_fork_rwsem); 1502 1503 scx_bypass(sch, false); 1504 1505 /* @sch is enabled; deliver any caps owed since its sub_attach() */ 1506 scx_sub_seed_caps(sch); 1507 1508 pr_info("sched_ext: BPF sub-scheduler \"%s\" enabled\n", sch->ops.name); 1509 kobject_uevent(&sch->kobj, KOBJ_ADD); 1510 ret = 0; 1511 goto out_unlock; 1512 1513 out_put_cgrp: 1514 cgroup_put(cgrp); 1515 out_unlock: 1516 mutex_unlock(&scx_enable_mutex); 1517 cmd->ret = ret; 1518 return; 1519 1520 abort: 1521 put_task_struct(p); 1522 scx_task_iter_stop(&sti); 1523 1524 /* 1525 * Undo __scx_init_task() for tasks we marked. scx_enable_task() never 1526 * ran for @sch on them, so calling scx_disable_task() here would invoke 1527 * ops.disable() without a matching ops.enable(). scx_enabling_sub_sched 1528 * must stay set until SUB_INIT is cleared from every marked task - 1529 * scx_disable_and_exit_task() reads it when a task exits concurrently. 1530 */ 1531 scx_task_iter_start(&sti, sch->cgrp); 1532 while ((p = scx_task_iter_next_locked(&sti))) { 1533 if (p->scx.flags & SCX_TASK_SUB_INIT) { 1534 scx_sub_init_cancel_task(sch, p); 1535 p->scx.flags &= ~SCX_TASK_SUB_INIT; 1536 } 1537 } 1538 scx_task_iter_stop(&sti); 1539 scx_enabling_sub_sched = NULL; 1540 err_unlock_and_disable: 1541 /* we'll soon enter disable path, keep bypass on */ 1542 scx_cgroup_unlock(); 1543 percpu_up_write(&scx_fork_rwsem); 1544 err_disable: 1545 mutex_unlock(&scx_enable_mutex); 1546 /* 1547 * Some enable failures only return an errno (e.g. -ENOMEM from an 1548 * allocation) without calling scx_error(). Record it so 1549 * scx_flush_disable_work() runs the disable and ops.exit() fires. 1550 */ 1551 scx_error(sch, "scx_sub_enable() failed (%d)", ret); 1552 scx_flush_disable_work(sch); 1553 cmd->ret = 0; 1554 } 1555 1556 /** 1557 * scx_cgroup_task_migrating - Prepare a task for a cgroup migration 1558 * @ctx: migration being prepared 1559 * 1560 * A task's sched must match its cgroup's owner, so a migration that crosses a 1561 * sched boundary re-homes the task once committed. Run the fallible part here, 1562 * before the migration commits: initialize the task for the destination sched. 1563 * A rejection fails the cgroup.procs write. 1564 */ 1565 static s32 scx_cgroup_task_migrating(struct cgroup_task_migrate_ctx *ctx) 1566 { 1567 struct task_struct *p = ctx->task; 1568 struct scx_sched *to; 1569 int ret; 1570 1571 /* 1572 * Cleared under scx_cgroup_lock() before root disable starts tearing 1573 * down tasks. As cgroup_mutex is held, a set flag guarantees that the 1574 * teardown loop is not running concurrently. 1575 */ 1576 if (!scx_cgroup_enabled) 1577 return NOTIFY_OK; 1578 1579 to = ctx->dst_dcgrp->scx_sched; 1580 if (scx_task_on_sched(to, p)) 1581 return NOTIFY_OK; 1582 1583 ret = __scx_init_task(to, p, ctx->dst_dcgrp, false); 1584 if (ret) 1585 return notifier_from_errno(ret); 1586 1587 return NOTIFY_OK; 1588 } 1589 1590 /** 1591 * scx_cgroup_task_migrated - Re-home a task that changed cgroups 1592 * @ctx: committed migration 1593 * 1594 * Move the task to its new cgroup's sched, which scx_cgroup_task_migrating() 1595 * already initialized it for. Can't fail. 1596 * 1597 * This is safe against all phases of the destination sched's destruction. A 1598 * disable resets cgroup ownership to the parent and re-homes tasks in one 1599 * scx_cgroup_lock() section. If that section already ran, the destination would 1600 * be the parent. Otherwise, the re-home loop is still ahead and guaranteed to 1601 * visit the task, now in the destination cgroup. 1602 */ 1603 static void scx_cgroup_task_migrated(struct cgroup_task_migrate_ctx *ctx) 1604 { 1605 struct task_struct *p = ctx->task; 1606 struct scx_sched *to; 1607 struct rq *rq; 1608 struct rq_flags rf; 1609 1610 if (!scx_cgroup_enabled) 1611 return; 1612 1613 to = ctx->dst_dcgrp->scx_sched; 1614 if (scx_task_on_sched(to, p)) 1615 return; 1616 1617 rq = task_rq_lock(p, &rf); 1618 scx_rehome_task(to, p); 1619 task_rq_unlock(rq, p, &rf); 1620 } 1621 1622 /** 1623 * scx_cgroup_task_migrate_canceled - Undo migration preparation 1624 * @ctx: canceled migration 1625 * 1626 * The migration failed after scx_cgroup_task_migrating() initialized the task 1627 * for the destination sched. The task stays on its current sched in the source 1628 * cgroup. Undo the destination's init. 1629 */ 1630 static void scx_cgroup_task_migrate_canceled(struct cgroup_task_migrate_ctx *ctx) 1631 { 1632 struct task_struct *p = ctx->task; 1633 struct scx_sched *to; 1634 struct rq *rq; 1635 struct rq_flags rf; 1636 1637 if (!scx_cgroup_enabled) 1638 return; 1639 1640 to = ctx->dst_dcgrp->scx_sched; 1641 if (scx_task_on_sched(to, p)) 1642 return; 1643 1644 rq = task_rq_lock(p, &rf); 1645 scx_sub_init_cancel_task(to, p); 1646 task_rq_unlock(rq, p, &rf); 1647 } 1648 1649 static s32 scx_cgroup_lifetime_notify(struct notifier_block *nb, 1650 unsigned long action, void *data) 1651 { 1652 struct cgroup *cgrp = data; 1653 struct cgroup *parent = cgroup_parent(cgrp); 1654 1655 if (!cgroup_on_dfl(cgrp)) 1656 return NOTIFY_OK; 1657 1658 switch (action) { 1659 case CGROUP_LIFETIME_ONLINE: 1660 /* inherit ->scx_sched from $parent */ 1661 if (parent) 1662 rcu_assign_pointer(cgrp->scx_sched, parent->scx_sched); 1663 break; 1664 case CGROUP_LIFETIME_OFFLINE: 1665 /* if there is a sched attached, shoot it down */ 1666 if (cgrp->scx_sched && cgrp->scx_sched->cgrp == cgrp) 1667 scx_exit(cgrp->scx_sched, SCX_EXIT_UNREG_KERN, 1668 SCX_ECODE_RSN_CGROUP_OFFLINE, 1669 "cgroup %llu going offline", cgroup_id(cgrp)); 1670 break; 1671 } 1672 1673 return NOTIFY_OK; 1674 } 1675 1676 static struct notifier_block scx_cgroup_lifetime_nb = { 1677 .notifier_call = scx_cgroup_lifetime_notify, 1678 }; 1679 1680 static s32 scx_cgroup_task_notify(struct notifier_block *nb, 1681 unsigned long action, void *data) 1682 { 1683 struct cgroup_task_migrate_ctx *ctx = data; 1684 1685 switch (action) { 1686 case CGROUP_TASK_MIGRATING: 1687 return scx_cgroup_task_migrating(ctx); 1688 case CGROUP_TASK_MIGRATED: 1689 scx_cgroup_task_migrated(ctx); 1690 break; 1691 case CGROUP_TASK_MIGRATE_CANCELED: 1692 scx_cgroup_task_migrate_canceled(ctx); 1693 break; 1694 } 1695 1696 return NOTIFY_OK; 1697 } 1698 1699 static struct notifier_block scx_cgroup_task_nb = { 1700 .notifier_call = scx_cgroup_task_notify, 1701 }; 1702 1703 static s32 __init scx_cgroup_notifier_init(void) 1704 { 1705 s32 ret; 1706 1707 ret = blocking_notifier_chain_register(&cgroup_lifetime_notifier, 1708 &scx_cgroup_lifetime_nb); 1709 if (ret) 1710 return ret; 1711 1712 return blocking_notifier_chain_register(&cgroup_task_notifier, 1713 &scx_cgroup_task_nb); 1714 } 1715 core_initcall(scx_cgroup_notifier_init); 1716 1717 static void scx_pstack_recursion(struct bpf_prog *prog, const char *op) 1718 { 1719 struct scx_sched *sch; 1720 1721 guard(rcu)(); 1722 sch = scx_prog_sched(prog->aux); 1723 if (unlikely(!sch)) 1724 return; 1725 1726 scx_error(sch, "%s recursion detected", op); 1727 } 1728 1729 void scx_pstack_recursion_on_dispatch(struct bpf_prog *prog) 1730 { 1731 scx_pstack_recursion(prog, "dispatch"); 1732 } 1733 1734 void scx_pstack_recursion_on_caps_updated(struct bpf_prog *prog) 1735 { 1736 scx_pstack_recursion(prog, "sub_caps_updated"); 1737 } 1738 1739 __bpf_kfunc_start_defs(); 1740 1741 /** 1742 * scx_bpf_sub_dispatch - Trigger dispatching on a child scheduler 1743 * @cgroup_id: cgroup ID of the child scheduler to dispatch 1744 * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs 1745 * 1746 * Allows a parent scheduler to trigger dispatching on one of its direct 1747 * child schedulers. The child scheduler runs its dispatch operation to 1748 * move tasks from dispatch queues to the local runqueue. 1749 * 1750 * Returns: true on success, false if cgroup_id is invalid, not a direct 1751 * child, or caller lacks dispatch permission. 1752 */ 1753 __bpf_kfunc bool scx_bpf_sub_dispatch(u64 cgroup_id, const struct bpf_prog_aux *aux) 1754 { 1755 struct rq *this_rq = this_rq(); 1756 struct scx_sched *parent, *child; 1757 1758 guard(rcu)(); 1759 parent = scx_prog_sched(aux); 1760 if (unlikely(!parent)) 1761 return false; 1762 1763 child = scx_find_sub_sched(cgroup_id); 1764 1765 if (unlikely(!child)) 1766 return false; 1767 1768 if (unlikely(scx_parent(child) != parent)) { 1769 scx_error(parent, "trying to dispatch a distant sub-sched on cgroup %llu", 1770 cgroup_id); 1771 return false; 1772 } 1773 1774 /* 1775 * Skip a child that does not effectively hold the base cap on this cpu: 1776 * its inserts would only be rejected. ecaps are synced at the top of 1777 * balance_one() before dispatch, so this reflects the in-effect state. 1778 */ 1779 if (scx_missing_caps(child, cpu_of(this_rq), SCX_CAP_BASE)) 1780 return false; 1781 1782 return scx_dispatch_sched(child, this_rq, this_rq->scx.sub_dispatch_prev, 1783 true); 1784 } 1785 1786 /* Validate common inputs. On success, *parent_out and *child_out are set. */ 1787 static s32 sub_cap_preamble(u64 cgroup_id, u64 caps, const struct bpf_prog_aux *aux, 1788 struct scx_sched **parent_out, struct scx_sched **child_out) 1789 { 1790 struct scx_sched *parent, *child; 1791 1792 parent = scx_prog_sched(aux); 1793 if (unlikely(!parent)) 1794 return -ENODEV; 1795 1796 if (!scx_is_cid_type()) { 1797 scx_error(parent, "sub-cap kfuncs require a cid-form scheduler"); 1798 return -EOPNOTSUPP; 1799 } 1800 1801 child = scx_find_sub_sched(cgroup_id); 1802 if (unlikely(!child)) 1803 return -ENODEV; 1804 1805 if (unlikely(scx_parent(child) != parent)) { 1806 scx_error(parent, "%s: sub-%llu is not a direct child", 1807 parent->cgrp_path, cgroup_id); 1808 return -EINVAL; 1809 } 1810 1811 if (unlikely(caps & ~__SCX_CAP_ALL)) { 1812 scx_error(parent, "invalid caps 0x%llx", caps); 1813 return -EINVAL; 1814 } 1815 1816 *parent_out = parent; 1817 *child_out = child; 1818 return 0; 1819 } 1820 1821 /** 1822 * scx_bpf_sub_grant - Grant @caps on @cmask__ign's cids to a direct child 1823 * @cgroup_id: cgroup id of the direct child sub-sched 1824 * @caps: bitmask of SCX_CAP_* to grant 1825 * @cmask__ign: cid cmask to grant @caps on (arena pointer) 1826 * @denied_out__ign: optional arena cmask accumulating refused cids 1827 * @aux: implicit BPF argument 1828 * 1829 * A cid in @cmask__ign is granted to the child only if the parent holds every 1830 * requested cap on it. Refused cids are OR'd into @denied_out__ign when 1831 * provided. Refusals outside @denied_out__ign's range are not recorded. 1832 * 1833 * All-or-nothing keeps the caller-visible result binary per cid, so 1834 * @denied_out__ign is one mask to interpret rather than a per-cap matrix. 1835 * 1836 * Return 0 on full success, -EPERM if any cid was refused, or a negative 1837 * errno on other failures. 1838 */ 1839 __bpf_kfunc s32 scx_bpf_sub_grant(u64 cgroup_id, u64 caps, 1840 const struct scx_cmask *cmask__ign, 1841 struct scx_cmask *denied_out__ign, 1842 const struct bpf_prog_aux *aux) 1843 { 1844 struct scx_cmask_ref ref, denied_ref; 1845 struct scx_sched *parent, *child; 1846 bool any_denied = false; 1847 LIST_HEAD(to_deliver); 1848 s32 si, ret; 1849 1850 guard(irqsave)(); 1851 1852 ret = sub_cap_preamble(cgroup_id, caps, aux, &parent, &child); 1853 if (ret) 1854 return ret; 1855 1856 ret = scx_cmask_ref_init(parent, cmask__ign, &ref); 1857 if (ret) { 1858 scx_error(parent, "invalid cmask (%d)", ret); 1859 return ret; 1860 } 1861 1862 if (denied_out__ign) { 1863 ret = scx_cmask_ref_init(parent, denied_out__ign, &denied_ref); 1864 if (ret) { 1865 scx_error(parent, "invalid denied_out (%d)", ret); 1866 return ret; 1867 } 1868 } 1869 1870 /* apply the grant one shard at a time */ 1871 for (si = ref.shard_first; si < ref.shard_end; si++) { 1872 SCX_CMASK_DEFINE_SHARD(slice, 0, SCX_CID_SHARD_MAX_CPUS); 1873 struct scx_pshard *pps = parent->pshard[si]; 1874 struct scx_pshard *cps = child->pshard[si]; 1875 u64 granted_caps = 0; 1876 u32 cap_bit; 1877 1878 scx_cmask_ref_shard(&ref, si, slice); 1879 if (scx_cmask_empty(slice)) 1880 continue; 1881 1882 SCX_CMASK_DEFINE_SHARD(granted_cids, slice->base, slice->nr_cids); 1883 SCX_CMASK_DEFINE_SHARD(changed_cids, slice->base, slice->nr_cids); 1884 SCX_CMASK_DEFINE_SHARD(delta, slice->base, slice->nr_cids); 1885 1886 scx_cmask_copy(granted_cids, slice); 1887 1888 scoped_guard (raw_spinlock, &pps->lock) { 1889 guard(raw_spinlock_nested)(&cps->lock); 1890 1891 /* 1892 * Narrow granted_cids to cids the parent holds every 1893 * requested cap on. All-or-nothing per cid. 1894 */ 1895 scx_for_each_cap_bit(cap_bit, caps) 1896 scx_cmask_and(granted_cids, &pps->caps[cap_bit].cmask); 1897 1898 /* 1899 * For each requested cap, fold the newly-set cids into 1900 * the child and accumulate the delta. 1901 */ 1902 scx_for_each_cap_bit(cap_bit, caps) { 1903 struct scx_cmask *ccm = &cps->caps[cap_bit].cmask; 1904 1905 scx_cmask_copy(delta, granted_cids); 1906 scx_cmask_andnot(delta, ccm); 1907 if (scx_cmask_empty(delta)) 1908 continue; 1909 1910 scx_cmask_or(ccm, delta); 1911 scx_cmask_or(changed_cids, delta); 1912 granted_caps |= BIT_U64(cap_bit); 1913 } 1914 1915 if (granted_caps) { 1916 s32 cid; 1917 1918 caps_updated_record(cps, changed_cids, granted_caps, 1919 &to_deliver); 1920 /* 1921 * The sync arms an update_idle() re-notify if 1922 * the cid gains baseline access, so the holder 1923 * learns of an already-idle cid. 1924 */ 1925 scx_cmask_for_each_cid(cid, changed_cids) 1926 queue_sync_ecaps(child, cid); 1927 } 1928 } 1929 1930 /* record cids that didn't make it through into @denied_out */ 1931 if (!scx_cmask_subset(slice, granted_cids)) { 1932 any_denied = true; 1933 if (denied_out__ign) { 1934 SCX_CMASK_DEFINE_SHARD(denied, slice->base, slice->nr_cids); 1935 1936 scx_cmask_copy(denied, slice); 1937 scx_cmask_andnot(denied, granted_cids); 1938 scx_cmask_ref_or(&denied_ref, denied); 1939 } 1940 } 1941 } 1942 1943 caps_updated_deliver(&to_deliver); 1944 1945 return any_denied ? -EPERM : 0; 1946 } 1947 1948 /** 1949 * scx_bpf_sub_revoke - Revoke @caps on @cmask__ign's cids from @child 1950 * @cgroup_id: cgroup id of the direct child sub-sched 1951 * @caps: bitmask of SCX_CAP_* to revoke 1952 * @cmask__ign: cid cmask to revoke @caps on (arena pointer) 1953 * @aux: implicit BPF argument 1954 * 1955 * Clear @caps bits on @cmask__ign from the child named by @cgroup_id and all 1956 * its descendants. The origin parent's pshard lock is held across the subtree 1957 * walk so a concurrent grant from the origin parent observes the revoked 1958 * state. 1959 */ 1960 __bpf_kfunc void scx_bpf_sub_revoke(u64 cgroup_id, u64 caps, 1961 const struct scx_cmask *cmask__ign, 1962 const struct bpf_prog_aux *aux) 1963 { 1964 struct scx_cmask_ref ref; 1965 struct scx_sched *parent, *child, *pos; 1966 LIST_HEAD(to_deliver); 1967 s32 si, ret; 1968 1969 guard(irqsave)(); 1970 1971 if (sub_cap_preamble(cgroup_id, caps, aux, &parent, &child)) 1972 return; 1973 1974 ret = scx_cmask_ref_init(parent, cmask__ign, &ref); 1975 if (ret) { 1976 scx_error(parent, "invalid cmask (%d)", ret); 1977 return; 1978 } 1979 1980 /* per-shard, walk child's subtree and clear @caps */ 1981 for (si = ref.shard_first; si < ref.shard_end; si++) { 1982 SCX_CMASK_DEFINE_SHARD(slice, 0, SCX_CID_SHARD_MAX_CPUS); 1983 1984 scx_cmask_ref_shard(&ref, si, slice); 1985 if (scx_cmask_empty(slice)) 1986 continue; 1987 1988 /* 1989 * Pre-order with subtree skip: a descendant that cleared 1990 * nothing means no descendant of it can hold @caps on these 1991 * cids either. 1992 */ 1993 guard(raw_spinlock)(&parent->pshard[si]->lock); 1994 pos = scx_next_descendant_pre(NULL, child); 1995 while (pos) { 1996 struct scx_pshard *ps = pos->pshard[si]; 1997 SCX_CMASK_DEFINE_SHARD(changed_cids, slice->base, slice->nr_cids); 1998 SCX_CMASK_DEFINE_SHARD(delta, slice->base, slice->nr_cids); 1999 u64 revoked_caps = 0; 2000 u32 cap_bit; 2001 2002 scoped_guard (raw_spinlock_nested, &ps->lock) { 2003 /* 2004 * For each cap, clear lost cids and accumulate 2005 * the per-cap diff for notification. 2006 */ 2007 scx_for_each_cap_bit(cap_bit, caps) { 2008 struct scx_cmask *cm = &ps->caps[cap_bit].cmask; 2009 2010 scx_cmask_copy(delta, cm); 2011 scx_cmask_and(delta, slice); 2012 if (scx_cmask_empty(delta)) 2013 continue; 2014 2015 scx_cmask_andnot(cm, delta); 2016 scx_cmask_or(changed_cids, delta); 2017 revoked_caps |= BIT_U64(cap_bit); 2018 } 2019 2020 if (revoked_caps) { 2021 s32 cid; 2022 2023 caps_updated_record(ps, changed_cids, revoked_caps, 2024 &to_deliver); 2025 scx_cmask_for_each_cid(cid, changed_cids) 2026 queue_sync_ecaps(pos, cid); 2027 } 2028 } 2029 2030 if (revoked_caps) 2031 pos = scx_next_descendant_pre(pos, child); 2032 else 2033 pos = scx_skip_subtree_pre(pos, child); 2034 } 2035 } 2036 2037 caps_updated_deliver(&to_deliver); 2038 } 2039 2040 /** 2041 * scx_bpf_sub_caps - Read self's or a direct child's cap cmasks 2042 * @cgroup_id: 0 for self, or a direct child's cgroup id 2043 * @caps: one or more SCX_CAP_* bits 2044 * @out__ign: arena cmask to receive the union of @caps within its range 2045 * @aux: implicit BPF argument 2046 * 2047 * Read the cap cmasks granted on each cid for self (@cgroup_id 0) or a direct 2048 * child - the literal granted set. A sched can read only itself or a direct 2049 * child. 2050 * 2051 * Return 0, -ENODEV if @cgroup_id names no direct child, or -EINVAL on bad 2052 * inputs. 2053 */ 2054 __bpf_kfunc s32 scx_bpf_sub_caps(u64 cgroup_id, u64 caps, struct scx_cmask *out__ign, 2055 const struct bpf_prog_aux *aux) 2056 { 2057 struct scx_cmask_ref ref; 2058 struct scx_sched *sch, *target; 2059 struct scx_pshard **pshard; 2060 s32 si, ret; 2061 2062 guard(irqsave)(); 2063 2064 sch = scx_prog_sched(aux); 2065 if (unlikely(!sch)) 2066 return -ENODEV; 2067 2068 if (!scx_is_cid_type()) { 2069 scx_error(sch, "sub-cap kfuncs require a cid-form scheduler"); 2070 return -EOPNOTSUPP; 2071 } 2072 2073 if (unlikely(caps & ~__SCX_CAP_ALL)) { 2074 scx_error(sch, "invalid caps 0x%llx", caps); 2075 return -EINVAL; 2076 } 2077 2078 /* @cgroup_id 0 reads self, otherwise a direct child */ 2079 if (cgroup_id) { 2080 target = scx_find_sub_sched(cgroup_id); 2081 if (unlikely(!target)) 2082 return -ENODEV; 2083 if (unlikely(scx_parent(target) != sch)) { 2084 scx_error(sch, "%s: sub-%llu is not a direct child", 2085 sch->cgrp_path, cgroup_id); 2086 return -EINVAL; 2087 } 2088 } else { 2089 target = sch; 2090 } 2091 2092 /* 2093 * The target's caps storage may not be set up yet (e.g. a self-read 2094 * during ops.init_cids()). Pairs with the publish in 2095 * scx_alloc_pshards(): a non-NULL pshard has every element set and the 2096 * acquire also orders the cid table reads below against it. 2097 */ 2098 pshard = smp_load_acquire(&target->pshard); 2099 if (unlikely(!pshard)) { 2100 scx_error(sch, "scx_bpf_sub_caps() called before caps storage is initialized"); 2101 return -ENODEV; 2102 } 2103 2104 ret = scx_cmask_ref_init(sch, out__ign, &ref); 2105 if (ret) { 2106 scx_error(sch, "invalid out (%d)", ret); 2107 return ret; 2108 } 2109 2110 for (si = ref.shard_first; si < ref.shard_end; si++) { 2111 const struct scx_cid_shard *shard = 2112 &rcu_dereference_all(scx_cid_shard_ranges)[si]; 2113 SCX_CMASK_DEFINE_SHARD(local_out, shard->base_cid, shard->nr_cids); 2114 u32 cap_bit; 2115 2116 scx_for_each_cap_bit(cap_bit, caps) 2117 scx_cmask_or(local_out, &pshard[si]->caps[cap_bit].cmask); 2118 scx_cmask_ref_copy(&ref, local_out); 2119 } 2120 return 0; 2121 } 2122 2123 /** 2124 * scx_bpf_sub_kill_bstr - Kill a direct child sub-scheduler 2125 * @cgroup_id: cgroup id of the direct child to kill 2126 * @fmt: reason message format string 2127 * @data: format string parameters packaged using ___bpf_fill() macro 2128 * @data__sz: @data len, must end in '__sz' for the verifier 2129 * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs 2130 * 2131 * Evict a direct child sub-scheduler, disabling it with the supplied reason. 2132 * The child and its subtree are torn down asynchronously through the usual 2133 * disable path. 2134 * 2135 * Unlike scx_bpf_exit(), no exit code is taken: the child is a separate 2136 * scheduler with its own exit-code semantics, so a code chosen by the parent 2137 * would have no defined meaning. The reason string carries the intent. 2138 * 2139 * Return 0 on success or -ENODEV if @cgroup_id names no sub-scheduler, which 2140 * can race with the child detaching on its own and so is not a scheduler error. 2141 * Naming a sched that exists but is not a direct child aborts the parent. 2142 */ 2143 __printf(2, 0) 2144 __bpf_kfunc s32 scx_bpf_sub_kill_bstr(u64 cgroup_id, char *fmt, 2145 unsigned long long *data, u32 data__sz, 2146 const struct bpf_prog_aux *aux) 2147 { 2148 struct scx_sched *parent, *child; 2149 s32 ret; 2150 2151 guard(rcu)(); 2152 2153 parent = scx_prog_sched(aux); 2154 if (unlikely(!parent)) 2155 return -ENODEV; 2156 2157 if (!scx_is_cid_type()) { 2158 scx_error(parent, "sub-cap kfuncs require a cid-form scheduler"); 2159 return -EOPNOTSUPP; 2160 } 2161 2162 child = scx_find_sub_sched(cgroup_id); 2163 if (unlikely(!child)) 2164 return -ENODEV; 2165 2166 if (unlikely(scx_parent(child) != parent)) { 2167 scx_error(parent, "%s: sub-%llu is not a direct child", 2168 parent->cgrp_path, cgroup_id); 2169 return -EINVAL; 2170 } 2171 2172 guard(raw_spinlock_irqsave)(&scx_exit_bstr_buf_lock); 2173 ret = scx_bstr_format(parent, &scx_exit_bstr_buf, fmt, data, data__sz); 2174 if (ret < 0) 2175 return ret; 2176 scx_exit(child, SCX_EXIT_PARENT_KILL, 0, "%s", scx_exit_bstr_buf.line); 2177 return 0; 2178 } 2179 2180 __bpf_kfunc_end_defs(); 2181 2182 #endif /* CONFIG_EXT_SUB_SCHED */ 2183