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 * On while a loaded sched implements ops.sub_cid_sched_updated(), see 33 * scx_ops_cid_sched_updated_enable(). 34 */ 35 static DEFINE_STATIC_KEY_FALSE(__scx_ops_cid_sched_updated_enabled); 36 static s32 scx_nr_ops_cid_sched_updated; /* such scheds, under scx_enable_mutex */ 37 38 /* latched at root enable before any rescue runs */ 39 s32 scx_rescue_bw_1024; /* 0 if disabled, see scx_rescue_enabled() */ 40 static s64 scx_rescue_quantum_ns; 41 static s64 scx_rescue_sat_delta_ns; 42 static unsigned long scx_rescue_decay_halflife; 43 static unsigned long scx_rescue_overload_after; 44 45 /* 46 * ecaps_report() waits here for its marked syncs. A cpu going down keeps 47 * picking tasks after hotplug parks its irq_work thread. Its picks can process 48 * a marked sync, e.g. a core scheduling sibling's. A regular irq_work queued 49 * there is left behind on PREEMPT_RT, so the wakeup is hard irq work. A hard 50 * irq can't take a wait queue's lock, which sleeps on PREEMPT_RT. 51 * scx_enable_mutex serializes the reports, so the single waiter sleeps on an 52 * rcuwait. 53 */ 54 static struct rcuwait ecaps_report_wait = __RCUWAIT_INITIALIZER(ecaps_report_wait); 55 56 /* a cpu going down waits here for its marked syncs, see scx_offline_ecaps() */ 57 static DECLARE_WAIT_QUEUE_HEAD(ecaps_offline_waitq); 58 59 /* 60 * The cpus that suspend or hibernation took down and that haven't come back. 61 * Their losses are not delivered, see scx_offline_ecaps(). Hotplug updates the 62 * set under cpus_write_lock(), and scx_sub_pm_end() clears it under 63 * cpus_read_lock(). A cpu that fails to come back stays in the set until 64 * regular hotplug brings it back or the PM cycle ends. 65 */ 66 static struct cpumask scx_frozen_cpus; 67 static DECLARE_WAIT_QUEUE_HEAD(scx_frozen_cpus_waitq); 68 69 /* between the PREPARE and POST notifications of a PM cycle */ 70 static bool scx_pm_in_progress; 71 72 /** 73 * scx_skip_subtree_pre - Skip @pos's subtree in a pre-order walk 74 * @pos: current position 75 * @root: walk root 76 * 77 * In a walk started by scx_next_descendant_pre(), continue past @pos's subtree: 78 * return @pos's next sibling, or the closest ancestor's next sibling, or NULL 79 * if @pos's subtree is the last under @root. Same locking rules. 80 */ 81 struct scx_sched *scx_skip_subtree_pre(struct scx_sched *pos, struct scx_sched *root) 82 { 83 struct scx_sched *next; 84 85 lockdep_assert(lockdep_is_held(&scx_enable_mutex) || 86 lockdep_is_held(&scx_sched_lock) || 87 rcu_read_lock_any_held()); 88 89 while (pos != root) { 90 next = list_next_or_null_rcu(&scx_parent(pos)->children, &pos->sibling, 91 struct scx_sched, sibling); 92 if (next) 93 return next; 94 pos = scx_parent(pos); 95 } 96 return NULL; 97 } 98 99 /** 100 * scx_next_descendant_pre - find the next descendant for pre-order walk 101 * @pos: the current position (%NULL to initiate traversal) 102 * @root: sched whose descendants to walk 103 * 104 * To be used by scx_for_each_descendant_pre(). Find the next descendant to 105 * visit for pre-order traversal of @root's descendants. @root is included in 106 * the iteration and the first node to be visited. 107 */ 108 struct scx_sched *scx_next_descendant_pre(struct scx_sched *pos, struct scx_sched *root) 109 { 110 struct scx_sched *next; 111 112 lockdep_assert(lockdep_is_held(&scx_enable_mutex) || 113 lockdep_is_held(&scx_sched_lock) || 114 rcu_read_lock_any_held()); 115 116 /* if first iteration, visit @root */ 117 if (!pos) 118 return root; 119 120 /* visit the first child if exists */ 121 next = list_first_or_null_rcu(&pos->children, struct scx_sched, sibling); 122 if (next) 123 return next; 124 125 /* no child, visit my or the closest ancestor's next sibling */ 126 return scx_skip_subtree_pre(pos, root); 127 } 128 129 /** 130 * scx_cid_sched_id_from - Resolve what @from sees when @sch runs on a cid 131 * @sch: sched whose task runs there, %NULL for none 132 * @from: sched asking 133 * 134 * Return %SCX_CID_SCHED_NONE when @sch is %NULL or outside @from's subtree, 135 * %SCX_CID_SCHED_SELF for @from itself, or else the cgroup id of the direct 136 * child of @from on the way down to @sch. 137 */ 138 static u64 scx_cid_sched_id_from(struct scx_sched *sch, struct scx_sched *from) 139 { 140 if (!sch || !scx_is_descendant(sch, from)) 141 return SCX_CID_SCHED_NONE; 142 if (sch == from) 143 return SCX_CID_SCHED_SELF; 144 return sch->ancestors[from->level + 1]->ops.sub_cgroup_id; 145 } 146 147 /* notify @from of what it now sees running on @rq's cid */ 148 static void scx_cid_notify_sched_updated(struct rq *rq, struct scx_sched *sch, 149 struct scx_sched *from) 150 { 151 if (SCX_HAS_OP(from, sub_cid_sched_updated)) 152 SCX_CALL_OP(from, sub_cid_sched_updated, rq, __scx_cpu_to_cid(cpu_of(rq)), 153 scx_cid_sched_id_from(sch, from)); 154 } 155 156 /** 157 * scx_cid_sched_update - Update rq->scx.sched and notify the scheds affected 158 * @rq: rq whose running session opens or closes 159 * @sch: sched starting a session, %NULL to close the open one 160 * 161 * Every sched whose scx_cid_sched_id_from() value changes is notified of the 162 * new one. Above the deepest common ancestor of the two scheds, both map to the 163 * same child, so the walk stops there. With root R, children A and B, and A's 164 * child A1, a switch from an A1 task to a B task reports: 165 * 166 * R R: A -> B 167 * / \ 168 * A B A: A1 -> NONE B: NONE -> SELF 169 * | 170 * A1 A1: SELF -> NONE 171 * 172 * When the task on one side is not an ext task, there is no common ancestor and 173 * only the other side is walked. 174 */ 175 void scx_cid_sched_update(struct rq *rq, struct scx_sched *sch) 176 { 177 struct scx_sched *prev = rq->scx.sched; 178 s32 level, common = -1; 179 180 lockdep_assert_rq_held(rq); 181 182 if (!static_branch_unlikely(&__scx_ops_cid_sched_updated_enabled) || prev == sch) 183 return; 184 185 rq->scx.sched = sch; 186 187 if (prev && sch) { 188 for (level = min(prev->level, sch->level); level >= 0; level--) 189 if (prev->ancestors[level] == sch->ancestors[level]) 190 break; 191 common = level; 192 scx_cid_notify_sched_updated(rq, sch, prev->ancestors[common]); 193 } 194 if (prev) 195 for (level = common + 1; level <= prev->level; level++) 196 scx_cid_notify_sched_updated(rq, sch, prev->ancestors[level]); 197 if (sch) 198 for (level = common + 1; level <= sch->level; level++) 199 scx_cid_notify_sched_updated(rq, sch, sch->ancestors[level]); 200 } 201 202 /** 203 * scx_ops_cid_sched_updated_enable - Maintain rq->scx.sched if @sch has the op 204 * @sch: sched being enabled, its has_op filled in 205 * 206 * rq->scx.sched is maintained only while a loaded sched implements 207 * ops.sub_cid_sched_updated(), so that everyone else pays one static branch per 208 * session open or close. The first such sched turns the key on and then 209 * initializes every rq from the task running there, in that order so that no 210 * session change in between goes unrecorded. While the key is off every 211 * rq->scx.sched is NULL, see scx_ops_cid_sched_updated_disable(). 212 */ 213 void scx_ops_cid_sched_updated_enable(struct scx_sched *sch) 214 { 215 s32 cpu; 216 217 lockdep_assert_held(&scx_enable_mutex); 218 219 if (!SCX_HAS_OP(sch, sub_cid_sched_updated) || scx_nr_ops_cid_sched_updated++) 220 return; 221 222 static_branch_enable(&__scx_ops_cid_sched_updated_enabled); 223 224 for_each_possible_cpu(cpu) { 225 struct rq *rq = cpu_rq(cpu); 226 struct task_struct *p; 227 228 guard(rq_lock_irqsave)(rq); 229 p = rq->donor; 230 if (p->sched_class == &ext_sched_class && 231 (p->scx.flags & SCX_TASK_RUN_TRACKED)) 232 rq->scx.sched = scx_task_sched(p); 233 } 234 } 235 236 /** 237 * scx_ops_cid_sched_updated_disable - Stop maintaining rq->scx.sched for @sch 238 * @sch: sched being disabled, its tasks all gone 239 * 240 * Close the session on every rq that still points at @sch, before ops.exit(), 241 * so that no sched is notified of @sch once it is gone. The last sched with the 242 * op turns the key off first and clears every rq, so while the key is off every 243 * rq->scx.sched is NULL. A sched whose enable failed before its has_op fill was 244 * never counted, so has_op gates the decrement. 245 */ 246 void scx_ops_cid_sched_updated_disable(struct scx_sched *sch) 247 { 248 bool last; 249 s32 cpu; 250 251 lockdep_assert_held(&scx_enable_mutex); 252 253 last = SCX_HAS_OP(sch, sub_cid_sched_updated) && !--scx_nr_ops_cid_sched_updated; 254 if (last) 255 static_branch_disable(&__scx_ops_cid_sched_updated_enabled); 256 257 /* 258 * Re-homing restarts a running task's session under its new sched. A 259 * task that blocked while its cpu's dispatch had the rq lock dropped is 260 * put and set next again without a restart, so rq->scx.sched keeps @sch 261 * until the pick completes: 262 * 263 * cpu 0, __schedule() cpu 1, scx_sub_disable(@sch) 264 * T of @sch blocks, stops running 265 * dispatch drops the rq lock 266 * re-home T, nothing to restart 267 * this sweep 268 * pick N, N's session opens 269 * 270 * Closing the session here reports NONE to @sch and its ancestors now 271 * and lets the pick report N's sched from NONE instead of from @sch. 272 */ 273 for_each_possible_cpu(cpu) { 274 struct rq *rq = cpu_rq(cpu); 275 276 guard(rq_lock_irqsave)(rq); 277 if (rq->scx.sched == sch) 278 scx_cid_sched_update(rq, NULL); 279 if (last) 280 rq->scx.sched = NULL; 281 } 282 } 283 284 static struct scx_sched *scx_find_sub_sched(u64 cgroup_id) 285 { 286 return rhashtable_lookup(&scx_sched_hash, &cgroup_id, 287 scx_sched_hash_params); 288 } 289 290 void scx_set_task_sched(struct task_struct *p, struct scx_sched *sch) 291 { 292 rcu_assign_pointer(p->scx.sched, sch); 293 } 294 295 struct cgroup *sch_cgroup(struct scx_sched *sch) 296 { 297 return sch->cgrp; 298 } 299 300 /* for each descendant of @cgrp including self, set ->scx_sched to @sch */ 301 void set_cgroup_sched(struct cgroup *cgrp, struct scx_sched *sch) 302 { 303 struct cgroup *pos; 304 struct cgroup_subsys_state *css; 305 306 cgroup_for_each_live_descendant_pre(pos, css, cgrp) 307 rcu_assign_pointer(pos->scx_sched, sch); 308 } 309 310 static void free_pshard(struct scx_pshard *pshard) 311 { 312 struct scx_caps_updated *cu; 313 314 if (!pshard) 315 return; 316 cu = &pshard->caps_updated; 317 if (cu->cmask_arena_out) 318 scx_arena_free(pshard->sch, cu->cmask_arena_out, 319 struct_size_t(struct scx_cmask, bits, 320 SCX_CMASK_NR_WORDS(pshard->nr_cids))); 321 kfree(pshard); 322 } 323 324 void scx_free_pshards(struct scx_sched *sch) 325 { 326 s32 si; 327 328 if (!sch->pshard) 329 return; 330 for (si = 0; si < sch->nr_pshards; si++) 331 free_pshard(sch->pshard[si]); 332 kfree(sch->pshard); 333 } 334 335 static struct scx_pshard *alloc_pshard(struct scx_sched *sch, s32 shard_idx, s32 node) 336 { 337 const struct scx_cid_shard *shard = 338 &rcu_dereference_protected(scx_cid_shard_ranges, 339 lockdep_is_held(&scx_enable_mutex))[shard_idx]; 340 size_t cmask_size = struct_size_t(struct scx_cmask, bits, 341 SCX_CMASK_NR_WORDS(shard->nr_cids)); 342 struct scx_pshard *pshard; 343 struct scx_caps_updated *cu; 344 s32 i; 345 346 pshard = kzalloc_node(sizeof(*pshard), GFP_KERNEL, node); 347 if (!pshard) 348 return NULL; 349 350 raw_spin_lock_init(&pshard->lock); 351 pshard->sch = sch; 352 pshard->base = shard->base_cid; 353 pshard->nr_cids = shard->nr_cids; 354 355 for (i = 0; i < __SCX_NR_CAPS; i++) 356 scx_cmask_init(&pshard->caps[i].cmask, shard->base_cid, shard->nr_cids); 357 358 cu = &pshard->caps_updated; 359 raw_spin_lock_init(&cu->lock); 360 INIT_LIST_HEAD(&cu->node_in_flight); 361 __scx_cmask_init(&cu->cmask, shard->base_cid, shard->nr_cids, SCX_CID_SHARD_MAX_CPUS); 362 363 cu->cmask_arena_out = scx_arena_alloc(sch, cmask_size); 364 if (!cu->cmask_arena_out) { 365 free_pshard(pshard); 366 return NULL; 367 } 368 369 scx_cmask_init(cu->cmask_arena_out, shard->base_cid, shard->nr_cids); 370 371 return pshard; 372 } 373 374 s32 scx_alloc_pshards(struct scx_sched *sch) 375 { 376 struct scx_pshard **pshard; 377 s32 *shard_node; 378 s32 si; 379 380 if (!sch->is_cid_type || !sch->arena_pool) 381 return 0; 382 383 shard_node = rcu_dereference_protected(scx_shard_node, 384 lockdep_is_held(&scx_enable_mutex)); 385 386 pshard = kzalloc_objs(pshard[0], scx_nr_cid_shards); 387 if (!pshard) 388 return -ENOMEM; 389 390 for (si = 0; si < scx_nr_cid_shards; si++) { 391 pshard[si] = alloc_pshard(sch, si, shard_node[si]); 392 if (!pshard[si]) { 393 while (--si >= 0) 394 free_pshard(pshard[si]); 395 kfree(pshard); 396 return -ENOMEM; 397 } 398 } 399 400 sch->nr_pshards = scx_nr_cid_shards; 401 /* 402 * Publish only after every entry is built so a reader observing 403 * @sch->pshard never sees a partially-filled array or unpublished cid 404 * tables. Pair the store with a barrier and an acquire load on the 405 * read side. 406 */ 407 smp_wmb(); 408 WRITE_ONCE(sch->pshard, pshard); 409 return 0; 410 } 411 412 /* 413 * Seed the root's caps fully. Root owns all cids on all caps at enable time. 414 * Children acquire caps via scx_bpf_sub_grant(). 415 */ 416 void scx_init_root_caps(struct scx_sched *sch) 417 { 418 s32 si, i; 419 420 for (si = 0; si < sch->nr_pshards; si++) { 421 struct scx_pshard *ps = sch->pshard[si]; 422 423 for (i = 0; i < __SCX_NR_CAPS; i++) 424 scx_cmask_fill(&ps->caps[i].cmask); 425 } 426 } 427 428 /* unserved remainder of @rq's rescuee's admitted slice, 0 once fully served */ 429 static s64 scx_rescue_slice_remaining(struct rq *rq) 430 { 431 return max(rq->scx.rescue.slice - rq->scx.rescue.served, 0); 432 } 433 434 /* 435 * Decay @pcpu's rescue usage average in place, halving per the knob-derived 436 * halflife, see scx_rescue_set_knobs(). The timestamp advances only by whole 437 * halflives. 438 */ 439 static u64 scx_rescue_decay_avg(struct scx_sched_pcpu *pcpu) 440 { 441 unsigned long halflife = scx_rescue_decay_halflife; 442 u64 n = div_u64(get_jiffies_64() - pcpu->rescue_avg_at, halflife); 443 444 if (n) { 445 pcpu->rescue_avg = n < 64 ? pcpu->rescue_avg >> n : 0; 446 pcpu->rescue_avg_at += n * halflife; 447 } 448 return pcpu->rescue_avg; 449 } 450 451 /** 452 * scx_rescue_charge - Charge the rescuee's runtime 453 * @rq: rq the rescuee is running on 454 * @delta_exec: runtime being charged 455 * 456 * Also ends the rescue once the admitted slice has been served in full. Ending 457 * on served time rather than slice exhaustion bounds both the rescue and the 458 * charging when a scheduler extends the rescuee's slice. 459 */ 460 void scx_rescue_charge(struct rq *rq, s64 delta_exec) 461 { 462 struct scx_sched_pcpu *pcpu; 463 464 lockdep_assert_rq_held(rq); 465 466 /* 467 * Count @delta_exec as served before the clamp below, which bounds only 468 * the budget charge. update_curr_scx() took the same delta off the 469 * slice, so a slice set to the unserved remainder, as escalation does, 470 * reaches zero when the remainder does, see scx_rescue_keep(). 471 */ 472 rq->scx.rescue.served += delta_exec; 473 474 /* 475 * A rescue slice is bounded by one quantum and tick-driven expiry can 476 * overshoot by up to a tick. Clamp to avoid wild over-charges on VMs. 477 */ 478 delta_exec = min_t(s64, delta_exec, scx_rescue_quantum_ns + TICK_NSEC); 479 480 rq->scx.rescue.budget -= delta_exec; 481 482 /* 483 * The per-cpu usage average feeds the overload victim pick. Charge the 484 * sched running the rescuee, which is the host while the rescuee's 485 * owner is bypassing. 486 */ 487 pcpu = per_cpu_ptr(scx_exec_sched(scx_task_sched(rq->scx.rescue.curr), 488 cpu_of(rq))->pcpu, cpu_of(rq)); 489 pcpu->rescue_avg = scx_rescue_decay_avg(pcpu) + delta_exec; 490 491 if (!scx_rescue_slice_remaining(rq)) 492 scx_task_slice_ended(rq, rq->scx.rescue.curr); 493 } 494 495 /** 496 * scx_rescue_end - End the rescue execution on @rq 497 * @rq: rq of interest 498 * 499 * When no rescuee is left pending, the session is over and the balance above 500 * one quantum dies with it - it would otherwise become a banked license to 501 * preempt the cid owner long after the starvation ended. While waiters remain, 502 * the accrued deficit belongs to the queue and carries into the next rescue. 503 */ 504 void scx_rescue_end(struct rq *rq) 505 { 506 lockdep_assert_rq_held(rq); 507 508 rq->scx.rescue.curr = NULL; 509 if (list_empty(&rq->scx.rescue.dsq.list)) 510 rq->scx.rescue.budget = min(rq->scx.rescue.budget, scx_rescue_quantum_ns); 511 } 512 513 /** 514 * scx_rescue_keep - Keep the rescue going past a zeroed slice 515 * @rq: rq @p is running on 516 * @p: task under rescue 517 * 518 * Decide what an exhausted slice means for the rescuee. dispatch_one() calls 519 * this when nothing else is runnable and put_prev_task_scx() when another task 520 * won the pick. scx_rescue_charge() ends the rescue the moment the admitted 521 * slice is fully served, so arriving here with the rescue still open means @p 522 * was preempted. Restore the unserved remainder and return %true. @p stays the 523 * rescuee. dispatch_one() keeps it running and put_prev_task_scx() reinserts it 524 * at the tail of the local DSQ, behind whatever preempted the rescuee. 525 * 526 * Return %false to end the rescue instead - the slice is already fully served 527 * or @p is leaving the rq. 528 */ 529 bool scx_rescue_keep(struct rq *rq, struct task_struct *p) 530 { 531 s64 remaining = scx_rescue_slice_remaining(rq); 532 533 lockdep_assert_rq_held(rq); 534 535 if (!remaining || !(p->scx.flags & SCX_TASK_QUEUED)) 536 return false; 537 538 /* never called on a protected rescuee, so the write can't be refused */ 539 if (WARN_ON_ONCE(!scx_set_task_slice(p, remaining))) 540 return false; 541 return true; 542 } 543 544 /** 545 * scx_rescue_accrue - Accrue budget at the configured fraction of elapsed time 546 * @rq: rq of interest 547 * 548 * A session spans from the first arrival until no rescuee is left, pending or 549 * admitted. While one is active the cap is three quanta and the balance drives 550 * escalation, see scx_rescue_timerfn(). Outside a session the cap is one 551 * quantum, so an idle gap funds the next arrival's admission but never an 552 * escalation. 553 */ 554 static void scx_rescue_accrue(struct rq *rq) 555 { 556 bool in_session = rq->scx.rescue.curr || !list_empty(&rq->scx.rescue.dsq.list); 557 s64 cap = in_session ? 3 * scx_rescue_quantum_ns : scx_rescue_quantum_ns; 558 s64 delta; 559 u64 now; 560 561 lockdep_assert_rq_held(rq); 562 563 /* not every path here holds an updated rq clock, use __scx_bpf_now() */ 564 now = __scx_bpf_now(rq); 565 delta = now - rq->scx.rescue.clock; 566 rq->scx.rescue.clock = now; 567 568 /* 569 * Avoid multiplication overflows by taking a shortcut when the gap is 570 * large enough to fill the budget. 571 */ 572 if (delta >= scx_rescue_sat_delta_ns) 573 rq->scx.rescue.budget = cap; 574 else 575 rq->scx.rescue.budget = 576 min(cap, rq->scx.rescue.budget + 577 ((delta * scx_rescue_bw_1024) >> SCHED_CAPACITY_SHIFT)); 578 } 579 580 /* 581 * The slice for the next admission - the quantum divided across the stranded 582 * tasks so that a crowded queue round-robins on shorter slices. 583 */ 584 static s64 scx_rescue_next_slice(struct rq *rq) 585 { 586 s64 min_slice = max_t(s64, SCX_RESCUE_MIN_SLICE_US * NSEC_PER_USEC, TICK_NSEC); 587 u32 depth = rq->scx.rescue.dsq.nr ?: 1; 588 589 return clamp(div_s64(scx_rescue_quantum_ns, depth), min_slice, scx_rescue_quantum_ns); 590 } 591 592 static void scx_rescue_timer_arm(struct rq *rq) 593 { 594 struct timer_list *timer = &rq->scx.rescue.timer; 595 s64 delay = scx_rescue_quantum_ns / 4; /* should be granular enough */ 596 597 if (timer_pending(timer)) 598 return; 599 600 /* 601 * While the head waiter can't be admitted because the bucket is short 602 * of a full quantum, stretch to the full funding delay. 603 */ 604 if (!rq->scx.rescue.curr && rq->scx.rescue.budget < scx_rescue_quantum_ns) { 605 s64 deficit = scx_rescue_quantum_ns - rq->scx.rescue.budget; 606 607 delay = max(delay, 608 div_s64(deficit << SCHED_CAPACITY_SHIFT, scx_rescue_bw_1024)); 609 } 610 611 /* +1 rounds up so the beat is due by the time the timer fires */ 612 timer->expires = jiffies + nsecs_to_jiffies(delay) + 1; 613 add_timer_on(timer, cpu_of(rq)); 614 } 615 616 /** 617 * scx_rescue_admit - Start rescuing @p on @rq 618 * @rq: rq @p is being admitted on 619 * @p: task being admitted, off any DSQ 620 * @slice: CPU time to grant 621 * 622 * The slice is a kernel slice, see %SCX_TASK_KERNEL_SLICE. The schedulers may 623 * preempt @p or shorten its slice, never extend it. @slice is measured on 624 * served CPU time, so neither shortens the rescue, see scx_rescue_charge() and 625 * scx_rescue_keep(). Prolonged denial escalates into protected execution, see 626 * scx_rescue_timerfn(). 627 */ 628 static void scx_rescue_admit(struct rq *rq, struct task_struct *p, s64 slice) 629 { 630 lockdep_assert_rq_held(rq); 631 WARN_ON_ONCE(rq->scx.rescue.curr); 632 633 rq->scx.rescue.curr = p; 634 rq->scx.rescue.slice = slice; 635 rq->scx.rescue.served = 0; 636 scx_set_task_slice(p, slice); 637 p->scx.flags |= SCX_TASK_KERNEL_SLICE; 638 scx_rescue_timer_arm(rq); 639 } 640 641 /** 642 * scx_rescue_try_admit - Try to admit a freshly stranded task 643 * @rq: rq @p is being inserted on 644 * @p: stranded task being diverted to rescue 645 * 646 * One rescue at a time and earlier arrivals go first. Admission needs a full 647 * quantum of budget, spent as the rescue runs. Return %true if @p was admitted 648 * and should be inserted at the tail of @rq's local DSQ, %false if it has to 649 * park on the rescue DSQ, with the timer armed to admit it later. 650 */ 651 static bool scx_rescue_try_admit(struct rq *rq, struct task_struct *p) 652 { 653 scx_rescue_accrue(rq); 654 655 if (!rq->scx.rescue.curr && list_empty(&rq->scx.rescue.dsq.list) && 656 rq->scx.rescue.budget >= scx_rescue_quantum_ns) { 657 scx_rescue_admit(rq, p, scx_rescue_quantum_ns); 658 return true; 659 } 660 661 scx_rescue_timer_arm(rq); 662 return false; 663 } 664 665 /** 666 * scx_rescue_check_overload - Eject the top rescue consumer on a stuck rescue 667 * @rq: rq whose rescue timer fired 668 * 669 * If the oldest waiter on @rq's rescue DSQ has been queued for too long, rescue 670 * demand on this cpu persistently exceeds the configured bandwidth. Eject the 671 * sub with the highest recent rescue consumption instead of letting the 672 * scheduler stall path blame the sched running the waiter, which may just be 673 * crowded out. 674 */ 675 static void scx_rescue_check_overload(struct rq *rq) 676 { 677 struct scx_sched *victim = NULL, *pos; 678 struct task_struct *p; 679 int cpu = cpu_of(rq); 680 u64 max_avg = 0; 681 u32 dur_ms; 682 683 lockdep_assert_rq_held(rq); 684 685 p = list_first_entry_or_null(&rq->scx.rescue.dsq.list, struct task_struct, 686 scx.dsq_list.node); 687 if (!p) 688 return; 689 690 /* has the head waiter been queued for longer than the threshold? */ 691 if (time_before(jiffies, p->scx.rescue_at + scx_rescue_overload_after)) 692 return; 693 694 /* 695 * Grace period after the last ejection on this cpu - the freed 696 * bandwidth gets one threshold's worth of time to drain the backlog 697 * before another sub is judged. 698 */ 699 if (time_before64(get_jiffies_64(), rq->scx.rescue.kill_at + 700 scx_rescue_overload_after)) 701 return; 702 703 list_for_each_entry_rcu(pos, &scx_sched_all, all) { 704 u64 avg = scx_rescue_decay_avg(per_cpu_ptr(pos->pcpu, cpu)); 705 706 /* skip an already-exiting sub, else the ejection is wasted */ 707 if (pos->level && avg > max_avg && 708 atomic_read(&pos->exit_kind) == SCX_EXIT_NONE) { 709 max_avg = avg; 710 victim = pos; 711 } 712 } 713 if (!victim) 714 return; 715 716 rq->scx.rescue.kill_at = get_jiffies_64(); 717 dur_ms = jiffies_to_msecs(jiffies - p->scx.rescue_at); 718 __scx_exit(victim, SCX_EXIT_ERROR_RESCUE, 0, cpu, 719 "used too much rescue CPU time (%llums) while %s[%d] waited %u.%03us to be rescued", 720 div_u64(max_avg, NSEC_PER_MSEC), p->comm, p->pid, dur_ms / 1000, 721 dur_ms % 1000); 722 } 723 724 /** 725 * scx_rescue_timerfn - Drive and pace rescue execution 726 * @timer: rq->scx.rescue.timer 727 * 728 * Runs every quarter quantum while a rescuee exists, pending or admitted, see 729 * scx_rescue_timer_arm(). The head waiter is admitted once the bucket holds a 730 * full quantum and granted its slice, see scx_rescue_next_slice(). A session 731 * whose budget accumulates over two quanta with the admitted rescuee still 732 * waiting escalates - the rescuee's remaining slice turns into protected 733 * execution and it preempts the current task. An overloaded rescue queue ejects 734 * the top consumer, see scx_rescue_check_overload(). 735 */ 736 static void scx_rescue_timerfn(struct timer_list *timer) 737 { 738 struct rq *rq = timer_container_of(rq, timer, scx.rescue.timer); 739 struct task_struct *p; 740 741 guard(rq_lock_irqsave)(rq); 742 743 p = rq->scx.rescue.curr; 744 if (!p && list_empty(&rq->scx.rescue.dsq.list)) 745 return; 746 747 scx_rescue_accrue(rq); 748 scx_rescue_check_overload(rq); 749 750 if (!p) { 751 s64 slice = scx_rescue_next_slice(rq); 752 753 /* no rescue in progress */ 754 if (rq->scx.rescue.budget < scx_rescue_quantum_ns) 755 goto out_arm; 756 757 /* there's enough budget to start rescuing the next one */ 758 p = list_first_entry(&rq->scx.rescue.dsq.list, struct task_struct, 759 scx.dsq_list.node); 760 scx_task_unlink_from_dsq(p, &rq->scx.rescue.dsq); 761 scx_rescue_admit(rq, p, slice); 762 scx_move_local_task_to_local_dsq(scx_task_sched(p), p, 763 SCX_ENQ_IGNORE_CAPS, rq); 764 if (sched_class_above(&ext_sched_class, rq->donor->sched_class)) 765 resched_curr(rq); 766 } else if (p->scx.dsq && rq->scx.rescue.budget > 2 * scx_rescue_quantum_ns) { 767 /* 768 * The rescuee waited for the CPU for too long. Escalate - grant 769 * the unserved remainder, protect it from the schedulers and 770 * preempt the current task. The slice is set before the 771 * protection. Repeat beats only repeat the head move - the 772 * slice write is refused on a protected task. 773 */ 774 scx_set_task_slice(p, scx_rescue_slice_remaining(rq)); 775 p->scx.flags |= SCX_TASK_PROTECTED; 776 scx_task_unlink_from_dsq(p, &rq->scx.local_dsq); 777 scx_move_local_task_to_local_dsq(scx_task_sched(p), p, 778 SCX_ENQ_HEAD | SCX_ENQ_PREEMPT | SCX_ENQ_IGNORE_CAPS, 779 rq); 780 } 781 out_arm: 782 scx_rescue_timer_arm(rq); 783 } 784 785 /* flush out tasks waiting for rescue before a CPU goes down */ 786 void scx_rescue_flush(struct rq *rq) 787 { 788 struct task_struct *p, *n; 789 790 lockdep_assert_rq_held(rq); 791 792 /* end the current rescue */ 793 if (rq->scx.rescue.curr) 794 scx_task_slice_ended(rq, rq->scx.rescue.curr); 795 796 /* and flush out all pending ones */ 797 list_for_each_entry_safe(p, n, &rq->scx.rescue.dsq.list, scx.dsq_list.node) { 798 scx_task_unlink_from_dsq(p, &rq->scx.rescue.dsq); 799 scx_move_local_task_to_local_dsq(scx_task_sched(p), p, 800 SCX_ENQ_IGNORE_CAPS, rq); 801 } 802 803 timer_delete(&rq->scx.rescue.timer); 804 } 805 806 void scx_rescue_dump(struct seq_buf *s, struct rq *rq) 807 { 808 struct task_struct *p = rq->scx.rescue.curr; 809 810 scx_dump_line(s, " rescue=%u budget=%lldus rescuing=%s[%d]", 811 rq->scx.rescue.dsq.nr, 812 div_s64(rq->scx.rescue.budget, NSEC_PER_USEC), 813 p ? p->comm : "none", p ? p->pid : -1); 814 } 815 816 /* 817 * A scheduler whose stall watchdog is shorter than the overload threshold gets 818 * stall-killed over its parked waiters before the overload check can eject the 819 * actual top consumer. The root's knobs set the threshold, warn on any 820 * scheduler that doesn't fit it. 821 */ 822 static void scx_rescue_check_timeout(struct scx_sched *sch) 823 { 824 if (!scx_rescue_bw_1024 || sch->watchdog_timeout > scx_rescue_overload_after) 825 return; 826 827 pr_warn("sched_ext: %s: watchdog timeout %ums <= rescue overload threshold %ums\n", 828 sch->ops.name, jiffies_to_msecs(sch->watchdog_timeout), 829 jiffies_to_msecs(scx_rescue_overload_after)); 830 } 831 832 /* latch the rescue parameters on root scheduler enable */ 833 void scx_rescue_set_knobs(struct scx_sched *sch) 834 { 835 s32 bw_ppt = sch->ops.rescue_bandwidth_ppt ?: SCX_RESCUE_DFL_BW_PPT; 836 s64 quantum_us = sch->ops.rescue_quantum_us ?: SCX_RESCUE_DFL_QUANTUM_US; 837 s64 period_ns; 838 839 if (sch->ops.rescue_bandwidth_ppt == SCX_RESCUE_DISABLE) { 840 scx_rescue_bw_1024 = 0; 841 return; 842 } 843 844 scx_rescue_bw_1024 = bw_ppt * SCHED_CAPACITY_SCALE / 1000; 845 scx_rescue_quantum_ns = max(quantum_us * NSEC_PER_USEC, TICK_NSEC); 846 scx_rescue_sat_delta_ns = 847 div_s64((4 * scx_rescue_quantum_ns + TICK_NSEC) << SCHED_CAPACITY_SHIFT, 848 scx_rescue_bw_1024); 849 850 /* 851 * The overload threshold and the decay halflife scale with the funding 852 * period - the time the bucket takes to fund one full quantum. 853 */ 854 period_ns = div_s64(scx_rescue_quantum_ns << SCHED_CAPACITY_SHIFT, scx_rescue_bw_1024); 855 scx_rescue_overload_after = 856 clamp(nsecs_to_jiffies(SCX_RESCUE_OVERLOAD_MULT * period_ns), 857 msecs_to_jiffies(SCX_RESCUE_MIN_OVERLOAD_MS), 858 msecs_to_jiffies(SCX_RESCUE_MAX_OVERLOAD_MS)); 859 scx_rescue_decay_halflife = scx_rescue_overload_after / 4; 860 861 /* a single in-budget wait must not cross the overload trigger */ 862 if (nsecs_to_jiffies(period_ns) > scx_rescue_overload_after / 2) 863 pr_warn("sched_ext: %s: rescue funding period %lldms > overload threshold %ums / 2\n", 864 sch->ops.name, div_s64(period_ns, NSEC_PER_MSEC), 865 jiffies_to_msecs(scx_rescue_overload_after)); 866 867 scx_rescue_check_timeout(sch); 868 } 869 870 void scx_rescue_init(struct rq *rq) 871 { 872 BUG_ON(scx_init_dsq(&rq->scx.rescue.dsq, SCX_DSQ_RESCUE, NULL)); 873 timer_setup(&rq->scx.rescue.timer, scx_rescue_timerfn, TIMER_PINNED); 874 rq->scx.rescue.kill_at = get_jiffies_64(); 875 } 876 877 /** 878 * __scx_resolve_local_dsq - Pick the local, rescue or reject DSQ for an insert 879 * @sch: enqueuing sub-sched 880 * @rq: rq whose local DSQ @p targets 881 * @p: task being inserted 882 * @enq_flags: in/out, unhonored flags are cleared 883 * 884 * Return @rq's local DSQ if @sch holds the required caps on @rq's cid. 885 * Otherwise, return @rq's rescue DSQ if the insert carries %SCX_ENQ_RESCUE and 886 * rescue is enabled, or @rq's reject DSQ after recording the reenq reason on 887 * @p. 888 * 889 * %SCX_ENQ_IMMED, %SCX_ENQ_PREEMPT, %SCX_ENQ_PREEMPT_LAZY and %SCX_ENQ_HEAD are 890 * cleared when diverting to rescue or reject. %SCX_ENQ_PREEMPT and 891 * %SCX_ENQ_PREEMPT_LAZY are also cleared on a fallback migration-disabled 892 * admission. 893 * 894 * bypass_enq_target_dsq() also calls this with the host as @sch when the host 895 * lacks %SCX_CAP_BASE on @rq's cid, if rescue is enabled or @p must run on the 896 * cpu, migration-disabled or with a migration pending. The bypassed task is 897 * then admitted or diverted like a capless %SCX_ENQ_RESCUE insert by the host 898 * itself. 899 */ 900 struct scx_dispatch_q *__scx_resolve_local_dsq(struct scx_sched *sch, struct rq *rq, 901 struct task_struct *p, u64 *enq_flags) 902 { 903 s32 cid = __scx_cpu_to_cid(cpu_of(rq)); 904 struct scx_sched *asch = rq->scx.remote_activate_sch ?: sch; 905 u64 needed = scx_caps_for_enq(*enq_flags); 906 u64 missing; 907 908 /* 909 * On a remote activation the scheduling sched (@asch) differs from 910 * @p's owner (@sch). Check caps against the scheduling sched. 911 */ 912 if (*enq_flags & (SCX_ENQ_PREEMPT | SCX_ENQ_PREEMPT_LAZY)) 913 needed |= scx_caps_for_preempt(asch, rq, *enq_flags); 914 missing = scx_missing_caps(asch, cpu_of(rq), needed); 915 916 /* requirements met */ 917 if (likely(!missing)) 918 return &rq->scx.local_dsq; 919 920 /* 921 * The task must run on this CPU regardless of caps: ops.enqueue() is 922 * skipped while the CPU is going down or before the root's 923 * ops.cpu_online(), the task is migration-disabled, or a migration is 924 * pending. Admit despite the missing caps and count it. Refuse 925 * preemptions. 926 */ 927 if (unlikely(!scx_rq_online(rq) || is_migration_disabled(p) || 928 p->migration_pending)) { 929 __scx_add_event(sch, SCX_EV_SUB_FORCED_ADMIT, 1); 930 *enq_flags &= ~(SCX_ENQ_PREEMPT | SCX_ENQ_PREEMPT_LAZY); 931 return &rq->scx.local_dsq; 932 } 933 934 /* 935 * Diverting to rescue or reject, neither of which honors IMMED, PREEMPT 936 * or HEAD - a diversion has no priority and IMMED is not allowed on 937 * non-local DSQs. Strip the enq and task flags along with the slice. 938 */ 939 scx_divert_strip_flags(p, enq_flags); 940 941 /* the enqueuer opted for rescue instead of rejection and reenqueue */ 942 if (scx_rescue_enabled() && (*enq_flags & SCX_ENQ_RESCUE)) { 943 __scx_add_event(sch, SCX_EV_SUB_RESCUE, 1); 944 if (scx_rescue_try_admit(rq, p)) 945 return &rq->scx.local_dsq; 946 947 /* queueing, the overload trigger measures the wait from here */ 948 p->scx.rescue_at = jiffies; 949 return &rq->scx.rescue.dsq; 950 } 951 952 p->scx.reenq_reason_caps = missing; 953 p->scx.reenq_reason_cid = cid; 954 WARN_ON_ONCE(p->scx.flags & SCX_TASK_REENQ_REASON_MASK); 955 p->scx.flags |= SCX_TASK_REENQ_CAP; 956 957 return &rq->scx.reject_dsq; 958 } 959 960 /* @p lost the caps needed to stay on @rq's local DSQ? Record reason if so. */ 961 bool scx_task_reenq_on_cap_revoke(struct rq *rq, struct task_struct *p) 962 { 963 s32 cpu = cpu_of(rq); 964 u64 missing; 965 966 /* migration-disabled tasks and the rescuee are admitted capless */ 967 if (is_migration_disabled(p) || p == scx_rescuee(rq)) 968 return false; 969 970 /* check caps against the sched running a bypassed task */ 971 missing = scx_missing_caps(scx_exec_sched(scx_task_sched(p), cpu), cpu, 972 scx_caps_for_task(p)); 973 if (likely(!missing)) 974 return false; 975 976 p->scx.reenq_reason_caps = missing; 977 p->scx.reenq_reason_cid = __scx_cpu_to_cid(cpu); 978 return true; 979 } 980 981 /* record a caps change, see struct scx_caps_updated */ 982 static void caps_updated_record(struct scx_pshard *ps, const struct scx_cmask *cids, u64 caps, 983 struct list_head *to_deliver) 984 { 985 struct scx_caps_updated *cu = &ps->caps_updated; 986 987 guard(raw_spinlock)(&cu->lock); 988 scx_cmask_or(&cu->cmask, cids); 989 cu->caps |= caps; 990 if (list_empty(&cu->node_in_flight)) 991 list_add_tail(&cu->node_in_flight, to_deliver); 992 } 993 994 /* deliver queued caps_updated callbacks, see struct scx_caps_updated */ 995 static void caps_updated_deliver(struct list_head *to_deliver) 996 { 997 struct scx_caps_updated *cu, *tmp; 998 999 list_for_each_entry_safe(cu, tmp, to_deliver, node_in_flight) { 1000 struct scx_pshard *ps = container_of(cu, struct scx_pshard, caps_updated); 1001 struct scx_sched *sch = ps->sch; 1002 1003 while (true) { 1004 u64 caps = 0; 1005 1006 /* 1007 * During enable, has_op is set after ops.sub_attach(), 1008 * so !has_op means the op is absent or the sched isn't 1009 * live yet - e.g. caps grant from ops.sub_attach(). 1010 * Either way don't consume - leave for 1011 * scx_sub_seed_caps() to deliver once has_op is set. 1012 */ 1013 scoped_guard (raw_spinlock, &cu->lock) { 1014 if (cu->caps && SCX_HAS_OP(sch, sub_caps_updated) && 1015 likely(!READ_ONCE(sch->aborting))) { 1016 struct scx_cmask_ref ref; 1017 1018 caps = cu->caps; 1019 scx_cmask_ref_init_kern(sch, cu->cmask_arena_out, 1020 ps->base, ps->nr_cids, &ref); 1021 scx_cmask_ref_copy(&ref, &cu->cmask); 1022 scx_cmask_clear(&cu->cmask); 1023 cu->caps = 0; 1024 } else { 1025 list_del_init(&cu->node_in_flight); 1026 } 1027 } 1028 if (!caps) 1029 break; 1030 1031 /* caps != 0 only when deliverable (has_op, above) */ 1032 SCX_CALL_OP(sch, sub_caps_updated, NULL, cu->cmask_arena_out, caps); 1033 } 1034 } 1035 } 1036 1037 /* 1038 * Deliver caps owed to @sch that couldn't be delivered earlier (e.g. a grant 1039 * taken during its sub_attach(), before has_op was set). Called once has_op is 1040 * set. 1041 */ 1042 static void scx_sub_seed_caps(struct scx_sched *sch) 1043 { 1044 LIST_HEAD(to_deliver); 1045 s32 si; 1046 1047 guard(irqsave)(); 1048 1049 for (si = 0; si < sch->nr_pshards; si++) { 1050 struct scx_pshard *ps = sch->pshard[si]; 1051 struct scx_caps_updated *cu = &ps->caps_updated; 1052 1053 scoped_guard (raw_spinlock, &cu->lock) { 1054 if (cu->caps && list_empty(&cu->node_in_flight)) 1055 list_add_tail(&cu->node_in_flight, &to_deliver); 1056 } 1057 } 1058 caps_updated_deliver(&to_deliver); 1059 } 1060 1061 static u64 calc_effective_caps(struct scx_pshard *ps, s32 cid) 1062 { 1063 u64 ecaps = 0; 1064 u32 cap_bit; 1065 1066 for (cap_bit = 0; cap_bit < __SCX_NR_CAPS; cap_bit++) 1067 if (scx_cmask_test(cid, &ps->caps[cap_bit].cmask)) 1068 ecaps |= BIT_U64(cap_bit) | scx_caps_implied(BIT_U64(cap_bit)); 1069 return ecaps; 1070 } 1071 1072 /** 1073 * queue_sync_ecaps - Queue ecaps update for a (sch, cid) pair 1074 * @sch: sched to update 1075 * @cid: cid to update 1076 * 1077 * Queue an ecaps update for @sch's @cid and reschedule the cpu so that it syncs 1078 * in dispatch_one(). The cpu isn't rescheduled while it is inactive or the root 1079 * bypasses, and its next scheduling event processes the sync then. A grant or 1080 * revoke can run in the PM syscore phase, where irq work can malfunction, see 1081 * scx_kick_cpu(), and the root bypasses throughout PM. Callers that need the 1082 * sync processed promptly reschedule the cpu themselves, see 1083 * resched_sync_ecaps(). 1084 */ 1085 static void queue_sync_ecaps(struct scx_sched *sch, s32 cid) 1086 { 1087 s32 cpu = __scx_cid_to_cpu(cid); 1088 struct scx_sched_pcpu *pcpu = per_cpu_ptr(sch->pcpu, cpu); 1089 1090 /* 1091 * Pairs with smp_mb() in __scx_process_sync_ecaps(). The caller has 1092 * written the state a sync reads, caps[] or cpu_active(). Either the 1093 * check below finds the node off the list and queues a sync, or a sync 1094 * in flight is still ahead of its reads and sees the new state. 1095 */ 1096 smp_mb(); 1097 1098 /* @cid's pshard->lock excludes concurrent queueing attempts */ 1099 if (llist_on_list(&pcpu->ecaps_to_sync_node)) 1100 return; 1101 1102 /* 1103 * A cpu going down processes its syncs in its own picks, see 1104 * scx_offline_ecaps(), and a resched for every change on the cid would 1105 * only keep preempting its hotplug thread. The irq work needs an online 1106 * cpu. An active cpu stays online here, as @cid's pshard->lock keeps 1107 * preemption off, which holds off the stop_machine() that takes a cpu 1108 * offline. 1109 */ 1110 if (llist_add(&pcpu->ecaps_to_sync_node, &cpu_rq(cpu)->scx.ecaps_to_sync) && 1111 cpu_active(cpu) && !scx_bypassing(sch->ancestors[0], smp_processor_id())) 1112 scx_resched_curr_deferred(cpu_rq(cpu)); 1113 } 1114 1115 /* the pshard holding @sch's caps on @cid */ 1116 static struct scx_pshard *cid_pshard(struct scx_sched *sch, s32 cid) 1117 { 1118 return sch->pshard[rcu_dereference_all(scx_cid_to_shard)[cid]]; 1119 } 1120 1121 static void ecaps_report_irq_workfn(struct irq_work *irq_work) 1122 { 1123 rcuwait_wake_up(&ecaps_report_wait); 1124 } 1125 1126 static struct irq_work ecaps_report_irq_work = IRQ_WORK_INIT_HARD(ecaps_report_irq_workfn); 1127 1128 /* 1129 * Complete @pcpu's report mark. The waiter in ecaps_report() can't be woken 1130 * under the rq lock, so the last completion wakes it through irq_work. 1131 */ 1132 static void ecaps_report_done(struct scx_sched_pcpu *pcpu) 1133 { 1134 pcpu->flags &= ~SCX_SCHED_PCPU_ECAPS_REPORT; 1135 if (atomic_dec_and_test(&pcpu->sch->nr_ecaps_reports)) 1136 irq_work_queue(&ecaps_report_irq_work); 1137 } 1138 1139 static void ecaps_offline_irq_workfn(struct irq_work *irq_work) 1140 { 1141 wake_up(&ecaps_offline_waitq); 1142 } 1143 1144 static DEFINE_IRQ_WORK(ecaps_offline_irq_work, ecaps_offline_irq_workfn); 1145 1146 /* 1147 * @pcpu's sync marked by scx_offline_ecaps() has been processed or discarded. 1148 * The waiter can't be woken under the rq lock, so the last completion wakes it 1149 * through irq_work. The marks are all done while the cpu's hotplug thread waits 1150 * in scx_offline_ecaps(), before hotplug parks any irq_work thread, so a 1151 * regular irq_work is enough. 1152 */ 1153 static void ecaps_offline_done(struct rq *rq, struct scx_sched_pcpu *pcpu) 1154 { 1155 lockdep_assert_rq_held(rq); 1156 1157 pcpu->flags &= ~SCX_SCHED_PCPU_ECAPS_OFFLINE; 1158 WRITE_ONCE(rq->scx.nr_ecaps_offline, rq->scx.nr_ecaps_offline - 1); 1159 if (!rq->scx.nr_ecaps_offline) 1160 irq_work_queue(&ecaps_offline_irq_work); 1161 } 1162 1163 /* 1164 * Test whether the hotplug operation in progress is suspend or hibernation 1165 * taking a cpu down or bringing it back. A kexec jump also sets 1166 * cpuhp_tasks_frozen but sends no PM notification, so outside a PM cycle its 1167 * cpu downs deliver their losses as in regular hotplug. 1168 */ 1169 static bool scx_pm_frozen(void) 1170 { 1171 return cpuhp_tasks_frozen && READ_ONCE(scx_pm_in_progress); 1172 } 1173 1174 /** 1175 * __scx_process_sync_ecaps - Sync this cpu's ecaps to pshard->caps[] 1176 * @rq: the cid's cpu rq 1177 * @prev: @rq's previous task from the in-progress dispatch 1178 * 1179 * pshard->caps[] is the target configuration. pcpu->ecaps is the effective 1180 * transposed copy owned by the cid's cpu and written only here under @rq's 1181 * lock. 1182 * 1183 * A sched's ecaps change only with a delivery, so that whenever an op of the 1184 * sched runs under @rq's lock, its ecaps are what its deliveries reported. A 1185 * sync that can't deliver leaves them alone, and a later one that can reports 1186 * the net change. 1187 * 1188 * A sched that newly gains baseline access here is owed an update_idle() so it 1189 * learns the cid's idle state. Such a gain arms the per-rq 1190 * %SCX_RQ_SUB_IDLE_RENOTIFY gate so the next idle pick delivers it. 1191 */ 1192 void __scx_process_sync_ecaps(struct rq *rq, struct task_struct *prev) 1193 { 1194 s32 cpu = cpu_of(rq); 1195 s32 cid; 1196 struct llist_node *batch, *pos, *tmp; 1197 u64 lost_all = 0; 1198 1199 if (likely(llist_empty(&rq->scx.ecaps_to_sync))) 1200 return; 1201 1202 /* @cid stays valid while a root is enabled */ 1203 cid = __scx_cpu_to_cid(cpu); 1204 1205 batch = llist_del_all(&rq->scx.ecaps_to_sync); 1206 llist_for_each_safe(pos, tmp, batch) { 1207 struct scx_sched_pcpu *pcpu = 1208 container_of(pos, struct scx_sched_pcpu, ecaps_to_sync_node); 1209 struct scx_pshard *ps = cid_pshard(pcpu->sch, cid); 1210 bool report = pcpu->flags & SCX_SCHED_PCPU_ECAPS_REPORT; 1211 bool offline = pcpu->flags & SCX_SCHED_PCPU_ECAPS_OFFLINE; 1212 u64 old, ecaps, lost, gained; 1213 1214 init_llist_node(pos); 1215 1216 /* pairs with smp_mb() in queue_sync_ecaps(), see there */ 1217 smp_mb(); 1218 1219 /* 1220 * Before the sched's has_op is set, only the parent's op would 1221 * run, and the change would never reach the sched. 1222 * ecaps_enable() enables deliveries on each cpu once has_op is 1223 * set. Deliveries also need the cpu online to the root, see 1224 * handle_hotplug(). 1225 * 1226 * An inactive cpu that can deliver is going down and reads as 1227 * capless. A delivery below can drop the rq lock and the cpu's 1228 * active state can change between syncs, so test it per sync. 1229 * Suspend and hibernation don't deliver the loss of a cpu they 1230 * take down, see scx_offline_ecaps(). 1231 * 1232 * A sync that can't deliver leaves the ecaps alone. It may 1233 * still carry a mark that is cleared below. Don't skip the rest 1234 * of the loop for it. 1235 */ 1236 old = READ_ONCE(pcpu->ecaps); 1237 if (!(pcpu->flags & SCX_SCHED_PCPU_ECAPS_ENABLED) || 1238 !(rq->scx.flags & SCX_RQ_OPS_ONLINE)) 1239 ecaps = old; 1240 else if (cpu_active(cpu)) 1241 ecaps = calc_effective_caps(ps, cid); 1242 else if (scx_pm_frozen()) 1243 ecaps = old; 1244 else 1245 ecaps = 0; 1246 WRITE_ONCE(pcpu->ecaps, ecaps); 1247 1248 lost = old & ~ecaps; 1249 gained = ecaps & ~old; 1250 lost_all |= lost; 1251 1252 /* 1253 * The bypass DSQ on this cpu is no longer consumed, so drain 1254 * it. A bypassing sched's own bypass DSQs are empty, as its 1255 * tasks sit on the host's. 1256 */ 1257 if ((lost & SCX_CAP_BASE) && !scx_bypassing(pcpu->sch, cpu)) 1258 scx_bypass_lb_kick(pcpu->sch); 1259 1260 /* 1261 * Tell the sched and its parent that the sched's effective caps 1262 * on this cid changed. The invocations are equivalent to the 1263 * dispatch path and may drop and re-acquire the rq lock 1264 * temporarily while the rest of @batch is held privately, see 1265 * scx_discard_ecaps_to_sync(). The dispatch kfuncs resolve 1266 * their context on the executing cpu, which under core 1267 * scheduling can differ from @rq's cpu, so the context is set 1268 * up there. The rq recorded in it keeps the dispatches 1269 * targeting @rq. 1270 */ 1271 if (ecaps != old) { 1272 struct scx_sched *parent = scx_parent(pcpu->sch); 1273 struct scx_dsp_ctx *dspc; 1274 1275 /* stash @prev so nested dispatches can access it */ 1276 rq->scx.sub_dispatch_prev = prev; 1277 1278 /* a disabling sched's ops are not called */ 1279 if (SCX_HAS_OP(pcpu->sch, sub_ecaps_updated) && 1280 likely(!READ_ONCE(pcpu->sch->aborting))) { 1281 dspc = &this_cpu_ptr(pcpu->sch->pcpu)->dsp_ctx; 1282 dspc->rq = rq; 1283 SCX_CALL_OP(pcpu->sch, sub_ecaps_updated, rq, 1284 scx_cpu_arg(cpu), old, ecaps); 1285 scx_flush_dispatch_buf(pcpu->sch, rq); 1286 } 1287 if (SCX_HAS_OP(parent, sub_child_ecaps_updated) && 1288 likely(!READ_ONCE(parent->aborting))) { 1289 dspc = &this_cpu_ptr(parent->pcpu)->dsp_ctx; 1290 dspc->rq = rq; 1291 SCX_CALL_OP(parent, sub_child_ecaps_updated, rq, 1292 pcpu->sch->ops.sub_cgroup_id, scx_cpu_arg(cpu), 1293 old, ecaps); 1294 scx_flush_dispatch_buf(parent, rq); 1295 } 1296 rq->scx.sub_dispatch_prev = NULL; 1297 } 1298 1299 if (report) 1300 ecaps_report_done(pcpu); 1301 if (offline) 1302 ecaps_offline_done(rq, pcpu); 1303 1304 /* 1305 * Gaining baseline access owes an update_idle() so the sched 1306 * learns the cpu's idle state. Arm the per-rq gate so the next 1307 * idle pick flushes it. Losing access drops any pending notify. 1308 */ 1309 if (gained & SCX_CAP_BASE) { 1310 pcpu->idle_renotify = true; 1311 rq->scx.flags |= SCX_RQ_SUB_IDLE_RENOTIFY; 1312 } else if (lost & SCX_CAP_BASE) { 1313 pcpu->idle_renotify = false; 1314 } 1315 } 1316 1317 /* 1318 * Losing a cap can strand already-queued tasks. Schedule a reenq scan 1319 * to move the now-capless ones off the local DSQ. The scan tests 1320 * against the effective caps and thus must come after the ecaps sync. 1321 */ 1322 if (lost_all & SCX_CAPS_REENQ_ON_LOSS) 1323 scx_schedule_reenq_local(rq, SCX_REENQ_CAP_REVOKE); 1324 } 1325 1326 void scx_sub_pm_begin(void) 1327 { 1328 WRITE_ONCE(scx_pm_in_progress, true); 1329 } 1330 1331 /* 1332 * Called on every cpu down and up whether or not a root is loaded, so that the 1333 * set stays exact when a root is enabled or disabled during a PM cycle. A cpu 1334 * that failed to come back from suspend or hibernation can come back through 1335 * regular hotplug before the PM cycle ends, e.g. through the SMT control. The 1336 * reseed at its activation reports the net change, so any up removes the cpu 1337 * from the set. 1338 */ 1339 void scx_update_frozen_cpus(s32 cpu, bool online) 1340 { 1341 if (online) { 1342 if (!cpumask_test_cpu(cpu, &scx_frozen_cpus)) 1343 return; 1344 __cpumask_clear_cpu(cpu, &scx_frozen_cpus); 1345 if (cpumask_empty(&scx_frozen_cpus)) 1346 wake_up_all(&scx_frozen_cpus_waitq); 1347 } else if (scx_pm_frozen()) { 1348 __cpumask_set_cpu(cpu, &scx_frozen_cpus); 1349 } 1350 } 1351 1352 /* 1353 * The PM cycle is over. A cpu still in the set failed to come back, and its 1354 * loss can't be delivered anymore. That breaks the guarantee that every ecaps 1355 * change reaches the sub-scheds and their parents, so abort every sched. A root 1356 * without sub-scheds is owed no reports and keeps running. 1357 * 1358 * Abort before clearing the set and waking the detaches in scx_sub_disable(), 1359 * so that a parent whose ops.sub_detach() runs with that loss unreported is 1360 * already being disabled, which ops.sub_detach() allows for. No exit cpu is 1361 * recorded, as the cpu running this isn't the one that failed. 1362 */ 1363 void scx_sub_pm_end(void) 1364 { 1365 /* hotplug updates the set under cpus_write_lock() */ 1366 guard(cpus_read_lock)(); 1367 1368 if (unlikely(!cpumask_empty(&scx_frozen_cpus)) && scx_has_subs()) { 1369 struct scx_sched *root; 1370 1371 guard(rcu)(); 1372 root = rcu_dereference(scx_root); 1373 if (root) 1374 __scx_exit(root, SCX_EXIT_ERROR, 0, -1, 1375 "%u cpu(s) failed to come back after suspend or hibernation", 1376 cpumask_weight(&scx_frozen_cpus)); 1377 } 1378 1379 WRITE_ONCE(scx_pm_in_progress, false); 1380 cpumask_clear(&scx_frozen_cpus); 1381 wake_up_all(&scx_frozen_cpus_waitq); 1382 } 1383 1384 /* 1385 * Called with cpus_read_lock() held before the root is published. The cpus 1386 * active now are online to the root without ops.cpu_online(), so they can 1387 * deliver ecaps. handle_hotplug() maintains %SCX_RQ_OPS_ONLINE from here on. 1388 */ 1389 void scx_init_rq_ops_online(void) 1390 { 1391 s32 cpu; 1392 1393 lockdep_assert_cpus_held(); 1394 1395 for_each_possible_cpu(cpu) { 1396 struct rq *rq = cpu_rq(cpu); 1397 1398 guard(rq_lock_irqsave)(rq); 1399 if (cpu_active(cpu)) 1400 rq->scx.flags |= SCX_RQ_OPS_ONLINE; 1401 else 1402 rq->scx.flags &= ~SCX_RQ_OPS_ONLINE; 1403 } 1404 } 1405 1406 /* 1407 * Make @rq's cpu dispatch through the ext class to process its ecaps syncs. 1408 * queue_sync_ecaps() reschedules only when the cpu has no sync queued yet, 1409 * never an inactive cpu, and not while the root bypasses, so reschedule here. 1410 * The callers run on the cpu's hotplug thread or in ecaps_report(), never in 1411 * the PM syscore phase. A higher class task can hold the cpu, so also start the 1412 * ext server, which picks the ext class within its period. 1413 */ 1414 static void resched_sync_ecaps(struct rq *rq) 1415 { 1416 lockdep_assert_rq_held(rq); 1417 1418 update_rq_clock(rq); 1419 dl_server_start(&rq->ext_server); 1420 scx_resched_curr_deferred(rq); 1421 } 1422 1423 /* 1424 * A cpu came back and the root's ops.cpu_online() has run. Let the cpu deliver 1425 * ecaps again and reseed each sub-sched's ecaps on its cid. The sync recomputes 1426 * effective caps from the pshard and reports any change since the last 1427 * delivery. 1428 */ 1429 void scx_online_ecaps(struct rq *rq) 1430 { 1431 struct scx_sched *root, *pos; 1432 s32 cid; 1433 1434 guard(rq_lock_irqsave)(rq); 1435 1436 rq->scx.flags |= SCX_RQ_OPS_ONLINE; 1437 1438 /* 1439 * Only a live hierarchy can have ecaps to reseed. This also keeps the 1440 * table reads below away from an enable that failed before publishing 1441 * the tables. A concurrent disable can't retire them, see 1442 * handle_hotplug(). 1443 */ 1444 if (!scx_enabled()) 1445 return; 1446 1447 root = scx_root_protected(); 1448 cid = __scx_cpu_to_cid(cpu_of(rq)); 1449 1450 scx_for_each_descendant_pre(pos, root) { 1451 struct scx_pshard *ps; 1452 1453 /* root holds every cap and never uses ecaps */ 1454 if (!pos->level) 1455 continue; 1456 1457 ps = cid_pshard(pos, cid); 1458 guard(raw_spinlock)(&ps->lock); 1459 queue_sync_ecaps(pos, cid); 1460 } 1461 1462 resched_sync_ecaps(rq); 1463 } 1464 1465 /* 1466 * A cpu is going down, and the root's ops.cpu_offline() follows. Queue a marked 1467 * sync for each sub-sched to report the loss and wait until each has been 1468 * processed. Then stop the cpu's ecaps deliveries, so that none comes after 1469 * ops.cpu_offline(). 1470 * 1471 * This runs on the cpu's hotplug thread. While it sleeps, the cpu keeps 1472 * scheduling, and a pick through the ext class processes the syncs, see 1473 * resched_sync_ecaps(). Only the marked syncs count, so a flood of changes on 1474 * the cid can't hold up the hotplug. After the wait, every sub-sched's ecaps on 1475 * the cpu are zero, and the later syncs have nothing to deliver. 1476 * 1477 * The loss on a cpu that suspend or hibernation takes down is not delivered, so 1478 * that the scheds don't see a PM cycle as cpus leaving and coming back. The cpu 1479 * keeps the caps last delivered until it comes back, and the reseed then 1480 * reports the net change. 1481 */ 1482 void scx_offline_ecaps(struct rq *rq) 1483 { 1484 s32 cpu = cpu_of(rq); 1485 struct scx_sched *root, *pos; 1486 u32 nr = 0; 1487 s32 cid; 1488 1489 /* 1490 * ecaps and the tables need a live root, see scx_online_ecaps(). The 1491 * ext class isn't picked without one, so the syncs wouldn't be 1492 * processed and the wait would never end. scx_enabled() can't change 1493 * during hotplug. 1494 */ 1495 if (scx_enabled() && !scx_pm_frozen()) { 1496 scoped_guard (rq_lock_irqsave, rq) { 1497 root = scx_root_protected(); 1498 cid = __scx_cpu_to_cid(cpu); 1499 1500 scx_for_each_descendant_pre(pos, root) { 1501 struct scx_sched_pcpu *pcpu = per_cpu_ptr(pos->pcpu, cpu); 1502 struct scx_pshard *ps; 1503 1504 /* root holds every cap and never uses ecaps */ 1505 if (!pos->level) 1506 continue; 1507 1508 /* 1509 * A batch that has yet to reach the sync sees 1510 * the mark. A sync already being processed has 1511 * left the list and is queued again below. 1512 */ 1513 pcpu->flags |= SCX_SCHED_PCPU_ECAPS_OFFLINE; 1514 nr++; 1515 1516 ps = cid_pshard(pos, cid); 1517 guard(raw_spinlock)(&ps->lock); 1518 queue_sync_ecaps(pos, cid); 1519 } 1520 1521 WRITE_ONCE(rq->scx.nr_ecaps_offline, nr); 1522 resched_sync_ecaps(rq); 1523 } 1524 1525 wait_event(ecaps_offline_waitq, !READ_ONCE(rq->scx.nr_ecaps_offline)); 1526 } 1527 1528 guard(rq_lock_irqsave)(rq); 1529 rq->scx.flags &= ~SCX_RQ_OPS_ONLINE; 1530 } 1531 1532 /* 1533 * Clear every cap @sch holds in the pshards. The report that follows delivers 1534 * the loss and zeroes the ecaps. The caller holds off cpu hotplug across this 1535 * and the report. 1536 */ 1537 static void clear_all_caps(struct scx_sched *sch) 1538 { 1539 s32 si; 1540 u32 cap_bit; 1541 1542 lockdep_assert_cpus_held(); 1543 1544 /* enable may have failed before scx_alloc_pshards() */ 1545 if (!sch->pshard) 1546 return; 1547 1548 for (si = 0; si < sch->nr_pshards; si++) { 1549 struct scx_pshard *ps = sch->pshard[si]; 1550 1551 guard(raw_spinlock_irqsave)(&ps->lock); 1552 for (cap_bit = 0; cap_bit < __SCX_NR_CAPS; cap_bit++) 1553 scx_cmask_clear(&ps->caps[cap_bit].cmask); 1554 } 1555 } 1556 1557 /* 1558 * Remove @pcpu's ecaps sync node from @cpu's pending list. The first grace 1559 * period has passed, so nothing queues the node again. The second grace period 1560 * waits for a sync batch that took the node earlier, see 1561 * scx_sched_quiesce_rcu_work(). 1562 */ 1563 void scx_discard_ecaps_to_sync(s32 cpu, struct scx_sched_pcpu *pcpu) 1564 { 1565 struct rq *rq = cpu_rq(cpu); 1566 struct llist_node *head = NULL, *tail = NULL; 1567 struct llist_node *pos, *tmp; 1568 1569 guard(rq_lock_irqsave)(rq); 1570 1571 /* ecaps_report() waited for every mark it set */ 1572 WARN_ON_ONCE(pcpu->flags & SCX_SCHED_PCPU_ECAPS_REPORT); 1573 1574 if (!llist_on_list(&pcpu->ecaps_to_sync_node)) 1575 return; 1576 1577 /* 1578 * llist can't unlink a single node. Take all queued nodes, drop @pcpu's 1579 * and resplice the rest. Nodes in the taken batch read as on-list 1580 * throughout, so queue_sync_ecaps() stays correct. 1581 */ 1582 llist_for_each_safe(pos, tmp, llist_del_all(&rq->scx.ecaps_to_sync)) { 1583 if (pos == &pcpu->ecaps_to_sync_node) { 1584 init_llist_node(pos); 1585 /* a cpu going down may be waiting for the sync */ 1586 if (pcpu->flags & SCX_SCHED_PCPU_ECAPS_OFFLINE) 1587 ecaps_offline_done(rq, pcpu); 1588 } else { 1589 pos->next = head; 1590 head = pos; 1591 if (!tail) 1592 tail = pos; 1593 } 1594 } 1595 if (head) 1596 llist_add_batch(head, tail, &rq->scx.ecaps_to_sync); 1597 } 1598 1599 /** 1600 * scx_discard_stale_ecaps_syncs - Discard ecaps syncs from earlier schedulers 1601 * 1602 * To be called during root enable before the scheduler goes live. An earlier 1603 * root's sub-sched may not have gone through its RCU free path yet (e.g. a 1604 * still-open link fd defers it) and can leave queued ecaps syncs behind. 1605 * Processing them would decode the dead sched's pshards with the current cid 1606 * layout. Discard them instead. The backing scx_sched_pcpu's are still 1607 * allocated as the free path removes ecaps_to_sync_node before freeing. 1608 */ 1609 void scx_discard_stale_ecaps_syncs(void) 1610 { 1611 s32 cpu; 1612 1613 for_each_possible_cpu(cpu) { 1614 struct rq *rq = cpu_rq(cpu); 1615 struct llist_node *pos, *tmp; 1616 1617 guard(rq_lock_irqsave)(rq); 1618 llist_for_each_safe(pos, tmp, llist_del_all(&rq->scx.ecaps_to_sync)) 1619 init_llist_node(pos); 1620 } 1621 } 1622 1623 static DECLARE_WAIT_QUEUE_HEAD(scx_unlink_waitq); 1624 1625 void drain_descendants(struct scx_sched *sch) 1626 { 1627 /* 1628 * Child scheds that finished the critical part of disabling will take 1629 * themselves off @sch->children. Wait for it to drain. As propagation 1630 * is recursive, empty @sch->children means that all proper descendant 1631 * scheds reached unlinking stage. 1632 */ 1633 wait_event(scx_unlink_waitq, list_empty(&sch->children)); 1634 } 1635 1636 /** 1637 * scx_rehome_task - Move a task to a sched it has been initialized for 1638 * @to: sched taking over @p, @p's init on it already complete 1639 * @p: task to re-home 1640 * 1641 * Exit @p from its current sched and switch it over to @to, overriding the 1642 * state to %SCX_TASK_READY to account for the already completed init. A task 1643 * on a non-ext class, possible under an %SCX_OPS_SWITCH_PARTIAL root, stays 1644 * %READY and is enabled by switching_to_scx() if it switches over. 1645 */ 1646 static void scx_rehome_task(struct scx_sched *to, struct task_struct *p) 1647 { 1648 lockdep_assert_held(&p->pi_lock); 1649 lockdep_assert_rq_held(task_rq(p)); 1650 1651 scx_prepare_task_sched_change(p); 1652 scoped_guard (sched_change, p, 1653 DEQUEUE_SAVE | DEQUEUE_MOVE | DEQUEUE_NOCLOCK) { 1654 scx_disable_and_exit_task(scx_task_sched(p), p); 1655 scx_set_task_state(p, SCX_TASK_INIT_BEGIN); 1656 scx_set_task_state(p, SCX_TASK_INIT); 1657 scx_set_task_sched(p, to); 1658 scx_set_task_state(p, SCX_TASK_READY); 1659 if (p->sched_class == &ext_sched_class) 1660 scx_enable_task(to, p); 1661 } 1662 } 1663 1664 /** 1665 * scx_punt_task - Hand a task to a failed sched without initialization 1666 * @to: failed and bypassed sched taking custody of @p 1667 * @p: task to punt 1668 * 1669 * Take @p off its current sched and put it on @to at %SCX_TASK_NONE. @to is 1670 * dying and its teardown will re-home @p properly. 1671 * 1672 * Used when @to must take over @p but failed to initialize it. Bypass keeps 1673 * scheduling decisions away from @to but @p can still trigger its task ops, 1674 * which may confuse the BPF side. @to is dying anyway. The exit paths call no 1675 * op on a %NONE task. __scx_disable_and_exit_task() and switched_from_scx() 1676 * only reset its fields, see scx_reset_task_fields(). 1677 */ 1678 static void scx_punt_task(struct scx_sched *to, struct task_struct *p) 1679 { 1680 lockdep_assert_held(&p->pi_lock); 1681 lockdep_assert_rq_held(task_rq(p)); 1682 WARN_ON_ONCE(!READ_ONCE(to->bypass_depth)); 1683 1684 scx_prepare_task_sched_change(p); 1685 scoped_guard (sched_change, p, 1686 DEQUEUE_SAVE | DEQUEUE_MOVE | DEQUEUE_NOCLOCK) { 1687 scx_disable_and_exit_task(scx_task_sched(p), p); 1688 scx_set_task_sched(p, to); 1689 } 1690 } 1691 1692 static void scx_fail_parent(struct scx_sched *sch, 1693 struct task_struct *failed, s32 fail_code) 1694 { 1695 struct scx_sched *parent = scx_parent(sch); 1696 struct scx_task_iter sti; 1697 struct task_struct *p; 1698 1699 scx_error(parent, "ops.init_task() failed (%d) for %s[%d] while disabling a sub-scheduler", 1700 fail_code, failed->comm, failed->pid); 1701 1702 /* 1703 * Once $parent is bypassed, tasks can be punted into it. This may 1704 * cause downstream failures on the BPF side but $parent is dying 1705 * anyway. 1706 */ 1707 scx_bypass(parent, true); 1708 1709 scx_task_iter_start(&sti, sch->cgrp); 1710 while ((p = scx_task_iter_next_locked(&sti))) { 1711 if (scx_task_on_sched(parent, p)) 1712 continue; 1713 1714 scx_punt_task(parent, p); 1715 } 1716 scx_task_iter_stop(&sti); 1717 } 1718 1719 #ifdef CONFIG_EXT_GROUP_SCHED 1720 /** 1721 * scx_cgroup_claim_subtree - Claim the subtree's cgroups for an enabling sub 1722 * @sch: sub-scheduler being enabled 1723 * 1724 * Called while enabling @sch, after the subtree's cgrp->scx_sched's are pointed 1725 * at @sch and before any task is claimed. This mirrors root enable's 1726 * cgroups-before-tasks order. The ops.init_task() args are task_group-granular 1727 * and can still reference a cgroup outside the handed-over set when the cpu 1728 * controller is coarser than the sub topology or mounted on cgroup1. 1729 * 1730 * First init each of the parent sched's subtree cgroups on @sch, and only then 1731 * exit them from the parent, so that a failed init can be unwound with the 1732 * parent untouched. The both-inited transient is invisible outside 1733 * scx_cgroup_lock(). %SCX_TG_SUB_INIT tracks the first pass's progress. 1734 * %SCX_TG_INITED stays set throughout, except for a task_group whose 1735 * ops.cgroup_init() failed on the parent (see scx_cgroup_return_subtree()): 1736 * there is nothing to exit from the parent and %SCX_TG_INITED is set back with 1737 * the transfer. 1738 * 1739 * Dying but not yet offlined task_groups are included: a removed cgroup keeps 1740 * hosting scheduling events until its dying tasks finish their final context 1741 * switches, so it still needs to be inited on a sched, and its offline-time 1742 * ops.cgroup_exit() follows the last of those events. 1743 * 1744 * Return 0 on success, -errno on failure. On failure, @sch has been 1745 * scx_error()'d and is left with no cgroups. 1746 */ 1747 static s32 scx_cgroup_claim_subtree(struct scx_sched *sch) 1748 { 1749 struct cgroup *sub_cgrp = sch_cgroup(sch); 1750 struct cgroup_subsys_state *ecss = cgroup_e_css(sub_cgrp, &cpu_cgrp_subsys); 1751 struct scx_sched *parent = scx_parent(sch); 1752 struct cgroup_subsys_state *css; 1753 int ret; 1754 1755 css_for_each_descendant_pre(css, ecss) { 1756 struct task_group *tg = css_tg(css); 1757 struct scx_cgroup_init_args args = { 1758 .weight = tg->scx.weight, 1759 .bw_period_us = tg->scx.bw_period_us, 1760 .bw_quota_us = tg->scx.bw_quota_us, 1761 .bw_burst_us = tg->scx.bw_burst_us, 1762 .sched_idle = tg->scx.sched_idle, 1763 }; 1764 1765 if (tg->scx.sched != parent || 1766 !cgroup_is_descendant(css->cgroup, sub_cgrp)) 1767 continue; 1768 1769 if (SCX_HAS_OP(sch, cgroup_init)) { 1770 ret = SCX_CALL_OP_RET(sch, cgroup_init, NULL, css->cgroup, &args); 1771 if (ret) { 1772 scx_error(sch, "ops.cgroup_init() failed (%d)", ret); 1773 goto err; 1774 } 1775 } 1776 tg->scx.flags |= SCX_TG_SUB_INIT; 1777 } 1778 1779 css_for_each_descendant_post(css, ecss) { 1780 struct task_group *tg = css_tg(css); 1781 1782 /* 1783 * SUB_INIT is pass 1's progress mark: pass 2 and the err path 1784 * must visit exactly the tgs pass 1 inited. 1785 */ 1786 if (!(tg->scx.flags & SCX_TG_SUB_INIT)) 1787 continue; 1788 1789 /* skip the exit if the parent's ops.cgroup_init() failed */ 1790 if ((tg->scx.flags & SCX_TG_INITED) && SCX_HAS_OP(parent, cgroup_exit)) 1791 SCX_CALL_OP(parent, cgroup_exit, NULL, css->cgroup); 1792 tg->scx.sched = sch; 1793 tg->scx.flags |= SCX_TG_INITED; 1794 tg->scx.flags &= ~SCX_TG_SUB_INIT; 1795 } 1796 1797 return 0; 1798 1799 err: 1800 css_for_each_descendant_post(css, ecss) { 1801 struct task_group *tg = css_tg(css); 1802 1803 if (!(tg->scx.flags & SCX_TG_SUB_INIT)) 1804 continue; 1805 1806 if (SCX_HAS_OP(sch, cgroup_exit)) 1807 SCX_CALL_OP(sch, cgroup_exit, NULL, css->cgroup); 1808 tg->scx.flags &= ~SCX_TG_SUB_INIT; 1809 } 1810 return ret; 1811 } 1812 1813 /** 1814 * scx_cgroup_return_subtree - Return the subtree's cgroups to the parent sched 1815 * @sch: sub-scheduler being disabled 1816 * 1817 * Called while disabling @sch, after the subtree's cgrp->scx_sched's are reset 1818 * to the parent sched and before tasks are re-homed, mirroring root disable's 1819 * cgroups-before-tasks teardown order. The reverse of 1820 * scx_cgroup_claim_subtree(): exit @sch's cgroups from @sch, then init them on 1821 * the parent with the current tg->scx.* values, resyncing settings that changed 1822 * while @sch had them. 1823 * 1824 * When an init on the parent fails, the parent is failed - the same policy as 1825 * task re-homing. The remaining task_groups are punted: they move to the parent 1826 * anyway with %SCX_TG_INITED cleared, as ops.cgroup_init() failed or never ran 1827 * for them. A punted task_group gets no cgroup ops. The dying parent's own 1828 * disable moves it one sched up, initing it there. Root ends the chain: root 1829 * teardown drops cgroup ops entirely and the next enable's bulk init re-inits 1830 * every online task_group. 1831 * 1832 * The task re-home that follows still delivers ops.init_task() to the dying 1833 * parent, including for tasks in punted cgroups it never inited - tolerated 1834 * like the downstream failures of task punting (see scx_punt_task()). 1835 */ 1836 static void scx_cgroup_return_subtree(struct scx_sched *sch) 1837 { 1838 struct cgroup *sub_cgrp = sch_cgroup(sch); 1839 struct cgroup_subsys_state *ecss = cgroup_e_css(sub_cgrp, &cpu_cgrp_subsys); 1840 struct scx_sched *parent = scx_parent(sch); 1841 struct cgroup_subsys_state *css; 1842 bool parent_failed = false; 1843 int ret; 1844 1845 css_for_each_descendant_post(css, ecss) { 1846 struct task_group *tg = css_tg(css); 1847 1848 if (tg->scx.sched != sch || 1849 !cgroup_is_descendant(css->cgroup, sub_cgrp)) 1850 continue; 1851 1852 /* skip the exit if @sch's ops.cgroup_init() failed for the tg */ 1853 if ((tg->scx.flags & SCX_TG_INITED) && SCX_HAS_OP(sch, cgroup_exit)) 1854 SCX_CALL_OP(sch, cgroup_exit, NULL, css->cgroup); 1855 tg->scx.sched = parent; 1856 tg->scx.flags |= SCX_TG_SUB_INIT; 1857 } 1858 1859 css_for_each_descendant_pre(css, ecss) { 1860 struct task_group *tg = css_tg(css); 1861 struct scx_cgroup_init_args args = { 1862 .weight = tg->scx.weight, 1863 .bw_period_us = tg->scx.bw_period_us, 1864 .bw_quota_us = tg->scx.bw_quota_us, 1865 .bw_burst_us = tg->scx.bw_burst_us, 1866 .sched_idle = tg->scx.sched_idle, 1867 }; 1868 1869 /* the first pass must have transferred everything */ 1870 WARN_ON_ONCE(tg->scx.sched == sch); 1871 1872 /* 1873 * SUB_INIT distinguishes the tgs pass 1 moved. The sched test 1874 * can't: a tg punted to the parent by an earlier failure would 1875 * also match. 1876 */ 1877 if (!(tg->scx.flags & SCX_TG_SUB_INIT)) 1878 continue; 1879 tg->scx.flags &= ~(SCX_TG_SUB_INIT | SCX_TG_INITED); 1880 1881 /* 1882 * A re-init on $parent failed. The task_groups from here on are 1883 * punted: they stay on the dying $parent with INITED clear and 1884 * move onward when it disables. 1885 */ 1886 if (parent_failed) 1887 continue; 1888 1889 if (SCX_HAS_OP(parent, cgroup_init)) { 1890 ret = SCX_CALL_OP_RET(parent, cgroup_init, NULL, css->cgroup, &args); 1891 if (ret) { 1892 scx_error(parent, "ops.cgroup_init() failed (%d) while disabling a sub-scheduler", 1893 ret); 1894 parent_failed = true; 1895 continue; 1896 } 1897 } 1898 tg->scx.flags |= SCX_TG_INITED; 1899 } 1900 } 1901 #else 1902 static inline s32 scx_cgroup_claim_subtree(struct scx_sched *sch) { return 0; } 1903 static inline void scx_cgroup_return_subtree(struct scx_sched *sch) {} 1904 #endif 1905 1906 /* 1907 * Enable @sch's ecaps deliveries on every possible cpu, so that a cpu inactive 1908 * during the attach report delivers from the reseed at its activation. 1909 */ 1910 static void ecaps_enable(struct scx_sched *sch) 1911 { 1912 s32 cpu; 1913 1914 for_each_possible_cpu(cpu) { 1915 guard(rq_lock_irqsave)(cpu_rq(cpu)); 1916 per_cpu_ptr(sch->pcpu, cpu)->flags |= SCX_SCHED_PCPU_ECAPS_ENABLED; 1917 } 1918 sch->ecaps_enabled = true; 1919 } 1920 1921 /** 1922 * ecaps_report - Report @sch's ecaps and wait 1923 * @sch: sub-scheduler to report 1924 * 1925 * Mark every cpu @sch was ever granted a cap on, deliver its pending change 1926 * through the dispatch path and wait for it. An inactive cpu is skipped. It may 1927 * already be offline, where the mark would never be processed and the wait 1928 * would never end. On attach, the reseed at its activation reports its caps. On 1929 * detach, its loss was reported as it went down. A cpu that suspend or 1930 * hibernation took down is back by then, or the hierarchy is aborting, see 1931 * scx_sub_disable(). 1932 * 1933 * If a marked cpu goes down meanwhile, a regular down waits for the marked sync 1934 * in scx_offline_ecaps() while the cpu is still online, as 1935 * ecaps_report_irq_work would never run on an offline cpu. Suspend and 1936 * hibernation don't wait, but no report runs across their downs. The attach 1937 * report runs while the attaching task waits uninterruptibly, which holds off 1938 * the freezer, and the detach report holds cpus_read_lock(). 1939 * 1940 * Called with scx_enable_mutex held. A sched's attach and detach reports must 1941 * not overlap, as the mark is one bit per pcpu. 1942 */ 1943 static void ecaps_report(struct scx_sched *sch) 1944 { 1945 s32 cpu; 1946 1947 lockdep_assert_held(&scx_enable_mutex); 1948 1949 for_each_possible_cpu(cpu) { 1950 struct scx_sched_pcpu *pcpu = per_cpu_ptr(sch->pcpu, cpu); 1951 struct rq *rq = cpu_rq(cpu); 1952 struct scx_pshard *ps; 1953 s32 cid; 1954 1955 guard(rq_lock_irqsave)(rq); 1956 1957 if (!cpu_active(cpu)) 1958 continue; 1959 1960 cid = __scx_cpu_to_cid(cpu); 1961 ps = cid_pshard(sch, cid); 1962 guard(raw_spinlock)(&ps->lock); 1963 1964 if (!pcpu->had_caps) 1965 continue; 1966 1967 pcpu->flags |= SCX_SCHED_PCPU_ECAPS_REPORT; 1968 atomic_inc(&sch->nr_ecaps_reports); 1969 queue_sync_ecaps(sch, cid); 1970 resched_sync_ecaps(rq); 1971 } 1972 1973 rcuwait_wait_event(&ecaps_report_wait, !atomic_read(&sch->nr_ecaps_reports), 1974 TASK_UNINTERRUPTIBLE); 1975 } 1976 1977 void scx_sub_disable(struct scx_sched *sch) 1978 { 1979 struct scx_sched *parent = scx_parent(sch); 1980 struct scx_task_iter sti; 1981 struct task_struct *p; 1982 int ret; 1983 1984 /* 1985 * Guarantee forward progress and wait for descendants to be disabled. 1986 * To limit disruptions, $parent is not bypassed. Tasks are fully 1987 * prepped and then inserted back into $parent. 1988 */ 1989 scx_bypass(sch, true); 1990 drain_descendants(sch); 1991 1992 /* 1993 * Here, every runnable task is guaranteed to make forward progress and 1994 * we can safely use blocking synchronization constructs. Actually 1995 * disable ops. 1996 */ 1997 mutex_lock(&scx_enable_mutex); 1998 1999 /* 2000 * Clear @sch's caps and report the loss before any task goes back to 2001 * the parent. A disabling sched is granted nothing, so the caps stay 2002 * cleared. Hold off cpu hotplug across both so that a cpu the report 2003 * skips has finished going down. Its loss was reported as it went down, 2004 * see scx_offline_ecaps(). 2005 * 2006 * The loss on a cpu that suspend or hibernation took down is not 2007 * delivered. Wait for such cpus to come back so that the report reaches 2008 * them. They go down only after the freezer has frozen the tasks and 2009 * come back before the tasks thaw, so the wait doesn't hold up the 2010 * freezer. If one fails to come back, the wait can last until the PM 2011 * cycle ends, and scx_sub_pm_end() aborts every sched first. 2012 * 2013 * The check and the report run in one cpus_read_lock() section so that 2014 * no cpu goes down for PM between them. scx_sub_pm_end() can still 2015 * clear the set meanwhile, which is fine, as it aborts every sched 2016 * first. The report also needs scx_enable_mutex, see ecaps_report(). A 2017 * cpu coming back takes cpus_write_lock(), so the wait drops 2018 * cpus_read_lock(). It drops scx_enable_mutex too so that other enables 2019 * and disables don't wait behind the PM cycle, and retakes both in 2020 * order. 2021 * 2022 * An enable that failed before its attach report has nothing to report 2023 * and doesn't wait. If it failed before scx_link_sched(), the root's 2024 * disable doesn't wait for it and may have retired the cid tables that 2025 * the report reads. 2026 */ 2027 cpus_read_lock(); 2028 while (sch->ecaps_enabled && !data_race(cpumask_empty(&scx_frozen_cpus))) { 2029 cpus_read_unlock(); 2030 mutex_unlock(&scx_enable_mutex); 2031 /* lockless hint, the loop retests */ 2032 wait_event_idle(scx_frozen_cpus_waitq, 2033 data_race(cpumask_empty(&scx_frozen_cpus))); 2034 mutex_lock(&scx_enable_mutex); 2035 cpus_read_lock(); 2036 } 2037 clear_all_caps(sch); 2038 if (sch->ecaps_enabled) 2039 ecaps_report(sch); 2040 cpus_read_unlock(); 2041 2042 percpu_down_write(&scx_fork_rwsem); 2043 scx_cgroup_lock(); 2044 2045 /* 2046 * An enable that failed before scx_link_sched() succeeded never owned a 2047 * cgroup or task and won't be waited on by an ancestor's 2048 * drain_descendants(). Nothing to reparent and walking the tasks can 2049 * misbehave as the task ownership invariant (either owned by self or 2050 * parent) does not hold. ->sibling can't identify this case - an undone 2051 * link leaves it non-empty. 2052 */ 2053 if (!sch->linked) 2054 goto dump; 2055 2056 set_cgroup_sched(sch_cgroup(sch), parent); 2057 2058 /* 2059 * Return the subtree's cgroups before re-homing tasks so that any 2060 * ops.init_task() on $parent only sees cgroups it has initialized. 2061 */ 2062 scx_cgroup_return_subtree(sch); 2063 2064 scx_task_iter_start(&sti, sch->cgrp); 2065 while ((p = scx_task_iter_next_locked(&sti))) { 2066 struct rq *rq; 2067 struct rq_flags rf; 2068 2069 /* filter out duplicate visits */ 2070 if (scx_task_on_sched(parent, p)) 2071 continue; 2072 2073 /* 2074 * By the time control reaches here, all linked descendant 2075 * schedulers should have been disabled. 2076 */ 2077 WARN_ON_ONCE(!scx_task_on_sched(sch, p)); 2078 2079 /* 2080 * @p is pinned by the iter: css_task_iter_next() takes a 2081 * reference and holds it until the next iter_next() call, so 2082 * @p->usage is guaranteed > 0. 2083 */ 2084 get_task_struct(p); 2085 2086 scx_task_iter_unlock(&sti); 2087 2088 /* 2089 * $p is READY or ENABLED on @sch. Initialize for $parent, 2090 * disable and exit from @sch, and then switch over to $parent. 2091 * 2092 * If a task fails to initialize for $parent, the only available 2093 * action is disabling $parent too. While this allows disabling 2094 * of a child sched to cause the parent scheduler to fail, the 2095 * failure can only originate from ops.init_task() of the 2096 * parent. A child can't directly affect the parent through its 2097 * own failures. 2098 */ 2099 ret = __scx_init_task(parent, p, NULL, false); 2100 if (ret) { 2101 scx_fail_parent(sch, p, ret); 2102 put_task_struct(p); 2103 break; 2104 } 2105 2106 rq = task_rq_lock(p, &rf); 2107 2108 if (scx_get_task_state(p) == SCX_TASK_DEAD) { 2109 /* 2110 * sched_ext_dead() raced us between __scx_init_task() 2111 * and this rq lock and ran exit_task() on @sch (the 2112 * sched @p was on at that point), not on $parent. 2113 * $parent's just-completed init is owed an exit_task() 2114 * and we issue it here. 2115 */ 2116 scx_sub_init_cancel_task(parent, p); 2117 task_rq_unlock(rq, p, &rf); 2118 put_task_struct(p); 2119 continue; 2120 } 2121 2122 scx_rehome_task(parent, p); 2123 2124 task_rq_unlock(rq, p, &rf); 2125 put_task_struct(p); 2126 } 2127 scx_task_iter_stop(&sti); 2128 2129 dump: 2130 scx_disable_dump(sch); 2131 2132 scx_cgroup_unlock(); 2133 percpu_up_write(&scx_fork_rwsem); 2134 2135 scx_ops_cid_sched_updated_disable(sch); 2136 2137 /* 2138 * All tasks are moved off of @sch but there may still be on-going 2139 * operations (e.g. ops.select_cpu()). Drain them by flushing RCU. Use 2140 * the expedited version as ancestors may be waiting in bypass mode. 2141 * Also, tell the parent that there is no need to keep running bypass 2142 * DSQs for us. 2143 */ 2144 synchronize_rcu_expedited(); 2145 scx_disable_bypass_dsp(sch); 2146 2147 scx_unlink_sched(sch); 2148 2149 mutex_unlock(&scx_enable_mutex); 2150 2151 /* 2152 * @sch is now unlinked from the parent's children list. Notify and call 2153 * ops.sub_detach/exit(). Note that ops.sub_detach/exit() must be called 2154 * after unlinking and releasing all locks. See scx_claim_exit(). 2155 */ 2156 wake_up_all(&scx_unlink_waitq); 2157 2158 if (parent->ops.sub_detach && sch->sub_attached) { 2159 struct scx_sub_detach_args sub_detach_args = { 2160 .ops = &sch->ops, 2161 .cgroup_path = sch->cgrp_path, 2162 }; 2163 SCX_CALL_OP(parent, sub_detach, NULL, 2164 &sub_detach_args); 2165 } 2166 2167 scx_log_sched_disable(sch); 2168 2169 if (sch->ops.exit) 2170 SCX_CALL_OP(sch, exit, NULL, sch->exit_info); 2171 2172 /* 2173 * @sch's non-ops programs such as timers and tracers can fire after 2174 * ops.exit(). Now that exit is complete, stop scx_prog_sched() from 2175 * resolving to @sch and drain in-flight resolvers. 2176 */ 2177 WRITE_ONCE(sch->dead, true); 2178 synchronize_rcu(); 2179 2180 if (sch->sub_kset) 2181 kobject_del(&sch->sub_kset->kobj); 2182 /* not added if enable failed before scx_sched_sysfs_add() */ 2183 if (sch->kobj.state_in_sysfs) 2184 kobject_del(&sch->kobj); 2185 } 2186 2187 /* verify that a scheduler can be attached to @cgrp and return the parent */ 2188 static struct scx_sched *find_parent_sched(struct cgroup *cgrp) 2189 { 2190 struct scx_sched *parent = scx_cgroup_sched(cgrp); 2191 struct scx_sched *pos; 2192 2193 lockdep_assert_held(&scx_sched_lock); 2194 2195 /* can't attach twice to the same cgroup */ 2196 if (parent->cgrp == cgrp) 2197 return ERR_PTR(-EBUSY); 2198 2199 /* does $parent allow sub-scheds? */ 2200 if (!parent->ops.sub_attach) 2201 return ERR_PTR(-EOPNOTSUPP); 2202 2203 /* can't insert between $parent and its exiting children */ 2204 list_for_each_entry(pos, &parent->children, sibling) 2205 if (cgroup_is_descendant(pos->cgrp, cgrp)) 2206 return ERR_PTR(-EBUSY); 2207 2208 return parent; 2209 } 2210 2211 static bool assert_task_ready_or_enabled(struct task_struct *p) 2212 { 2213 u32 state = scx_get_task_state(p); 2214 2215 switch (state) { 2216 case SCX_TASK_READY: 2217 case SCX_TASK_ENABLED: 2218 return true; 2219 default: 2220 WARN_ONCE(true, "sched_ext: Invalid task state %d for %s[%d] during enabling sub sched", 2221 state, p->comm, p->pid); 2222 return false; 2223 } 2224 } 2225 2226 void scx_sub_enable_workfn(struct kthread_work *work) 2227 { 2228 struct scx_enable_cmd *cmd = container_of(work, struct scx_enable_cmd, work); 2229 struct sched_ext_ops *ops = cmd->ops; 2230 struct cgroup *cgrp; 2231 struct scx_sched *parent, *sch; 2232 struct scx_task_iter sti; 2233 struct task_struct *p; 2234 s32 i, ret; 2235 2236 mutex_lock(&scx_enable_mutex); 2237 2238 if (!scx_enabled()) { 2239 ret = -ENODEV; 2240 goto out_unlock; 2241 } 2242 2243 /* See scx_root_enable_workfn() for the @ops->priv check. */ 2244 if (rcu_access_pointer(ops->priv)) { 2245 ret = -EBUSY; 2246 goto out_unlock; 2247 } 2248 2249 /* nesting ops need private stacks, see bpf_scx_check_member() */ 2250 if (!bpf_jit_supports_private_stack()) { 2251 ret = -EOPNOTSUPP; 2252 goto out_unlock; 2253 } 2254 2255 cgrp = cgroup_get_from_id(ops->sub_cgroup_id); 2256 if (IS_ERR(cgrp)) { 2257 ret = PTR_ERR(cgrp); 2258 goto out_unlock; 2259 } 2260 2261 raw_spin_lock_irq(&scx_sched_lock); 2262 parent = find_parent_sched(cgrp); 2263 if (IS_ERR(parent)) { 2264 raw_spin_unlock_irq(&scx_sched_lock); 2265 ret = PTR_ERR(parent); 2266 goto out_put_cgrp; 2267 } 2268 kobject_get(&parent->kobj); 2269 raw_spin_unlock_irq(&scx_sched_lock); 2270 2271 /* 2272 * Flip the hot-path gates before ops->priv is published - the sub's 2273 * programs can e.g. kick cpus from that point on. The matching dec is 2274 * at the end of scx_sched_free_rcu_work(). 2275 */ 2276 static_branch_inc(&__scx_has_subs); 2277 2278 /* scx_alloc_and_add_sched() consumes @cgrp whether it succeeds or not */ 2279 sch = scx_alloc_and_add_sched(cmd, cgrp, parent); 2280 kobject_put(&parent->kobj); 2281 if (IS_ERR(sch)) { 2282 static_branch_dec(&__scx_has_subs); 2283 ret = PTR_ERR(sch); 2284 goto out_unlock; 2285 } 2286 2287 /* 2288 * Validate before scx_link_sched() publishes @sch, so an invalid sub 2289 * never becomes visible with an unallocated pshard. 2290 */ 2291 ret = scx_validate_ops(sch, ops); 2292 if (ret) 2293 goto err_disable; 2294 2295 scx_rescue_check_timeout(sch); 2296 2297 /* 2298 * Allocate pshard[] before scx_link_sched() publishes @sch into the 2299 * parent's RCU children list. A concurrent revoke walking the tree 2300 * would otherwise dereference sch->pshard[si] while it's still NULL. 2301 * Unlike the root path, the cid shard layout is stable at this point. 2302 * 2303 * scx_alloc_pshards() skips allocation when @sch's arena pool isn't 2304 * initialized, so scx_arena_pool_init() must run first. 2305 */ 2306 ret = scx_arena_pool_init(sch); 2307 if (ret) 2308 goto err_disable; 2309 2310 ret = scx_alloc_pshards(sch); 2311 if (ret) 2312 goto err_disable; 2313 2314 ret = scx_link_sched(sch); 2315 if (ret) 2316 goto err_disable; 2317 2318 ret = scx_sched_sysfs_add(sch); 2319 if (ret) 2320 goto err_disable; 2321 2322 if (sch->level >= SCX_SUB_MAX_DEPTH) { 2323 scx_error(sch, "max nesting depth %d violated", 2324 SCX_SUB_MAX_DEPTH); 2325 ret = -EINVAL; 2326 goto err_disable; 2327 } 2328 2329 scoped_guard(cpus_read_lock) { 2330 ret = scx_alloc_kern_arena_objs(sch); 2331 if (ret) 2332 goto err_disable; 2333 } 2334 2335 if (sch->ops.init) { 2336 ret = SCX_CALL_OP_RET(sch, init, NULL); 2337 if (ret) { 2338 ret = scx_ops_sanitize_err(sch, "init", ret); 2339 scx_error(sch, "ops.init() failed (%d)", ret); 2340 goto err_disable; 2341 } 2342 sch->exit_info->flags |= SCX_EFLAG_INITIALIZED; 2343 } 2344 2345 struct scx_sub_attach_args sub_attach_args = { 2346 .ops = &sch->ops, 2347 .cgroup_path = sch->cgrp_path, 2348 }; 2349 2350 /* 2351 * The cgroup stays online across ops.sub_attach(), so the parent never 2352 * sees an attach for a cgroup that rmdir already removed. 2353 */ 2354 cgroup_lock(); 2355 if (!(cgrp->self.flags & CSS_ONLINE)) { 2356 cgroup_unlock(); 2357 scx_error(sch, "cgroup is not online"); 2358 ret = -ENODEV; 2359 goto err_disable; 2360 } 2361 ret = SCX_CALL_OP_RET(parent, sub_attach, NULL, 2362 &sub_attach_args); 2363 cgroup_unlock(); 2364 2365 if (ret) { 2366 ret = scx_ops_sanitize_err(sch, "sub_attach", ret); 2367 scx_error(sch, "parent rejected (%d)", ret); 2368 goto err_disable; 2369 } 2370 sch->sub_attached = true; 2371 2372 scx_bypass(sch, true); 2373 2374 for (i = SCX_OPI_BEGIN; i < SCX_OPI_END; i++) 2375 if (((void (**)(void))ops)[i]) 2376 set_bit(i, sch->has_op); 2377 2378 scx_ops_cid_sched_updated_enable(sch); 2379 2380 percpu_down_write(&scx_fork_rwsem); 2381 scx_cgroup_lock(); 2382 2383 /* 2384 * Set cgroup->scx_sched's and check CSS_ONLINE. Either we see 2385 * !CSS_ONLINE or scx_cgroup_lifetime_notify() sees and shoots us down. 2386 */ 2387 set_cgroup_sched(sch_cgroup(sch), sch); 2388 if (!(cgrp->self.flags & CSS_ONLINE)) { 2389 scx_error(sch, "cgroup is not online"); 2390 ret = -ENODEV; 2391 goto err_unlock_and_disable; 2392 } 2393 2394 /* 2395 * Take over the subtree's cgroups before any task is claimed, 2396 * mirroring root enable's cgroups-before-tasks order. 2397 */ 2398 ret = scx_cgroup_claim_subtree(sch); 2399 if (ret) 2400 goto err_unlock_and_disable; 2401 2402 /* 2403 * Initialize tasks for the new child $sch without exiting them for 2404 * $parent so that the tasks can always be reverted back to $parent 2405 * sched on child init failure. 2406 */ 2407 WARN_ON_ONCE(scx_enabling_sub_sched); 2408 scx_enabling_sub_sched = sch; 2409 2410 scx_task_iter_start(&sti, sch->cgrp); 2411 while ((p = scx_task_iter_next_locked(&sti))) { 2412 struct rq *rq; 2413 struct rq_flags rf; 2414 2415 /* 2416 * Task iteration may visit the same task twice when racing 2417 * against exiting. Use %SCX_TASK_SUB_INIT to mark tasks which 2418 * finished __scx_init_task() and skip if set. 2419 * 2420 * A task may exit and get freed between __scx_init_task() 2421 * completion and scx_enable_task(). In such cases, 2422 * scx_disable_and_exit_task() must exit the task for both the 2423 * parent and child scheds. 2424 */ 2425 if (p->scx.flags & SCX_TASK_SUB_INIT) 2426 continue; 2427 2428 /* @p is pinned by the iter; see scx_sub_disable() */ 2429 get_task_struct(p); 2430 2431 if (!assert_task_ready_or_enabled(p)) { 2432 ret = -EINVAL; 2433 goto abort; 2434 } 2435 2436 scx_task_iter_unlock(&sti); 2437 2438 /* 2439 * As $p is still on $parent, it can't be transitioned to INIT. 2440 * Let's worry about task state later. Use __scx_init_task(). 2441 */ 2442 ret = __scx_init_task(sch, p, NULL, false); 2443 if (ret) 2444 goto abort; 2445 2446 rq = task_rq_lock(p, &rf); 2447 2448 if (scx_get_task_state(p) == SCX_TASK_DEAD) { 2449 /* 2450 * sched_ext_dead() raced us between __scx_init_task() 2451 * and this rq lock and ran exit_task() on $parent (the 2452 * sched @p was on at that point), not on @sch. @sch's 2453 * just-completed init is owed an exit_task() and we 2454 * issue it here. 2455 */ 2456 scx_sub_init_cancel_task(sch, p); 2457 task_rq_unlock(rq, p, &rf); 2458 put_task_struct(p); 2459 continue; 2460 } 2461 2462 p->scx.flags |= SCX_TASK_SUB_INIT; 2463 task_rq_unlock(rq, p, &rf); 2464 2465 put_task_struct(p); 2466 } 2467 scx_task_iter_stop(&sti); 2468 2469 /* 2470 * All tasks are prepped. Disable/exit tasks for $parent and enable for 2471 * the new @sch. 2472 */ 2473 scx_task_iter_start(&sti, sch->cgrp); 2474 while ((p = scx_task_iter_next_locked(&sti))) { 2475 /* 2476 * Use clearing of %SCX_TASK_SUB_INIT to detect and skip 2477 * duplicate iterations. 2478 */ 2479 if (!(p->scx.flags & SCX_TASK_SUB_INIT)) 2480 continue; 2481 2482 scx_prepare_task_sched_change(p); 2483 scoped_guard (sched_change, p, 2484 DEQUEUE_SAVE | DEQUEUE_MOVE | DEQUEUE_NOCLOCK) { 2485 /* 2486 * $p must be either READY or ENABLED. If ENABLED, 2487 * __scx_disabled_and_exit_task() first disables and 2488 * makes it READY. However, after exiting $p, it will 2489 * leave $p as READY. 2490 */ 2491 assert_task_ready_or_enabled(p); 2492 __scx_disable_and_exit_task(parent, p); 2493 2494 /* 2495 * $p is now only initialized for @sch and READY, which 2496 * is what we want. Assign it to @sch and, if it's on 2497 * the ext class, enable. A non-ext task, possible under 2498 * an %SCX_OPS_SWITCH_PARTIAL root, stays READY and is 2499 * enabled by switching_to_scx() if it switches over. 2500 */ 2501 scx_set_task_sched(p, sch); 2502 if (p->sched_class == &ext_sched_class) 2503 scx_enable_task(sch, p); 2504 2505 p->scx.flags &= ~SCX_TASK_SUB_INIT; 2506 } 2507 } 2508 scx_task_iter_stop(&sti); 2509 2510 scx_enabling_sub_sched = NULL; 2511 2512 scx_cgroup_unlock(); 2513 percpu_up_write(&scx_fork_rwsem); 2514 2515 /* 2516 * Report the caps granted from ops.sub_attach() before bypass lifts and 2517 * @sch makes its first scheduling decision. The report sleeps until its 2518 * syncs are processed, so it runs outside the fork rwsem. 2519 */ 2520 scx_sub_seed_caps(sch); 2521 ecaps_enable(sch); 2522 ecaps_report(sch); 2523 2524 scx_bypass(sch, false); 2525 2526 pr_info("sched_ext: BPF sub-scheduler \"%s\" enabled\n", sch->ops.name); 2527 kobject_uevent(&sch->kobj, KOBJ_ADD); 2528 ret = 0; 2529 goto out_unlock; 2530 2531 out_put_cgrp: 2532 cgroup_put(cgrp); 2533 out_unlock: 2534 mutex_unlock(&scx_enable_mutex); 2535 cmd->ret = ret; 2536 return; 2537 2538 abort: 2539 put_task_struct(p); 2540 scx_task_iter_stop(&sti); 2541 2542 /* 2543 * Undo __scx_init_task() for tasks we marked. scx_enable_task() never 2544 * ran for @sch on them, so calling scx_disable_task() here would invoke 2545 * ops.disable() without a matching ops.enable(). scx_enabling_sub_sched 2546 * must stay set until SUB_INIT is cleared from every marked task - 2547 * scx_disable_and_exit_task() reads it when a task exits concurrently. 2548 */ 2549 scx_task_iter_start(&sti, sch->cgrp); 2550 while ((p = scx_task_iter_next_locked(&sti))) { 2551 if (p->scx.flags & SCX_TASK_SUB_INIT) { 2552 scx_sub_init_cancel_task(sch, p); 2553 p->scx.flags &= ~SCX_TASK_SUB_INIT; 2554 } 2555 } 2556 scx_task_iter_stop(&sti); 2557 scx_enabling_sub_sched = NULL; 2558 err_unlock_and_disable: 2559 /* we'll soon enter disable path, keep bypass on */ 2560 scx_cgroup_unlock(); 2561 percpu_up_write(&scx_fork_rwsem); 2562 err_disable: 2563 mutex_unlock(&scx_enable_mutex); 2564 /* 2565 * Some enable failures only return an errno (e.g. -ENOMEM from an 2566 * allocation) without calling scx_error(). Record it so 2567 * scx_flush_disable_work() runs the disable and ops.exit() fires. 2568 */ 2569 scx_error(sch, "scx_sub_enable() failed (%d)", ret); 2570 scx_flush_disable_work(sch); 2571 cmd->ret = 0; 2572 } 2573 2574 /** 2575 * scx_cgroup_task_migrating - Prepare a task for a cgroup migration 2576 * @ctx: migration being prepared 2577 * 2578 * A task's sched must match its cgroup's owner, so a migration that crosses a 2579 * sched boundary re-homes the task once committed. Run the fallible part here, 2580 * before the migration commits: initialize the task for the destination sched. 2581 * A rejection fails the cgroup.procs write. 2582 */ 2583 static s32 scx_cgroup_task_migrating(struct cgroup_task_migrate_ctx *ctx) 2584 { 2585 struct task_struct *p = ctx->task; 2586 struct scx_sched *to; 2587 int ret; 2588 2589 /* 2590 * Cleared under scx_cgroup_lock() before root disable starts tearing 2591 * down tasks. As cgroup_mutex is held, a set flag guarantees that the 2592 * teardown loop is not running concurrently. 2593 */ 2594 if (!scx_cgroup_enabled) 2595 return NOTIFY_OK; 2596 2597 to = scx_cgroup_sched(ctx->dst_dcgrp); 2598 if (scx_task_on_sched(to, p)) 2599 return NOTIFY_OK; 2600 2601 ret = __scx_init_task(to, p, ctx->dst_dcgrp, false); 2602 if (ret) 2603 return notifier_from_errno(ret); 2604 2605 return NOTIFY_OK; 2606 } 2607 2608 /** 2609 * scx_cgroup_task_migrated - Re-home a task that changed cgroups 2610 * @ctx: committed migration 2611 * 2612 * Move the task to its new cgroup's sched, which scx_cgroup_task_migrating() 2613 * already initialized it for. Can't fail. 2614 * 2615 * This is safe against all phases of the destination sched's destruction. A 2616 * disable resets cgroup ownership to the parent and re-homes tasks in one 2617 * scx_cgroup_lock() section. If that section already ran, the destination would 2618 * be the parent. Otherwise, the re-home loop is still ahead and guaranteed to 2619 * visit the task, now in the destination cgroup. 2620 */ 2621 static void scx_cgroup_task_migrated(struct cgroup_task_migrate_ctx *ctx) 2622 { 2623 struct task_struct *p = ctx->task; 2624 struct scx_sched *to; 2625 struct rq *rq; 2626 struct rq_flags rf; 2627 2628 if (!scx_cgroup_enabled) 2629 return; 2630 2631 to = scx_cgroup_sched(ctx->dst_dcgrp); 2632 if (scx_task_on_sched(to, p)) 2633 return; 2634 2635 rq = task_rq_lock(p, &rf); 2636 scx_rehome_task(to, p); 2637 task_rq_unlock(rq, p, &rf); 2638 } 2639 2640 /** 2641 * scx_cgroup_task_migrate_canceled - Undo migration preparation 2642 * @ctx: canceled migration 2643 * 2644 * The migration failed after scx_cgroup_task_migrating() initialized the task 2645 * for the destination sched. The task stays on its current sched in the source 2646 * cgroup. Undo the destination's init. 2647 */ 2648 static void scx_cgroup_task_migrate_canceled(struct cgroup_task_migrate_ctx *ctx) 2649 { 2650 struct task_struct *p = ctx->task; 2651 struct scx_sched *to; 2652 struct rq *rq; 2653 struct rq_flags rf; 2654 2655 if (!scx_cgroup_enabled) 2656 return; 2657 2658 to = scx_cgroup_sched(ctx->dst_dcgrp); 2659 if (scx_task_on_sched(to, p)) 2660 return; 2661 2662 rq = task_rq_lock(p, &rf); 2663 scx_sub_init_cancel_task(to, p); 2664 task_rq_unlock(rq, p, &rf); 2665 } 2666 2667 static s32 scx_cgroup_lifetime_notify(struct notifier_block *nb, 2668 unsigned long action, void *data) 2669 { 2670 struct cgroup *cgrp = data; 2671 struct cgroup *parent = cgroup_parent(cgrp); 2672 struct scx_sched *sch; 2673 2674 if (!cgroup_on_dfl(cgrp)) 2675 return NOTIFY_OK; 2676 2677 switch (action) { 2678 case CGROUP_LIFETIME_ONLINE: 2679 /* inherit ->scx_sched from $parent */ 2680 if (parent) 2681 rcu_assign_pointer(cgrp->scx_sched, scx_cgroup_sched(parent)); 2682 break; 2683 case CGROUP_LIFETIME_OFFLINE: 2684 /* if there is a sched attached, shoot it down */ 2685 sch = scx_cgroup_sched(cgrp); 2686 if (sch && sch->cgrp == cgrp) 2687 scx_exit(sch, SCX_EXIT_UNREG_KERN, 2688 SCX_ECODE_RSN_CGROUP_OFFLINE, 2689 "cgroup %llu going offline", cgroup_id(cgrp)); 2690 break; 2691 } 2692 2693 return NOTIFY_OK; 2694 } 2695 2696 static struct notifier_block scx_cgroup_lifetime_nb = { 2697 .notifier_call = scx_cgroup_lifetime_notify, 2698 }; 2699 2700 static s32 scx_cgroup_task_notify(struct notifier_block *nb, 2701 unsigned long action, void *data) 2702 { 2703 struct cgroup_task_migrate_ctx *ctx = data; 2704 2705 switch (action) { 2706 case CGROUP_TASK_MIGRATING: 2707 return scx_cgroup_task_migrating(ctx); 2708 case CGROUP_TASK_MIGRATED: 2709 scx_cgroup_task_migrated(ctx); 2710 break; 2711 case CGROUP_TASK_MIGRATE_CANCELED: 2712 scx_cgroup_task_migrate_canceled(ctx); 2713 break; 2714 } 2715 2716 return NOTIFY_OK; 2717 } 2718 2719 static struct notifier_block scx_cgroup_task_nb = { 2720 .notifier_call = scx_cgroup_task_notify, 2721 }; 2722 2723 static s32 __init scx_cgroup_notifier_init(void) 2724 { 2725 s32 ret; 2726 2727 ret = blocking_notifier_chain_register(&cgroup_lifetime_notifier, 2728 &scx_cgroup_lifetime_nb); 2729 if (ret) 2730 return ret; 2731 2732 return blocking_notifier_chain_register(&cgroup_task_notifier, 2733 &scx_cgroup_task_nb); 2734 } 2735 core_initcall(scx_cgroup_notifier_init); 2736 2737 static void scx_pstack_recursion(struct bpf_prog *prog, const char *op) 2738 { 2739 struct scx_sched *sch; 2740 2741 guard(rcu)(); 2742 sch = scx_prog_sched(prog->aux); 2743 if (unlikely(!sch)) 2744 return; 2745 2746 scx_error(sch, "%s recursion detected", op); 2747 } 2748 2749 void scx_pstack_recursion_on_dispatch(struct bpf_prog *prog) 2750 { 2751 scx_pstack_recursion(prog, "dispatch"); 2752 } 2753 2754 void scx_pstack_recursion_on_caps_updated(struct bpf_prog *prog) 2755 { 2756 scx_pstack_recursion(prog, "sub_caps_updated"); 2757 } 2758 2759 __bpf_kfunc_start_defs(); 2760 2761 /** 2762 * scx_bpf_sub_dispatch - Trigger dispatching on a child scheduler 2763 * @cgroup_id: cgroup ID of the child scheduler to dispatch 2764 * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs 2765 * 2766 * Allows a parent scheduler to trigger dispatching on one of its direct 2767 * child schedulers. The child scheduler runs its dispatch operation to 2768 * move tasks from dispatch queues to the local runqueue. 2769 * 2770 * Dispatch into a child while the local DSQ is empty, when the cpu needs a 2771 * task. A child holding only %SCX_CAP_ENQ_IMMED can insert only IMMED tasks, 2772 * and the consume of its bypassing descendants' bypass DSQs is one such insert. 2773 * With a task already queued on the local DSQ, such an insert fails and the 2774 * task is reenqueued. 2775 * 2776 * Returns: true on success, false if cgroup_id is invalid, not a direct 2777 * child, or caller lacks dispatch permission. 2778 */ 2779 __bpf_kfunc bool scx_bpf_sub_dispatch(u64 cgroup_id, const struct bpf_prog_aux *aux) 2780 { 2781 struct rq *rq = scx_locked_rq(); 2782 struct scx_sched *parent, *child; 2783 2784 guard(rcu)(); 2785 parent = scx_prog_sched(aux); 2786 if (unlikely(!parent)) 2787 return false; 2788 2789 child = scx_find_sub_sched(cgroup_id); 2790 2791 if (unlikely(!child)) 2792 return false; 2793 2794 if (unlikely(scx_parent(child) != parent)) { 2795 scx_error(parent, "trying to dispatch a distant sub-sched on cgroup %llu", 2796 cgroup_id); 2797 return false; 2798 } 2799 2800 /* 2801 * Skip a child that does not effectively hold the base cap on this cpu: 2802 * its inserts would only be rejected. ecaps are synced at the top of 2803 * dispatch_one() before dispatch, so this reflects the in-effect state. 2804 */ 2805 if (scx_missing_caps(child, cpu_of(rq), SCX_CAP_BASE)) 2806 return false; 2807 2808 return scx_dispatch_sched(child, rq, rq->scx.sub_dispatch_prev, true) != 2809 SCX_DSP_NONE; 2810 } 2811 2812 /* Validate common inputs. On success, *parent_out and *child_out are set. */ 2813 static s32 sub_cap_preamble(u64 cgroup_id, u64 caps, const struct bpf_prog_aux *aux, 2814 struct scx_sched **parent_out, struct scx_sched **child_out) 2815 { 2816 struct scx_sched *parent, *child; 2817 2818 parent = scx_prog_sched(aux); 2819 if (unlikely(!parent)) 2820 return -ENODEV; 2821 2822 if (!scx_kf_allowed_ctx(parent)) 2823 return -EDEADLK; 2824 2825 if (!scx_is_cid_type()) { 2826 scx_error(parent, "sub-cap kfuncs require a cid-form scheduler"); 2827 return -EOPNOTSUPP; 2828 } 2829 2830 child = scx_find_sub_sched(cgroup_id); 2831 if (unlikely(!child)) 2832 return -ENODEV; 2833 2834 if (unlikely(scx_parent(child) != parent)) { 2835 scx_error(parent, "%s: sub-%llu is not a direct child", 2836 parent->cgrp_path, cgroup_id); 2837 return -EINVAL; 2838 } 2839 2840 if (unlikely(caps & ~__SCX_CAP_ALL)) { 2841 scx_error(parent, "invalid caps 0x%llx", caps); 2842 return -EINVAL; 2843 } 2844 2845 *parent_out = parent; 2846 *child_out = child; 2847 return 0; 2848 } 2849 2850 /** 2851 * scx_bpf_sub_grant - Grant @caps on a cmask's cids to a direct child 2852 * @cgroup_id: cgroup id of the direct child sub-sched 2853 * @caps: bitmask of SCX_CAP_* to grant 2854 * @cmask__arena: cid cmask to grant @caps on 2855 * @denied_out__arena__nullable: optional cmask accumulating refused cids 2856 * @aux: implicit BPF argument 2857 * 2858 * A cid in @cmask__arena is granted to the child only if the parent holds every 2859 * requested cap on it. Refused cids are OR'd into the denied mask when 2860 * provided. Refusals outside the denied mask's range are not recorded. 2861 * 2862 * All-or-nothing keeps the caller-visible result binary per cid, so the denied 2863 * mask is one mask to interpret rather than a per-cap matrix. 2864 * 2865 * Return 0 on full success, -EPERM if any cid was refused, -ENODEV if the child 2866 * is gone or being disabled, or a negative errno on other failures. 2867 */ 2868 __bpf_kfunc s32 scx_bpf_sub_grant(u64 cgroup_id, u64 caps, 2869 const struct scx_cmask *cmask__arena, 2870 struct scx_cmask *denied_out__arena__nullable, 2871 const struct bpf_prog_aux *aux) 2872 { 2873 struct scx_cmask_ref ref, denied_ref; 2874 struct scx_sched *parent, *child; 2875 bool any_denied = false; 2876 LIST_HEAD(to_deliver); 2877 s32 si, ret; 2878 2879 guard(irqsave)(); 2880 2881 ret = sub_cap_preamble(cgroup_id, caps, aux, &parent, &child); 2882 if (ret) 2883 return ret; 2884 2885 ret = scx_cmask_ref_init(parent, cmask__arena, &ref); 2886 if (ret) { 2887 scx_error(parent, "invalid cmask (%d)", ret); 2888 return ret; 2889 } 2890 2891 if (denied_out__arena__nullable) { 2892 ret = scx_cmask_ref_init(parent, denied_out__arena__nullable, &denied_ref); 2893 if (ret) { 2894 scx_error(parent, "invalid denied_out (%d)", ret); 2895 return ret; 2896 } 2897 } 2898 2899 /* apply the grant one shard at a time */ 2900 for (si = ref.shard_first; si < ref.shard_end; si++) { 2901 SCX_CMASK_DEFINE_SHARD(slice, 0, SCX_CID_SHARD_MAX_CPUS); 2902 struct scx_pshard *pps = parent->pshard[si]; 2903 struct scx_pshard *cps = child->pshard[si]; 2904 u64 granted_caps = 0; 2905 u32 cap_bit; 2906 2907 scx_cmask_ref_shard(&ref, si, slice); 2908 if (scx_cmask_empty(slice)) 2909 continue; 2910 2911 SCX_CMASK_DEFINE_SHARD(granted_cids, slice->base, slice->nr_cids); 2912 SCX_CMASK_DEFINE_SHARD(changed_cids, slice->base, slice->nr_cids); 2913 SCX_CMASK_DEFINE_SHARD(delta, slice->base, slice->nr_cids); 2914 2915 scx_cmask_copy(granted_cids, slice); 2916 2917 scoped_guard (raw_spinlock, &pps->lock) { 2918 guard(raw_spinlock_nested)(&cps->lock); 2919 2920 /* the child is being disabled, see clear_all_caps() */ 2921 if (unlikely(READ_ONCE(child->aborting))) { 2922 ret = -ENODEV; 2923 goto out; 2924 } 2925 2926 /* 2927 * Narrow granted_cids to cids the parent holds every 2928 * requested cap on. All-or-nothing per cid. 2929 */ 2930 scx_for_each_cap_bit(cap_bit, caps) 2931 scx_cmask_and(granted_cids, &pps->caps[cap_bit].cmask); 2932 2933 /* 2934 * For each requested cap, fold the newly-set cids into 2935 * the child and accumulate the delta. 2936 */ 2937 scx_for_each_cap_bit(cap_bit, caps) { 2938 struct scx_cmask *ccm = &cps->caps[cap_bit].cmask; 2939 2940 scx_cmask_copy(delta, granted_cids); 2941 scx_cmask_andnot(delta, ccm); 2942 if (scx_cmask_empty(delta)) 2943 continue; 2944 2945 scx_cmask_or(ccm, delta); 2946 scx_cmask_or(changed_cids, delta); 2947 granted_caps |= BIT_U64(cap_bit); 2948 } 2949 2950 if (granted_caps) { 2951 s32 cid; 2952 2953 caps_updated_record(cps, changed_cids, granted_caps, 2954 &to_deliver); 2955 /* 2956 * The sync arms an update_idle() re-notify if 2957 * the cid gains baseline access, so the holder 2958 * learns of an already-idle cid. 2959 */ 2960 scx_cmask_for_each_cid(cid, changed_cids) { 2961 s32 cpu = __scx_cid_to_cpu(cid); 2962 2963 per_cpu_ptr(child->pcpu, cpu)->had_caps = true; 2964 queue_sync_ecaps(child, cid); 2965 } 2966 } 2967 } 2968 2969 /* record cids that didn't make it into the denied mask */ 2970 if (!scx_cmask_subset(slice, granted_cids)) { 2971 any_denied = true; 2972 if (denied_out__arena__nullable) { 2973 SCX_CMASK_DEFINE_SHARD(denied, slice->base, slice->nr_cids); 2974 2975 scx_cmask_copy(denied, slice); 2976 scx_cmask_andnot(denied, granted_cids); 2977 scx_cmask_ref_or(&denied_ref, denied); 2978 } 2979 } 2980 } 2981 2982 ret = any_denied ? -EPERM : 0; 2983 out: 2984 caps_updated_deliver(&to_deliver); 2985 return ret; 2986 } 2987 2988 /** 2989 * scx_bpf_sub_revoke - Revoke @caps on a cmask's cids from a direct child 2990 * @cgroup_id: cgroup id of the direct child sub-sched 2991 * @caps: bitmask of SCX_CAP_* to revoke 2992 * @cmask__arena: cid cmask to revoke @caps on 2993 * @aux: implicit BPF argument 2994 * 2995 * Clear @caps bits on @cmask__arena from the child named by @cgroup_id and all 2996 * its descendants. The origin parent's pshard lock is held across the subtree 2997 * walk so a concurrent grant from the origin parent observes the revoked state. 2998 */ 2999 __bpf_kfunc void scx_bpf_sub_revoke(u64 cgroup_id, u64 caps, 3000 const struct scx_cmask *cmask__arena, 3001 const struct bpf_prog_aux *aux) 3002 { 3003 struct scx_cmask_ref ref; 3004 struct scx_sched *parent, *child, *pos; 3005 LIST_HEAD(to_deliver); 3006 s32 si, ret; 3007 3008 guard(irqsave)(); 3009 3010 if (sub_cap_preamble(cgroup_id, caps, aux, &parent, &child)) 3011 return; 3012 3013 ret = scx_cmask_ref_init(parent, cmask__arena, &ref); 3014 if (ret) { 3015 scx_error(parent, "invalid cmask (%d)", ret); 3016 return; 3017 } 3018 3019 /* per-shard, walk child's subtree and clear @caps */ 3020 for (si = ref.shard_first; si < ref.shard_end; si++) { 3021 SCX_CMASK_DEFINE_SHARD(slice, 0, SCX_CID_SHARD_MAX_CPUS); 3022 3023 scx_cmask_ref_shard(&ref, si, slice); 3024 if (scx_cmask_empty(slice)) 3025 continue; 3026 3027 /* 3028 * Pre-order with subtree skip: a descendant that cleared 3029 * nothing means no descendant of it can hold @caps on these 3030 * cids either. 3031 */ 3032 guard(raw_spinlock)(&parent->pshard[si]->lock); 3033 pos = scx_next_descendant_pre(NULL, child); 3034 while (pos) { 3035 struct scx_pshard *ps = pos->pshard[si]; 3036 SCX_CMASK_DEFINE_SHARD(changed_cids, slice->base, slice->nr_cids); 3037 SCX_CMASK_DEFINE_SHARD(delta, slice->base, slice->nr_cids); 3038 u64 revoked_caps = 0; 3039 u32 cap_bit; 3040 3041 scoped_guard (raw_spinlock_nested, &ps->lock) { 3042 /* 3043 * For each cap, clear lost cids and accumulate 3044 * the per-cap diff for notification. 3045 */ 3046 scx_for_each_cap_bit(cap_bit, caps) { 3047 struct scx_cmask *cm = &ps->caps[cap_bit].cmask; 3048 3049 scx_cmask_copy(delta, cm); 3050 scx_cmask_and(delta, slice); 3051 if (scx_cmask_empty(delta)) 3052 continue; 3053 3054 scx_cmask_andnot(cm, delta); 3055 scx_cmask_or(changed_cids, delta); 3056 revoked_caps |= BIT_U64(cap_bit); 3057 } 3058 3059 if (revoked_caps) { 3060 s32 cid; 3061 3062 caps_updated_record(ps, changed_cids, revoked_caps, 3063 &to_deliver); 3064 scx_cmask_for_each_cid(cid, changed_cids) 3065 queue_sync_ecaps(pos, cid); 3066 } 3067 } 3068 3069 if (revoked_caps) 3070 pos = scx_next_descendant_pre(pos, child); 3071 else 3072 pos = scx_skip_subtree_pre(pos, child); 3073 } 3074 } 3075 3076 caps_updated_deliver(&to_deliver); 3077 } 3078 3079 /** 3080 * scx_bpf_sub_caps - Read self's or a direct child's cap cmasks 3081 * @cgroup_id: 0 for self, or a direct child's cgroup id 3082 * @caps: one or more SCX_CAP_* bits 3083 * @out__arena: cmask to receive the union of @caps within its range 3084 * @aux: implicit BPF argument 3085 * 3086 * Read the cap cmasks granted on each cid for self (@cgroup_id 0) or a direct 3087 * child - the literal granted set. A sched can read only itself or a direct 3088 * child. 3089 * 3090 * Return 0, -ENODEV if @cgroup_id names no direct child, or -EINVAL on bad 3091 * inputs. 3092 */ 3093 __bpf_kfunc s32 scx_bpf_sub_caps(u64 cgroup_id, u64 caps, struct scx_cmask *out__arena, 3094 const struct bpf_prog_aux *aux) 3095 { 3096 struct scx_cmask_ref ref; 3097 struct scx_sched *sch, *target; 3098 struct scx_pshard **pshard; 3099 s32 si, ret; 3100 3101 guard(irqsave)(); 3102 3103 sch = scx_prog_sched(aux); 3104 if (unlikely(!sch)) 3105 return -ENODEV; 3106 3107 if (!scx_is_cid_type()) { 3108 scx_error(sch, "sub-cap kfuncs require a cid-form scheduler"); 3109 return -EOPNOTSUPP; 3110 } 3111 3112 if (unlikely(caps & ~__SCX_CAP_ALL)) { 3113 scx_error(sch, "invalid caps 0x%llx", caps); 3114 return -EINVAL; 3115 } 3116 3117 /* @cgroup_id 0 reads self, otherwise a direct child */ 3118 if (cgroup_id) { 3119 target = scx_find_sub_sched(cgroup_id); 3120 if (unlikely(!target)) 3121 return -ENODEV; 3122 if (unlikely(scx_parent(target) != sch)) { 3123 scx_error(sch, "%s: sub-%llu is not a direct child", 3124 sch->cgrp_path, cgroup_id); 3125 return -EINVAL; 3126 } 3127 } else { 3128 target = sch; 3129 } 3130 3131 /* 3132 * The target's caps storage may not be set up yet (e.g. a self-read 3133 * during ops.init_cids()). Pairs with the publish in 3134 * scx_alloc_pshards(): a non-NULL pshard has every element set and the 3135 * acquire also orders the cid table reads below against it. 3136 */ 3137 pshard = smp_load_acquire(&target->pshard); 3138 if (unlikely(!pshard)) { 3139 scx_error(sch, "scx_bpf_sub_caps() called before caps storage is initialized"); 3140 return -ENODEV; 3141 } 3142 3143 ret = scx_cmask_ref_init(sch, out__arena, &ref); 3144 if (ret) { 3145 scx_error(sch, "invalid out (%d)", ret); 3146 return ret; 3147 } 3148 3149 for (si = ref.shard_first; si < ref.shard_end; si++) { 3150 const struct scx_cid_shard *shard = 3151 &rcu_dereference_all(scx_cid_shard_ranges)[si]; 3152 SCX_CMASK_DEFINE_SHARD(local_out, shard->base_cid, shard->nr_cids); 3153 u32 cap_bit; 3154 3155 scx_for_each_cap_bit(cap_bit, caps) 3156 scx_cmask_or(local_out, &pshard[si]->caps[cap_bit].cmask); 3157 scx_cmask_ref_copy(&ref, local_out); 3158 } 3159 return 0; 3160 } 3161 3162 /** 3163 * scx_bpf_sub_kill_bstr - Kill a direct child sub-scheduler 3164 * @cgroup_id: cgroup id of the direct child to kill 3165 * @fmt: reason message format string 3166 * @data: format string parameters packaged using ___bpf_fill() macro 3167 * @data__sz: @data len, must end in '__sz' for the verifier 3168 * @aux: implicit BPF argument to access bpf_prog_aux hidden from BPF progs 3169 * 3170 * Evict a direct child sub-scheduler, disabling it with the supplied reason. 3171 * The child and its subtree are torn down asynchronously through the usual 3172 * disable path. 3173 * 3174 * Unlike scx_bpf_exit(), no exit code is taken: the child is a separate 3175 * scheduler with its own exit-code semantics, so a code chosen by the parent 3176 * would have no defined meaning. The reason string carries the intent. 3177 * 3178 * Return 0 on success or -ENODEV if @cgroup_id names no sub-scheduler, which 3179 * can race with the child detaching on its own and so is not a scheduler error. 3180 * Naming a sched that exists but is not a direct child aborts the parent. 3181 */ 3182 __printf(2, 0) 3183 __bpf_kfunc s32 scx_bpf_sub_kill_bstr(u64 cgroup_id, char *fmt, 3184 unsigned long long *data, u32 data__sz, 3185 const struct bpf_prog_aux *aux) 3186 { 3187 struct scx_sched *parent, *child; 3188 3189 guard(rcu)(); 3190 3191 parent = scx_prog_sched(aux); 3192 if (unlikely(!parent)) 3193 return -ENODEV; 3194 3195 if (!scx_is_cid_type()) { 3196 scx_error(parent, "sub-cap kfuncs require a cid-form scheduler"); 3197 return -EOPNOTSUPP; 3198 } 3199 3200 child = scx_find_sub_sched(cgroup_id); 3201 if (unlikely(!child)) 3202 return -ENODEV; 3203 3204 if (unlikely(scx_parent(child) != parent)) { 3205 scx_error(parent, "%s: sub-%llu is not a direct child", 3206 parent->cgrp_path, cgroup_id); 3207 return -EINVAL; 3208 } 3209 3210 scx_exit_bstr(child, SCX_EXIT_PARENT_KILL, 0, parent, fmt, data, data__sz); 3211 return 0; 3212 } 3213 3214 __bpf_kfunc_end_defs(); 3215 3216 #else /* !CONFIG_EXT_SUB_SCHED */ 3217 3218 __bpf_kfunc_start_defs(); 3219 3220 __bpf_kfunc s32 scx_bpf_sub_grant(u64 cgroup_id, u64 caps, 3221 const struct scx_cmask *cmask__arena, 3222 struct scx_cmask *denied_out__arena__nullable, 3223 const struct bpf_prog_aux *aux) 3224 { 3225 return -EOPNOTSUPP; 3226 } 3227 3228 __bpf_kfunc void scx_bpf_sub_revoke(u64 cgroup_id, u64 caps, 3229 const struct scx_cmask *cmask__arena, 3230 const struct bpf_prog_aux *aux) 3231 { 3232 } 3233 3234 __bpf_kfunc s32 scx_bpf_sub_caps(u64 cgroup_id, u64 caps, struct scx_cmask *out__arena, 3235 const struct bpf_prog_aux *aux) 3236 { 3237 return -EOPNOTSUPP; 3238 } 3239 3240 __bpf_kfunc s32 scx_bpf_sub_kill_bstr(u64 cgroup_id, char *fmt, 3241 unsigned long long *data, u32 data__sz, 3242 const struct bpf_prog_aux *aux) 3243 { 3244 return -EOPNOTSUPP; 3245 } 3246 3247 __bpf_kfunc_end_defs(); 3248 3249 #endif /* CONFIG_EXT_SUB_SCHED */ 3250