1 /* SPDX-License-Identifier: GPL-2.0 */ 2 /* 3 * BPF extensible scheduler class: Documentation/scheduler/sched-ext.rst 4 * 5 * Copyright (c) 2022 Meta Platforms, Inc. and affiliates. 6 * Copyright (c) 2022 Tejun Heo <tj@kernel.org> 7 * Copyright (c) 2022 David Vernet <dvernet@meta.com> 8 */ 9 #include <linux/btf_ids.h> 10 #include "ext_idle.h" 11 12 /* 13 * NOTE: sched_ext is in the process of growing multiple scheduler support and 14 * scx_root usage is in a transitional state. Naked dereferences are safe if the 15 * caller is one of the tasks attached to SCX and explicit RCU dereference is 16 * necessary otherwise. Naked scx_root dereferences trigger sparse warnings but 17 * are used as temporary markers to indicate that the dereferences need to be 18 * updated to point to the associated scheduler instances rather than scx_root. 19 */ 20 static struct scx_sched __rcu *scx_root; 21 22 /* 23 * During exit, a task may schedule after losing its PIDs. When disabling the 24 * BPF scheduler, we need to be able to iterate tasks in every state to 25 * guarantee system safety. Maintain a dedicated task list which contains every 26 * task between its fork and eventual free. 27 */ 28 static DEFINE_SPINLOCK(scx_tasks_lock); 29 static LIST_HEAD(scx_tasks); 30 31 /* ops enable/disable */ 32 static DEFINE_MUTEX(scx_enable_mutex); 33 DEFINE_STATIC_KEY_FALSE(__scx_enabled); 34 DEFINE_STATIC_PERCPU_RWSEM(scx_fork_rwsem); 35 static atomic_t scx_enable_state_var = ATOMIC_INIT(SCX_DISABLED); 36 static unsigned long scx_in_softlockup; 37 static atomic_t scx_breather_depth = ATOMIC_INIT(0); 38 static int scx_bypass_depth; 39 static bool scx_init_task_enabled; 40 static bool scx_switching_all; 41 DEFINE_STATIC_KEY_FALSE(__scx_switched_all); 42 43 static atomic_long_t scx_nr_rejected = ATOMIC_LONG_INIT(0); 44 static atomic_long_t scx_hotplug_seq = ATOMIC_LONG_INIT(0); 45 46 /* 47 * A monotically increasing sequence number that is incremented every time a 48 * scheduler is enabled. This can be used by to check if any custom sched_ext 49 * scheduler has ever been used in the system. 50 */ 51 static atomic_long_t scx_enable_seq = ATOMIC_LONG_INIT(0); 52 53 /* 54 * The maximum amount of time in jiffies that a task may be runnable without 55 * being scheduled on a CPU. If this timeout is exceeded, it will trigger 56 * scx_error(). 57 */ 58 static unsigned long scx_watchdog_timeout; 59 60 /* 61 * The last time the delayed work was run. This delayed work relies on 62 * ksoftirqd being able to run to service timer interrupts, so it's possible 63 * that this work itself could get wedged. To account for this, we check that 64 * it's not stalled in the timer tick, and trigger an error if it is. 65 */ 66 static unsigned long scx_watchdog_timestamp = INITIAL_JIFFIES; 67 68 static struct delayed_work scx_watchdog_work; 69 70 /* 71 * For %SCX_KICK_WAIT: Each CPU has a pointer to an array of pick_task sequence 72 * numbers. The arrays are allocated with kvzalloc() as size can exceed percpu 73 * allocator limits on large machines. O(nr_cpu_ids^2) allocation, allocated 74 * lazily when enabling and freed when disabling to avoid waste when sched_ext 75 * isn't active. 76 */ 77 struct scx_kick_pseqs { 78 struct rcu_head rcu; 79 unsigned long seqs[]; 80 }; 81 82 static DEFINE_PER_CPU(struct scx_kick_pseqs __rcu *, scx_kick_pseqs); 83 84 /* 85 * Direct dispatch marker. 86 * 87 * Non-NULL values are used for direct dispatch from enqueue path. A valid 88 * pointer points to the task currently being enqueued. An ERR_PTR value is used 89 * to indicate that direct dispatch has already happened. 90 */ 91 static DEFINE_PER_CPU(struct task_struct *, direct_dispatch_task); 92 93 static const struct rhashtable_params dsq_hash_params = { 94 .key_len = sizeof_field(struct scx_dispatch_q, id), 95 .key_offset = offsetof(struct scx_dispatch_q, id), 96 .head_offset = offsetof(struct scx_dispatch_q, hash_node), 97 }; 98 99 static LLIST_HEAD(dsqs_to_free); 100 101 /* dispatch buf */ 102 struct scx_dsp_buf_ent { 103 struct task_struct *task; 104 unsigned long qseq; 105 u64 dsq_id; 106 u64 enq_flags; 107 }; 108 109 static u32 scx_dsp_max_batch; 110 111 struct scx_dsp_ctx { 112 struct rq *rq; 113 u32 cursor; 114 u32 nr_tasks; 115 struct scx_dsp_buf_ent buf[]; 116 }; 117 118 static struct scx_dsp_ctx __percpu *scx_dsp_ctx; 119 120 /* string formatting from BPF */ 121 struct scx_bstr_buf { 122 u64 data[MAX_BPRINTF_VARARGS]; 123 char line[SCX_EXIT_MSG_LEN]; 124 }; 125 126 static DEFINE_RAW_SPINLOCK(scx_exit_bstr_buf_lock); 127 static struct scx_bstr_buf scx_exit_bstr_buf; 128 129 /* ops debug dump */ 130 struct scx_dump_data { 131 s32 cpu; 132 bool first; 133 s32 cursor; 134 struct seq_buf *s; 135 const char *prefix; 136 struct scx_bstr_buf buf; 137 }; 138 139 static struct scx_dump_data scx_dump_data = { 140 .cpu = -1, 141 }; 142 143 /* /sys/kernel/sched_ext interface */ 144 static struct kset *scx_kset; 145 146 #define CREATE_TRACE_POINTS 147 #include <trace/events/sched_ext.h> 148 149 static void process_ddsp_deferred_locals(struct rq *rq); 150 static void scx_kick_cpu(struct scx_sched *sch, s32 cpu, u64 flags); 151 static void scx_vexit(struct scx_sched *sch, enum scx_exit_kind kind, 152 s64 exit_code, const char *fmt, va_list args); 153 154 static __printf(4, 5) void scx_exit(struct scx_sched *sch, 155 enum scx_exit_kind kind, s64 exit_code, 156 const char *fmt, ...) 157 { 158 va_list args; 159 160 va_start(args, fmt); 161 scx_vexit(sch, kind, exit_code, fmt, args); 162 va_end(args); 163 } 164 165 #define scx_error(sch, fmt, args...) scx_exit((sch), SCX_EXIT_ERROR, 0, fmt, ##args) 166 167 #define SCX_HAS_OP(sch, op) test_bit(SCX_OP_IDX(op), (sch)->has_op) 168 169 static long jiffies_delta_msecs(unsigned long at, unsigned long now) 170 { 171 if (time_after(at, now)) 172 return jiffies_to_msecs(at - now); 173 else 174 return -(long)jiffies_to_msecs(now - at); 175 } 176 177 /* if the highest set bit is N, return a mask with bits [N+1, 31] set */ 178 static u32 higher_bits(u32 flags) 179 { 180 return ~((1 << fls(flags)) - 1); 181 } 182 183 /* return the mask with only the highest bit set */ 184 static u32 highest_bit(u32 flags) 185 { 186 int bit = fls(flags); 187 return ((u64)1 << bit) >> 1; 188 } 189 190 static bool u32_before(u32 a, u32 b) 191 { 192 return (s32)(a - b) < 0; 193 } 194 195 static struct scx_dispatch_q *find_global_dsq(struct scx_sched *sch, 196 struct task_struct *p) 197 { 198 return sch->global_dsqs[cpu_to_node(task_cpu(p))]; 199 } 200 201 static struct scx_dispatch_q *find_user_dsq(struct scx_sched *sch, u64 dsq_id) 202 { 203 return rhashtable_lookup_fast(&sch->dsq_hash, &dsq_id, dsq_hash_params); 204 } 205 206 /* 207 * scx_kf_mask enforcement. Some kfuncs can only be called from specific SCX 208 * ops. When invoking SCX ops, SCX_CALL_OP[_RET]() should be used to indicate 209 * the allowed kfuncs and those kfuncs should use scx_kf_allowed() to check 210 * whether it's running from an allowed context. 211 * 212 * @mask is constant, always inline to cull the mask calculations. 213 */ 214 static __always_inline void scx_kf_allow(u32 mask) 215 { 216 /* nesting is allowed only in increasing scx_kf_mask order */ 217 WARN_ONCE((mask | higher_bits(mask)) & current->scx.kf_mask, 218 "invalid nesting current->scx.kf_mask=0x%x mask=0x%x\n", 219 current->scx.kf_mask, mask); 220 current->scx.kf_mask |= mask; 221 barrier(); 222 } 223 224 static void scx_kf_disallow(u32 mask) 225 { 226 barrier(); 227 current->scx.kf_mask &= ~mask; 228 } 229 230 /* 231 * Track the rq currently locked. 232 * 233 * This allows kfuncs to safely operate on rq from any scx ops callback, 234 * knowing which rq is already locked. 235 */ 236 DEFINE_PER_CPU(struct rq *, scx_locked_rq_state); 237 238 static inline void update_locked_rq(struct rq *rq) 239 { 240 /* 241 * Check whether @rq is actually locked. This can help expose bugs 242 * or incorrect assumptions about the context in which a kfunc or 243 * callback is executed. 244 */ 245 if (rq) 246 lockdep_assert_rq_held(rq); 247 __this_cpu_write(scx_locked_rq_state, rq); 248 } 249 250 #define SCX_CALL_OP(sch, mask, op, rq, args...) \ 251 do { \ 252 if (rq) \ 253 update_locked_rq(rq); \ 254 if (mask) { \ 255 scx_kf_allow(mask); \ 256 (sch)->ops.op(args); \ 257 scx_kf_disallow(mask); \ 258 } else { \ 259 (sch)->ops.op(args); \ 260 } \ 261 if (rq) \ 262 update_locked_rq(NULL); \ 263 } while (0) 264 265 #define SCX_CALL_OP_RET(sch, mask, op, rq, args...) \ 266 ({ \ 267 __typeof__((sch)->ops.op(args)) __ret; \ 268 \ 269 if (rq) \ 270 update_locked_rq(rq); \ 271 if (mask) { \ 272 scx_kf_allow(mask); \ 273 __ret = (sch)->ops.op(args); \ 274 scx_kf_disallow(mask); \ 275 } else { \ 276 __ret = (sch)->ops.op(args); \ 277 } \ 278 if (rq) \ 279 update_locked_rq(NULL); \ 280 __ret; \ 281 }) 282 283 /* 284 * Some kfuncs are allowed only on the tasks that are subjects of the 285 * in-progress scx_ops operation for, e.g., locking guarantees. To enforce such 286 * restrictions, the following SCX_CALL_OP_*() variants should be used when 287 * invoking scx_ops operations that take task arguments. These can only be used 288 * for non-nesting operations due to the way the tasks are tracked. 289 * 290 * kfuncs which can only operate on such tasks can in turn use 291 * scx_kf_allowed_on_arg_tasks() to test whether the invocation is allowed on 292 * the specific task. 293 */ 294 #define SCX_CALL_OP_TASK(sch, mask, op, rq, task, args...) \ 295 do { \ 296 BUILD_BUG_ON((mask) & ~__SCX_KF_TERMINAL); \ 297 current->scx.kf_tasks[0] = task; \ 298 SCX_CALL_OP((sch), mask, op, rq, task, ##args); \ 299 current->scx.kf_tasks[0] = NULL; \ 300 } while (0) 301 302 #define SCX_CALL_OP_TASK_RET(sch, mask, op, rq, task, args...) \ 303 ({ \ 304 __typeof__((sch)->ops.op(task, ##args)) __ret; \ 305 BUILD_BUG_ON((mask) & ~__SCX_KF_TERMINAL); \ 306 current->scx.kf_tasks[0] = task; \ 307 __ret = SCX_CALL_OP_RET((sch), mask, op, rq, task, ##args); \ 308 current->scx.kf_tasks[0] = NULL; \ 309 __ret; \ 310 }) 311 312 #define SCX_CALL_OP_2TASKS_RET(sch, mask, op, rq, task0, task1, args...) \ 313 ({ \ 314 __typeof__((sch)->ops.op(task0, task1, ##args)) __ret; \ 315 BUILD_BUG_ON((mask) & ~__SCX_KF_TERMINAL); \ 316 current->scx.kf_tasks[0] = task0; \ 317 current->scx.kf_tasks[1] = task1; \ 318 __ret = SCX_CALL_OP_RET((sch), mask, op, rq, task0, task1, ##args); \ 319 current->scx.kf_tasks[0] = NULL; \ 320 current->scx.kf_tasks[1] = NULL; \ 321 __ret; \ 322 }) 323 324 /* @mask is constant, always inline to cull unnecessary branches */ 325 static __always_inline bool scx_kf_allowed(struct scx_sched *sch, u32 mask) 326 { 327 if (unlikely(!(current->scx.kf_mask & mask))) { 328 scx_error(sch, "kfunc with mask 0x%x called from an operation only allowing 0x%x", 329 mask, current->scx.kf_mask); 330 return false; 331 } 332 333 /* 334 * Enforce nesting boundaries. e.g. A kfunc which can be called from 335 * DISPATCH must not be called if we're running DEQUEUE which is nested 336 * inside ops.dispatch(). We don't need to check boundaries for any 337 * blocking kfuncs as the verifier ensures they're only called from 338 * sleepable progs. 339 */ 340 if (unlikely(highest_bit(mask) == SCX_KF_CPU_RELEASE && 341 (current->scx.kf_mask & higher_bits(SCX_KF_CPU_RELEASE)))) { 342 scx_error(sch, "cpu_release kfunc called from a nested operation"); 343 return false; 344 } 345 346 if (unlikely(highest_bit(mask) == SCX_KF_DISPATCH && 347 (current->scx.kf_mask & higher_bits(SCX_KF_DISPATCH)))) { 348 scx_error(sch, "dispatch kfunc called from a nested operation"); 349 return false; 350 } 351 352 return true; 353 } 354 355 /* see SCX_CALL_OP_TASK() */ 356 static __always_inline bool scx_kf_allowed_on_arg_tasks(struct scx_sched *sch, 357 u32 mask, 358 struct task_struct *p) 359 { 360 if (!scx_kf_allowed(sch, mask)) 361 return false; 362 363 if (unlikely((p != current->scx.kf_tasks[0] && 364 p != current->scx.kf_tasks[1]))) { 365 scx_error(sch, "called on a task not being operated on"); 366 return false; 367 } 368 369 return true; 370 } 371 372 /** 373 * nldsq_next_task - Iterate to the next task in a non-local DSQ 374 * @dsq: user dsq being iterated 375 * @cur: current position, %NULL to start iteration 376 * @rev: walk backwards 377 * 378 * Returns %NULL when iteration is finished. 379 */ 380 static struct task_struct *nldsq_next_task(struct scx_dispatch_q *dsq, 381 struct task_struct *cur, bool rev) 382 { 383 struct list_head *list_node; 384 struct scx_dsq_list_node *dsq_lnode; 385 386 lockdep_assert_held(&dsq->lock); 387 388 if (cur) 389 list_node = &cur->scx.dsq_list.node; 390 else 391 list_node = &dsq->list; 392 393 /* find the next task, need to skip BPF iteration cursors */ 394 do { 395 if (rev) 396 list_node = list_node->prev; 397 else 398 list_node = list_node->next; 399 400 if (list_node == &dsq->list) 401 return NULL; 402 403 dsq_lnode = container_of(list_node, struct scx_dsq_list_node, 404 node); 405 } while (dsq_lnode->flags & SCX_DSQ_LNODE_ITER_CURSOR); 406 407 return container_of(dsq_lnode, struct task_struct, scx.dsq_list); 408 } 409 410 #define nldsq_for_each_task(p, dsq) \ 411 for ((p) = nldsq_next_task((dsq), NULL, false); (p); \ 412 (p) = nldsq_next_task((dsq), (p), false)) 413 414 415 /* 416 * BPF DSQ iterator. Tasks in a non-local DSQ can be iterated in [reverse] 417 * dispatch order. BPF-visible iterator is opaque and larger to allow future 418 * changes without breaking backward compatibility. Can be used with 419 * bpf_for_each(). See bpf_iter_scx_dsq_*(). 420 */ 421 enum scx_dsq_iter_flags { 422 /* iterate in the reverse dispatch order */ 423 SCX_DSQ_ITER_REV = 1U << 16, 424 425 __SCX_DSQ_ITER_HAS_SLICE = 1U << 30, 426 __SCX_DSQ_ITER_HAS_VTIME = 1U << 31, 427 428 __SCX_DSQ_ITER_USER_FLAGS = SCX_DSQ_ITER_REV, 429 __SCX_DSQ_ITER_ALL_FLAGS = __SCX_DSQ_ITER_USER_FLAGS | 430 __SCX_DSQ_ITER_HAS_SLICE | 431 __SCX_DSQ_ITER_HAS_VTIME, 432 }; 433 434 struct bpf_iter_scx_dsq_kern { 435 struct scx_dsq_list_node cursor; 436 struct scx_dispatch_q *dsq; 437 u64 slice; 438 u64 vtime; 439 } __attribute__((aligned(8))); 440 441 struct bpf_iter_scx_dsq { 442 u64 __opaque[6]; 443 } __attribute__((aligned(8))); 444 445 446 /* 447 * SCX task iterator. 448 */ 449 struct scx_task_iter { 450 struct sched_ext_entity cursor; 451 struct task_struct *locked_task; 452 struct rq *rq; 453 struct rq_flags rf; 454 u32 cnt; 455 bool list_locked; 456 }; 457 458 /** 459 * scx_task_iter_start - Lock scx_tasks_lock and start a task iteration 460 * @iter: iterator to init 461 * 462 * Initialize @iter and return with scx_tasks_lock held. Once initialized, @iter 463 * must eventually be stopped with scx_task_iter_stop(). 464 * 465 * scx_tasks_lock and the rq lock may be released using scx_task_iter_unlock() 466 * between this and the first next() call or between any two next() calls. If 467 * the locks are released between two next() calls, the caller is responsible 468 * for ensuring that the task being iterated remains accessible either through 469 * RCU read lock or obtaining a reference count. 470 * 471 * All tasks which existed when the iteration started are guaranteed to be 472 * visited as long as they still exist. 473 */ 474 static void scx_task_iter_start(struct scx_task_iter *iter) 475 { 476 BUILD_BUG_ON(__SCX_DSQ_ITER_ALL_FLAGS & 477 ((1U << __SCX_DSQ_LNODE_PRIV_SHIFT) - 1)); 478 479 spin_lock_irq(&scx_tasks_lock); 480 481 iter->cursor = (struct sched_ext_entity){ .flags = SCX_TASK_CURSOR }; 482 list_add(&iter->cursor.tasks_node, &scx_tasks); 483 iter->locked_task = NULL; 484 iter->cnt = 0; 485 iter->list_locked = true; 486 } 487 488 static void __scx_task_iter_rq_unlock(struct scx_task_iter *iter) 489 { 490 if (iter->locked_task) { 491 task_rq_unlock(iter->rq, iter->locked_task, &iter->rf); 492 iter->locked_task = NULL; 493 } 494 } 495 496 /** 497 * scx_task_iter_unlock - Unlock rq and scx_tasks_lock held by a task iterator 498 * @iter: iterator to unlock 499 * 500 * If @iter is in the middle of a locked iteration, it may be locking the rq of 501 * the task currently being visited in addition to scx_tasks_lock. Unlock both. 502 * This function can be safely called anytime during an iteration. The next 503 * iterator operation will automatically restore the necessary locking. 504 */ 505 static void scx_task_iter_unlock(struct scx_task_iter *iter) 506 { 507 __scx_task_iter_rq_unlock(iter); 508 if (iter->list_locked) { 509 iter->list_locked = false; 510 spin_unlock_irq(&scx_tasks_lock); 511 } 512 } 513 514 static void __scx_task_iter_maybe_relock(struct scx_task_iter *iter) 515 { 516 if (!iter->list_locked) { 517 spin_lock_irq(&scx_tasks_lock); 518 iter->list_locked = true; 519 } 520 } 521 522 /** 523 * scx_task_iter_stop - Stop a task iteration and unlock scx_tasks_lock 524 * @iter: iterator to exit 525 * 526 * Exit a previously initialized @iter. Must be called with scx_tasks_lock held 527 * which is released on return. If the iterator holds a task's rq lock, that rq 528 * lock is also released. See scx_task_iter_start() for details. 529 */ 530 static void scx_task_iter_stop(struct scx_task_iter *iter) 531 { 532 __scx_task_iter_maybe_relock(iter); 533 list_del_init(&iter->cursor.tasks_node); 534 scx_task_iter_unlock(iter); 535 } 536 537 /** 538 * scx_task_iter_next - Next task 539 * @iter: iterator to walk 540 * 541 * Visit the next task. See scx_task_iter_start() for details. Locks are dropped 542 * and re-acquired every %SCX_TASK_ITER_BATCH iterations to avoid causing stalls 543 * by holding scx_tasks_lock for too long. 544 */ 545 static struct task_struct *scx_task_iter_next(struct scx_task_iter *iter) 546 { 547 struct list_head *cursor = &iter->cursor.tasks_node; 548 struct sched_ext_entity *pos; 549 550 __scx_task_iter_maybe_relock(iter); 551 552 if (!(++iter->cnt % SCX_TASK_ITER_BATCH)) { 553 scx_task_iter_unlock(iter); 554 cond_resched(); 555 __scx_task_iter_maybe_relock(iter); 556 } 557 558 list_for_each_entry(pos, cursor, tasks_node) { 559 if (&pos->tasks_node == &scx_tasks) 560 return NULL; 561 if (!(pos->flags & SCX_TASK_CURSOR)) { 562 list_move(cursor, &pos->tasks_node); 563 return container_of(pos, struct task_struct, scx); 564 } 565 } 566 567 /* can't happen, should always terminate at scx_tasks above */ 568 BUG(); 569 } 570 571 /** 572 * scx_task_iter_next_locked - Next non-idle task with its rq locked 573 * @iter: iterator to walk 574 * 575 * Visit the non-idle task with its rq lock held. Allows callers to specify 576 * whether they would like to filter out dead tasks. See scx_task_iter_start() 577 * for details. 578 */ 579 static struct task_struct *scx_task_iter_next_locked(struct scx_task_iter *iter) 580 { 581 struct task_struct *p; 582 583 __scx_task_iter_rq_unlock(iter); 584 585 while ((p = scx_task_iter_next(iter))) { 586 /* 587 * scx_task_iter is used to prepare and move tasks into SCX 588 * while loading the BPF scheduler and vice-versa while 589 * unloading. The init_tasks ("swappers") should be excluded 590 * from the iteration because: 591 * 592 * - It's unsafe to use __setschduler_prio() on an init_task to 593 * determine the sched_class to use as it won't preserve its 594 * idle_sched_class. 595 * 596 * - ops.init/exit_task() can easily be confused if called with 597 * init_tasks as they, e.g., share PID 0. 598 * 599 * As init_tasks are never scheduled through SCX, they can be 600 * skipped safely. Note that is_idle_task() which tests %PF_IDLE 601 * doesn't work here: 602 * 603 * - %PF_IDLE may not be set for an init_task whose CPU hasn't 604 * yet been onlined. 605 * 606 * - %PF_IDLE can be set on tasks that are not init_tasks. See 607 * play_idle_precise() used by CONFIG_IDLE_INJECT. 608 * 609 * Test for idle_sched_class as only init_tasks are on it. 610 */ 611 if (p->sched_class != &idle_sched_class) 612 break; 613 } 614 if (!p) 615 return NULL; 616 617 iter->rq = task_rq_lock(p, &iter->rf); 618 iter->locked_task = p; 619 620 return p; 621 } 622 623 /** 624 * scx_add_event - Increase an event counter for 'name' by 'cnt' 625 * @sch: scx_sched to account events for 626 * @name: an event name defined in struct scx_event_stats 627 * @cnt: the number of the event occurred 628 * 629 * This can be used when preemption is not disabled. 630 */ 631 #define scx_add_event(sch, name, cnt) do { \ 632 this_cpu_add((sch)->pcpu->event_stats.name, (cnt)); \ 633 trace_sched_ext_event(#name, (cnt)); \ 634 } while(0) 635 636 /** 637 * __scx_add_event - Increase an event counter for 'name' by 'cnt' 638 * @sch: scx_sched to account events for 639 * @name: an event name defined in struct scx_event_stats 640 * @cnt: the number of the event occurred 641 * 642 * This should be used only when preemption is disabled. 643 */ 644 #define __scx_add_event(sch, name, cnt) do { \ 645 __this_cpu_add((sch)->pcpu->event_stats.name, (cnt)); \ 646 trace_sched_ext_event(#name, cnt); \ 647 } while(0) 648 649 /** 650 * scx_agg_event - Aggregate an event counter 'kind' from 'src_e' to 'dst_e' 651 * @dst_e: destination event stats 652 * @src_e: source event stats 653 * @kind: a kind of event to be aggregated 654 */ 655 #define scx_agg_event(dst_e, src_e, kind) do { \ 656 (dst_e)->kind += READ_ONCE((src_e)->kind); \ 657 } while(0) 658 659 /** 660 * scx_dump_event - Dump an event 'kind' in 'events' to 's' 661 * @s: output seq_buf 662 * @events: event stats 663 * @kind: a kind of event to dump 664 */ 665 #define scx_dump_event(s, events, kind) do { \ 666 dump_line(&(s), "%40s: %16lld", #kind, (events)->kind); \ 667 } while (0) 668 669 670 static void scx_read_events(struct scx_sched *sch, 671 struct scx_event_stats *events); 672 673 static enum scx_enable_state scx_enable_state(void) 674 { 675 return atomic_read(&scx_enable_state_var); 676 } 677 678 static enum scx_enable_state scx_set_enable_state(enum scx_enable_state to) 679 { 680 return atomic_xchg(&scx_enable_state_var, to); 681 } 682 683 static bool scx_tryset_enable_state(enum scx_enable_state to, 684 enum scx_enable_state from) 685 { 686 int from_v = from; 687 688 return atomic_try_cmpxchg(&scx_enable_state_var, &from_v, to); 689 } 690 691 /** 692 * wait_ops_state - Busy-wait the specified ops state to end 693 * @p: target task 694 * @opss: state to wait the end of 695 * 696 * Busy-wait for @p to transition out of @opss. This can only be used when the 697 * state part of @opss is %SCX_QUEUEING or %SCX_DISPATCHING. This function also 698 * has load_acquire semantics to ensure that the caller can see the updates made 699 * in the enqueueing and dispatching paths. 700 */ 701 static void wait_ops_state(struct task_struct *p, unsigned long opss) 702 { 703 do { 704 cpu_relax(); 705 } while (atomic_long_read_acquire(&p->scx.ops_state) == opss); 706 } 707 708 static inline bool __cpu_valid(s32 cpu) 709 { 710 return likely(cpu >= 0 && cpu < nr_cpu_ids && cpu_possible(cpu)); 711 } 712 713 /** 714 * ops_cpu_valid - Verify a cpu number, to be used on ops input args 715 * @sch: scx_sched to abort on error 716 * @cpu: cpu number which came from a BPF ops 717 * @where: extra information reported on error 718 * 719 * @cpu is a cpu number which came from the BPF scheduler and can be any value. 720 * Verify that it is in range and one of the possible cpus. If invalid, trigger 721 * an ops error. 722 */ 723 static bool ops_cpu_valid(struct scx_sched *sch, s32 cpu, const char *where) 724 { 725 if (__cpu_valid(cpu)) { 726 return true; 727 } else { 728 scx_error(sch, "invalid CPU %d%s%s", cpu, where ? " " : "", where ?: ""); 729 return false; 730 } 731 } 732 733 /** 734 * ops_sanitize_err - Sanitize a -errno value 735 * @sch: scx_sched to error out on error 736 * @ops_name: operation to blame on failure 737 * @err: -errno value to sanitize 738 * 739 * Verify @err is a valid -errno. If not, trigger scx_error() and return 740 * -%EPROTO. This is necessary because returning a rogue -errno up the chain can 741 * cause misbehaviors. For an example, a large negative return from 742 * ops.init_task() triggers an oops when passed up the call chain because the 743 * value fails IS_ERR() test after being encoded with ERR_PTR() and then is 744 * handled as a pointer. 745 */ 746 static int ops_sanitize_err(struct scx_sched *sch, const char *ops_name, s32 err) 747 { 748 if (err < 0 && err >= -MAX_ERRNO) 749 return err; 750 751 scx_error(sch, "ops.%s() returned an invalid errno %d", ops_name, err); 752 return -EPROTO; 753 } 754 755 static void run_deferred(struct rq *rq) 756 { 757 process_ddsp_deferred_locals(rq); 758 } 759 760 static void deferred_bal_cb_workfn(struct rq *rq) 761 { 762 run_deferred(rq); 763 } 764 765 static void deferred_irq_workfn(struct irq_work *irq_work) 766 { 767 struct rq *rq = container_of(irq_work, struct rq, scx.deferred_irq_work); 768 769 raw_spin_rq_lock(rq); 770 run_deferred(rq); 771 raw_spin_rq_unlock(rq); 772 } 773 774 /** 775 * schedule_deferred - Schedule execution of deferred actions on an rq 776 * @rq: target rq 777 * 778 * Schedule execution of deferred actions on @rq. Must be called with @rq 779 * locked. Deferred actions are executed with @rq locked but unpinned, and thus 780 * can unlock @rq to e.g. migrate tasks to other rqs. 781 */ 782 static void schedule_deferred(struct rq *rq) 783 { 784 lockdep_assert_rq_held(rq); 785 786 /* 787 * If in the middle of waking up a task, task_woken_scx() will be called 788 * afterwards which will then run the deferred actions, no need to 789 * schedule anything. 790 */ 791 if (rq->scx.flags & SCX_RQ_IN_WAKEUP) 792 return; 793 794 /* Don't do anything if there already is a deferred operation. */ 795 if (rq->scx.flags & SCX_RQ_BAL_PENDING) 796 return; 797 798 /* 799 * If in balance, the balance callbacks will be called before rq lock is 800 * released. Schedule one. 801 * 802 * 803 * We can't directly insert the callback into the 804 * rq's list: The call can drop its lock and make the pending balance 805 * callback visible to unrelated code paths that call rq_pin_lock(). 806 * 807 * Just let balance_one() know that it must do it itself. 808 */ 809 if (rq->scx.flags & SCX_RQ_IN_BALANCE) { 810 rq->scx.flags |= SCX_RQ_BAL_CB_PENDING; 811 return; 812 } 813 814 /* 815 * No scheduler hooks available. Queue an irq work. They are executed on 816 * IRQ re-enable which may take a bit longer than the scheduler hooks. 817 * The above WAKEUP and BALANCE paths should cover most of the cases and 818 * the time to IRQ re-enable shouldn't be long. 819 */ 820 irq_work_queue(&rq->scx.deferred_irq_work); 821 } 822 823 /** 824 * touch_core_sched - Update timestamp used for core-sched task ordering 825 * @rq: rq to read clock from, must be locked 826 * @p: task to update the timestamp for 827 * 828 * Update @p->scx.core_sched_at timestamp. This is used by scx_prio_less() to 829 * implement global or local-DSQ FIFO ordering for core-sched. Should be called 830 * when a task becomes runnable and its turn on the CPU ends (e.g. slice 831 * exhaustion). 832 */ 833 static void touch_core_sched(struct rq *rq, struct task_struct *p) 834 { 835 lockdep_assert_rq_held(rq); 836 837 #ifdef CONFIG_SCHED_CORE 838 /* 839 * It's okay to update the timestamp spuriously. Use 840 * sched_core_disabled() which is cheaper than enabled(). 841 * 842 * As this is used to determine ordering between tasks of sibling CPUs, 843 * it may be better to use per-core dispatch sequence instead. 844 */ 845 if (!sched_core_disabled()) 846 p->scx.core_sched_at = sched_clock_cpu(cpu_of(rq)); 847 #endif 848 } 849 850 /** 851 * touch_core_sched_dispatch - Update core-sched timestamp on dispatch 852 * @rq: rq to read clock from, must be locked 853 * @p: task being dispatched 854 * 855 * If the BPF scheduler implements custom core-sched ordering via 856 * ops.core_sched_before(), @p->scx.core_sched_at is used to implement FIFO 857 * ordering within each local DSQ. This function is called from dispatch paths 858 * and updates @p->scx.core_sched_at if custom core-sched ordering is in effect. 859 */ 860 static void touch_core_sched_dispatch(struct rq *rq, struct task_struct *p) 861 { 862 lockdep_assert_rq_held(rq); 863 864 #ifdef CONFIG_SCHED_CORE 865 if (unlikely(SCX_HAS_OP(scx_root, core_sched_before))) 866 touch_core_sched(rq, p); 867 #endif 868 } 869 870 static void update_curr_scx(struct rq *rq) 871 { 872 struct task_struct *curr = rq->curr; 873 s64 delta_exec; 874 875 delta_exec = update_curr_common(rq); 876 if (unlikely(delta_exec <= 0)) 877 return; 878 879 if (curr->scx.slice != SCX_SLICE_INF) { 880 curr->scx.slice -= min_t(u64, curr->scx.slice, delta_exec); 881 if (!curr->scx.slice) 882 touch_core_sched(rq, curr); 883 } 884 } 885 886 static bool scx_dsq_priq_less(struct rb_node *node_a, 887 const struct rb_node *node_b) 888 { 889 const struct task_struct *a = 890 container_of(node_a, struct task_struct, scx.dsq_priq); 891 const struct task_struct *b = 892 container_of(node_b, struct task_struct, scx.dsq_priq); 893 894 return time_before64(a->scx.dsq_vtime, b->scx.dsq_vtime); 895 } 896 897 static void dsq_mod_nr(struct scx_dispatch_q *dsq, s32 delta) 898 { 899 /* scx_bpf_dsq_nr_queued() reads ->nr without locking, use WRITE_ONCE() */ 900 WRITE_ONCE(dsq->nr, dsq->nr + delta); 901 } 902 903 static void refill_task_slice_dfl(struct scx_sched *sch, struct task_struct *p) 904 { 905 p->scx.slice = SCX_SLICE_DFL; 906 __scx_add_event(sch, SCX_EV_REFILL_SLICE_DFL, 1); 907 } 908 909 static void dispatch_enqueue(struct scx_sched *sch, struct scx_dispatch_q *dsq, 910 struct task_struct *p, u64 enq_flags) 911 { 912 bool is_local = dsq->id == SCX_DSQ_LOCAL; 913 914 WARN_ON_ONCE(p->scx.dsq || !list_empty(&p->scx.dsq_list.node)); 915 WARN_ON_ONCE((p->scx.dsq_flags & SCX_TASK_DSQ_ON_PRIQ) || 916 !RB_EMPTY_NODE(&p->scx.dsq_priq)); 917 918 if (!is_local) { 919 raw_spin_lock(&dsq->lock); 920 if (unlikely(dsq->id == SCX_DSQ_INVALID)) { 921 scx_error(sch, "attempting to dispatch to a destroyed dsq"); 922 /* fall back to the global dsq */ 923 raw_spin_unlock(&dsq->lock); 924 dsq = find_global_dsq(sch, p); 925 raw_spin_lock(&dsq->lock); 926 } 927 } 928 929 if (unlikely((dsq->id & SCX_DSQ_FLAG_BUILTIN) && 930 (enq_flags & SCX_ENQ_DSQ_PRIQ))) { 931 /* 932 * SCX_DSQ_LOCAL and SCX_DSQ_GLOBAL DSQs always consume from 933 * their FIFO queues. To avoid confusion and accidentally 934 * starving vtime-dispatched tasks by FIFO-dispatched tasks, we 935 * disallow any internal DSQ from doing vtime ordering of 936 * tasks. 937 */ 938 scx_error(sch, "cannot use vtime ordering for built-in DSQs"); 939 enq_flags &= ~SCX_ENQ_DSQ_PRIQ; 940 } 941 942 if (enq_flags & SCX_ENQ_DSQ_PRIQ) { 943 struct rb_node *rbp; 944 945 /* 946 * A PRIQ DSQ shouldn't be using FIFO enqueueing. As tasks are 947 * linked to both the rbtree and list on PRIQs, this can only be 948 * tested easily when adding the first task. 949 */ 950 if (unlikely(RB_EMPTY_ROOT(&dsq->priq) && 951 nldsq_next_task(dsq, NULL, false))) 952 scx_error(sch, "DSQ ID 0x%016llx already had FIFO-enqueued tasks", 953 dsq->id); 954 955 p->scx.dsq_flags |= SCX_TASK_DSQ_ON_PRIQ; 956 rb_add(&p->scx.dsq_priq, &dsq->priq, scx_dsq_priq_less); 957 958 /* 959 * Find the previous task and insert after it on the list so 960 * that @dsq->list is vtime ordered. 961 */ 962 rbp = rb_prev(&p->scx.dsq_priq); 963 if (rbp) { 964 struct task_struct *prev = 965 container_of(rbp, struct task_struct, 966 scx.dsq_priq); 967 list_add(&p->scx.dsq_list.node, &prev->scx.dsq_list.node); 968 } else { 969 list_add(&p->scx.dsq_list.node, &dsq->list); 970 } 971 } else { 972 /* a FIFO DSQ shouldn't be using PRIQ enqueuing */ 973 if (unlikely(!RB_EMPTY_ROOT(&dsq->priq))) 974 scx_error(sch, "DSQ ID 0x%016llx already had PRIQ-enqueued tasks", 975 dsq->id); 976 977 if (enq_flags & (SCX_ENQ_HEAD | SCX_ENQ_PREEMPT)) 978 list_add(&p->scx.dsq_list.node, &dsq->list); 979 else 980 list_add_tail(&p->scx.dsq_list.node, &dsq->list); 981 } 982 983 /* seq records the order tasks are queued, used by BPF DSQ iterator */ 984 dsq->seq++; 985 p->scx.dsq_seq = dsq->seq; 986 987 dsq_mod_nr(dsq, 1); 988 p->scx.dsq = dsq; 989 990 /* 991 * scx.ddsp_dsq_id and scx.ddsp_enq_flags are only relevant on the 992 * direct dispatch path, but we clear them here because the direct 993 * dispatch verdict may be overridden on the enqueue path during e.g. 994 * bypass. 995 */ 996 p->scx.ddsp_dsq_id = SCX_DSQ_INVALID; 997 p->scx.ddsp_enq_flags = 0; 998 999 /* 1000 * We're transitioning out of QUEUEING or DISPATCHING. store_release to 1001 * match waiters' load_acquire. 1002 */ 1003 if (enq_flags & SCX_ENQ_CLEAR_OPSS) 1004 atomic_long_set_release(&p->scx.ops_state, SCX_OPSS_NONE); 1005 1006 if (is_local) { 1007 struct rq *rq = container_of(dsq, struct rq, scx.local_dsq); 1008 bool preempt = false; 1009 1010 if ((enq_flags & SCX_ENQ_PREEMPT) && p != rq->curr && 1011 rq->curr->sched_class == &ext_sched_class) { 1012 rq->curr->scx.slice = 0; 1013 preempt = true; 1014 } 1015 1016 if (preempt || sched_class_above(&ext_sched_class, 1017 rq->curr->sched_class)) 1018 resched_curr(rq); 1019 } else { 1020 raw_spin_unlock(&dsq->lock); 1021 } 1022 } 1023 1024 static void task_unlink_from_dsq(struct task_struct *p, 1025 struct scx_dispatch_q *dsq) 1026 { 1027 WARN_ON_ONCE(list_empty(&p->scx.dsq_list.node)); 1028 1029 if (p->scx.dsq_flags & SCX_TASK_DSQ_ON_PRIQ) { 1030 rb_erase(&p->scx.dsq_priq, &dsq->priq); 1031 RB_CLEAR_NODE(&p->scx.dsq_priq); 1032 p->scx.dsq_flags &= ~SCX_TASK_DSQ_ON_PRIQ; 1033 } 1034 1035 list_del_init(&p->scx.dsq_list.node); 1036 dsq_mod_nr(dsq, -1); 1037 } 1038 1039 static void dispatch_dequeue(struct rq *rq, struct task_struct *p) 1040 { 1041 struct scx_dispatch_q *dsq = p->scx.dsq; 1042 bool is_local = dsq == &rq->scx.local_dsq; 1043 1044 if (!dsq) { 1045 /* 1046 * If !dsq && on-list, @p is on @rq's ddsp_deferred_locals. 1047 * Unlinking is all that's needed to cancel. 1048 */ 1049 if (unlikely(!list_empty(&p->scx.dsq_list.node))) 1050 list_del_init(&p->scx.dsq_list.node); 1051 1052 /* 1053 * When dispatching directly from the BPF scheduler to a local 1054 * DSQ, the task isn't associated with any DSQ but 1055 * @p->scx.holding_cpu may be set under the protection of 1056 * %SCX_OPSS_DISPATCHING. 1057 */ 1058 if (p->scx.holding_cpu >= 0) 1059 p->scx.holding_cpu = -1; 1060 1061 return; 1062 } 1063 1064 if (!is_local) 1065 raw_spin_lock(&dsq->lock); 1066 1067 /* 1068 * Now that we hold @dsq->lock, @p->holding_cpu and @p->scx.dsq_* can't 1069 * change underneath us. 1070 */ 1071 if (p->scx.holding_cpu < 0) { 1072 /* @p must still be on @dsq, dequeue */ 1073 task_unlink_from_dsq(p, dsq); 1074 } else { 1075 /* 1076 * We're racing against dispatch_to_local_dsq() which already 1077 * removed @p from @dsq and set @p->scx.holding_cpu. Clear the 1078 * holding_cpu which tells dispatch_to_local_dsq() that it lost 1079 * the race. 1080 */ 1081 WARN_ON_ONCE(!list_empty(&p->scx.dsq_list.node)); 1082 p->scx.holding_cpu = -1; 1083 } 1084 p->scx.dsq = NULL; 1085 1086 if (!is_local) 1087 raw_spin_unlock(&dsq->lock); 1088 } 1089 1090 static struct scx_dispatch_q *find_dsq_for_dispatch(struct scx_sched *sch, 1091 struct rq *rq, u64 dsq_id, 1092 struct task_struct *p) 1093 { 1094 struct scx_dispatch_q *dsq; 1095 1096 if (dsq_id == SCX_DSQ_LOCAL) 1097 return &rq->scx.local_dsq; 1098 1099 if ((dsq_id & SCX_DSQ_LOCAL_ON) == SCX_DSQ_LOCAL_ON) { 1100 s32 cpu = dsq_id & SCX_DSQ_LOCAL_CPU_MASK; 1101 1102 if (!ops_cpu_valid(sch, cpu, "in SCX_DSQ_LOCAL_ON dispatch verdict")) 1103 return find_global_dsq(sch, p); 1104 1105 return &cpu_rq(cpu)->scx.local_dsq; 1106 } 1107 1108 if (dsq_id == SCX_DSQ_GLOBAL) 1109 dsq = find_global_dsq(sch, p); 1110 else 1111 dsq = find_user_dsq(sch, dsq_id); 1112 1113 if (unlikely(!dsq)) { 1114 scx_error(sch, "non-existent DSQ 0x%llx for %s[%d]", 1115 dsq_id, p->comm, p->pid); 1116 return find_global_dsq(sch, p); 1117 } 1118 1119 return dsq; 1120 } 1121 1122 static void mark_direct_dispatch(struct scx_sched *sch, 1123 struct task_struct *ddsp_task, 1124 struct task_struct *p, u64 dsq_id, 1125 u64 enq_flags) 1126 { 1127 /* 1128 * Mark that dispatch already happened from ops.select_cpu() or 1129 * ops.enqueue() by spoiling direct_dispatch_task with a non-NULL value 1130 * which can never match a valid task pointer. 1131 */ 1132 __this_cpu_write(direct_dispatch_task, ERR_PTR(-ESRCH)); 1133 1134 /* @p must match the task on the enqueue path */ 1135 if (unlikely(p != ddsp_task)) { 1136 if (IS_ERR(ddsp_task)) 1137 scx_error(sch, "%s[%d] already direct-dispatched", 1138 p->comm, p->pid); 1139 else 1140 scx_error(sch, "scheduling for %s[%d] but trying to direct-dispatch %s[%d]", 1141 ddsp_task->comm, ddsp_task->pid, 1142 p->comm, p->pid); 1143 return; 1144 } 1145 1146 WARN_ON_ONCE(p->scx.ddsp_dsq_id != SCX_DSQ_INVALID); 1147 WARN_ON_ONCE(p->scx.ddsp_enq_flags); 1148 1149 p->scx.ddsp_dsq_id = dsq_id; 1150 p->scx.ddsp_enq_flags = enq_flags; 1151 } 1152 1153 static void direct_dispatch(struct scx_sched *sch, struct task_struct *p, 1154 u64 enq_flags) 1155 { 1156 struct rq *rq = task_rq(p); 1157 struct scx_dispatch_q *dsq = 1158 find_dsq_for_dispatch(sch, rq, p->scx.ddsp_dsq_id, p); 1159 1160 touch_core_sched_dispatch(rq, p); 1161 1162 p->scx.ddsp_enq_flags |= enq_flags; 1163 1164 /* 1165 * We are in the enqueue path with @rq locked and pinned, and thus can't 1166 * double lock a remote rq and enqueue to its local DSQ. For 1167 * DSQ_LOCAL_ON verdicts targeting the local DSQ of a remote CPU, defer 1168 * the enqueue so that it's executed when @rq can be unlocked. 1169 */ 1170 if (dsq->id == SCX_DSQ_LOCAL && dsq != &rq->scx.local_dsq) { 1171 unsigned long opss; 1172 1173 opss = atomic_long_read(&p->scx.ops_state) & SCX_OPSS_STATE_MASK; 1174 1175 switch (opss & SCX_OPSS_STATE_MASK) { 1176 case SCX_OPSS_NONE: 1177 break; 1178 case SCX_OPSS_QUEUEING: 1179 /* 1180 * As @p was never passed to the BPF side, _release is 1181 * not strictly necessary. Still do it for consistency. 1182 */ 1183 atomic_long_set_release(&p->scx.ops_state, SCX_OPSS_NONE); 1184 break; 1185 default: 1186 WARN_ONCE(true, "sched_ext: %s[%d] has invalid ops state 0x%lx in direct_dispatch()", 1187 p->comm, p->pid, opss); 1188 atomic_long_set_release(&p->scx.ops_state, SCX_OPSS_NONE); 1189 break; 1190 } 1191 1192 WARN_ON_ONCE(p->scx.dsq || !list_empty(&p->scx.dsq_list.node)); 1193 list_add_tail(&p->scx.dsq_list.node, 1194 &rq->scx.ddsp_deferred_locals); 1195 schedule_deferred(rq); 1196 return; 1197 } 1198 1199 dispatch_enqueue(sch, dsq, p, 1200 p->scx.ddsp_enq_flags | SCX_ENQ_CLEAR_OPSS); 1201 } 1202 1203 static bool scx_rq_online(struct rq *rq) 1204 { 1205 /* 1206 * Test both cpu_active() and %SCX_RQ_ONLINE. %SCX_RQ_ONLINE indicates 1207 * the online state as seen from the BPF scheduler. cpu_active() test 1208 * guarantees that, if this function returns %true, %SCX_RQ_ONLINE will 1209 * stay set until the current scheduling operation is complete even if 1210 * we aren't locking @rq. 1211 */ 1212 return likely((rq->scx.flags & SCX_RQ_ONLINE) && cpu_active(cpu_of(rq))); 1213 } 1214 1215 static void do_enqueue_task(struct rq *rq, struct task_struct *p, u64 enq_flags, 1216 int sticky_cpu) 1217 { 1218 struct scx_sched *sch = scx_root; 1219 struct task_struct **ddsp_taskp; 1220 unsigned long qseq; 1221 1222 WARN_ON_ONCE(!(p->scx.flags & SCX_TASK_QUEUED)); 1223 1224 /* rq migration */ 1225 if (sticky_cpu == cpu_of(rq)) 1226 goto local_norefill; 1227 1228 /* 1229 * If !scx_rq_online(), we already told the BPF scheduler that the CPU 1230 * is offline and are just running the hotplug path. Don't bother the 1231 * BPF scheduler. 1232 */ 1233 if (!scx_rq_online(rq)) 1234 goto local; 1235 1236 if (scx_rq_bypassing(rq)) { 1237 __scx_add_event(sch, SCX_EV_BYPASS_DISPATCH, 1); 1238 goto global; 1239 } 1240 1241 if (p->scx.ddsp_dsq_id != SCX_DSQ_INVALID) 1242 goto direct; 1243 1244 /* see %SCX_OPS_ENQ_EXITING */ 1245 if (!(sch->ops.flags & SCX_OPS_ENQ_EXITING) && 1246 unlikely(p->flags & PF_EXITING)) { 1247 __scx_add_event(sch, SCX_EV_ENQ_SKIP_EXITING, 1); 1248 goto local; 1249 } 1250 1251 /* see %SCX_OPS_ENQ_MIGRATION_DISABLED */ 1252 if (!(sch->ops.flags & SCX_OPS_ENQ_MIGRATION_DISABLED) && 1253 is_migration_disabled(p)) { 1254 __scx_add_event(sch, SCX_EV_ENQ_SKIP_MIGRATION_DISABLED, 1); 1255 goto local; 1256 } 1257 1258 if (unlikely(!SCX_HAS_OP(sch, enqueue))) 1259 goto global; 1260 1261 /* DSQ bypass didn't trigger, enqueue on the BPF scheduler */ 1262 qseq = rq->scx.ops_qseq++ << SCX_OPSS_QSEQ_SHIFT; 1263 1264 WARN_ON_ONCE(atomic_long_read(&p->scx.ops_state) != SCX_OPSS_NONE); 1265 atomic_long_set(&p->scx.ops_state, SCX_OPSS_QUEUEING | qseq); 1266 1267 ddsp_taskp = this_cpu_ptr(&direct_dispatch_task); 1268 WARN_ON_ONCE(*ddsp_taskp); 1269 *ddsp_taskp = p; 1270 1271 SCX_CALL_OP_TASK(sch, SCX_KF_ENQUEUE, enqueue, rq, p, enq_flags); 1272 1273 *ddsp_taskp = NULL; 1274 if (p->scx.ddsp_dsq_id != SCX_DSQ_INVALID) 1275 goto direct; 1276 1277 /* 1278 * If not directly dispatched, QUEUEING isn't clear yet and dispatch or 1279 * dequeue may be waiting. The store_release matches their load_acquire. 1280 */ 1281 atomic_long_set_release(&p->scx.ops_state, SCX_OPSS_QUEUED | qseq); 1282 return; 1283 1284 direct: 1285 direct_dispatch(sch, p, enq_flags); 1286 return; 1287 1288 local: 1289 /* 1290 * For task-ordering, slice refill must be treated as implying the end 1291 * of the current slice. Otherwise, the longer @p stays on the CPU, the 1292 * higher priority it becomes from scx_prio_less()'s POV. 1293 */ 1294 touch_core_sched(rq, p); 1295 refill_task_slice_dfl(sch, p); 1296 local_norefill: 1297 dispatch_enqueue(sch, &rq->scx.local_dsq, p, enq_flags); 1298 return; 1299 1300 global: 1301 touch_core_sched(rq, p); /* see the comment in local: */ 1302 refill_task_slice_dfl(sch, p); 1303 dispatch_enqueue(sch, find_global_dsq(sch, p), p, enq_flags); 1304 } 1305 1306 static bool task_runnable(const struct task_struct *p) 1307 { 1308 return !list_empty(&p->scx.runnable_node); 1309 } 1310 1311 static void set_task_runnable(struct rq *rq, struct task_struct *p) 1312 { 1313 lockdep_assert_rq_held(rq); 1314 1315 if (p->scx.flags & SCX_TASK_RESET_RUNNABLE_AT) { 1316 p->scx.runnable_at = jiffies; 1317 p->scx.flags &= ~SCX_TASK_RESET_RUNNABLE_AT; 1318 } 1319 1320 /* 1321 * list_add_tail() must be used. scx_bypass() depends on tasks being 1322 * appended to the runnable_list. 1323 */ 1324 list_add_tail(&p->scx.runnable_node, &rq->scx.runnable_list); 1325 } 1326 1327 static void clr_task_runnable(struct task_struct *p, bool reset_runnable_at) 1328 { 1329 list_del_init(&p->scx.runnable_node); 1330 if (reset_runnable_at) 1331 p->scx.flags |= SCX_TASK_RESET_RUNNABLE_AT; 1332 } 1333 1334 static void enqueue_task_scx(struct rq *rq, struct task_struct *p, int enq_flags) 1335 { 1336 struct scx_sched *sch = scx_root; 1337 int sticky_cpu = p->scx.sticky_cpu; 1338 1339 if (enq_flags & ENQUEUE_WAKEUP) 1340 rq->scx.flags |= SCX_RQ_IN_WAKEUP; 1341 1342 enq_flags |= rq->scx.extra_enq_flags; 1343 1344 if (sticky_cpu >= 0) 1345 p->scx.sticky_cpu = -1; 1346 1347 /* 1348 * Restoring a running task will be immediately followed by 1349 * set_next_task_scx() which expects the task to not be on the BPF 1350 * scheduler as tasks can only start running through local DSQs. Force 1351 * direct-dispatch into the local DSQ by setting the sticky_cpu. 1352 */ 1353 if (unlikely(enq_flags & ENQUEUE_RESTORE) && task_current(rq, p)) 1354 sticky_cpu = cpu_of(rq); 1355 1356 if (p->scx.flags & SCX_TASK_QUEUED) { 1357 WARN_ON_ONCE(!task_runnable(p)); 1358 goto out; 1359 } 1360 1361 set_task_runnable(rq, p); 1362 p->scx.flags |= SCX_TASK_QUEUED; 1363 rq->scx.nr_running++; 1364 add_nr_running(rq, 1); 1365 1366 if (SCX_HAS_OP(sch, runnable) && !task_on_rq_migrating(p)) 1367 SCX_CALL_OP_TASK(sch, SCX_KF_REST, runnable, rq, p, enq_flags); 1368 1369 if (enq_flags & SCX_ENQ_WAKEUP) 1370 touch_core_sched(rq, p); 1371 1372 do_enqueue_task(rq, p, enq_flags, sticky_cpu); 1373 out: 1374 rq->scx.flags &= ~SCX_RQ_IN_WAKEUP; 1375 1376 if ((enq_flags & SCX_ENQ_CPU_SELECTED) && 1377 unlikely(cpu_of(rq) != p->scx.selected_cpu)) 1378 __scx_add_event(sch, SCX_EV_SELECT_CPU_FALLBACK, 1); 1379 } 1380 1381 static void ops_dequeue(struct rq *rq, struct task_struct *p, u64 deq_flags) 1382 { 1383 struct scx_sched *sch = scx_root; 1384 unsigned long opss; 1385 1386 /* dequeue is always temporary, don't reset runnable_at */ 1387 clr_task_runnable(p, false); 1388 1389 /* acquire ensures that we see the preceding updates on QUEUED */ 1390 opss = atomic_long_read_acquire(&p->scx.ops_state); 1391 1392 switch (opss & SCX_OPSS_STATE_MASK) { 1393 case SCX_OPSS_NONE: 1394 break; 1395 case SCX_OPSS_QUEUEING: 1396 /* 1397 * QUEUEING is started and finished while holding @p's rq lock. 1398 * As we're holding the rq lock now, we shouldn't see QUEUEING. 1399 */ 1400 BUG(); 1401 case SCX_OPSS_QUEUED: 1402 if (SCX_HAS_OP(sch, dequeue)) 1403 SCX_CALL_OP_TASK(sch, SCX_KF_REST, dequeue, rq, 1404 p, deq_flags); 1405 1406 if (atomic_long_try_cmpxchg(&p->scx.ops_state, &opss, 1407 SCX_OPSS_NONE)) 1408 break; 1409 fallthrough; 1410 case SCX_OPSS_DISPATCHING: 1411 /* 1412 * If @p is being dispatched from the BPF scheduler to a DSQ, 1413 * wait for the transfer to complete so that @p doesn't get 1414 * added to its DSQ after dequeueing is complete. 1415 * 1416 * As we're waiting on DISPATCHING with the rq locked, the 1417 * dispatching side shouldn't try to lock the rq while 1418 * DISPATCHING is set. See dispatch_to_local_dsq(). 1419 * 1420 * DISPATCHING shouldn't have qseq set and control can reach 1421 * here with NONE @opss from the above QUEUED case block. 1422 * Explicitly wait on %SCX_OPSS_DISPATCHING instead of @opss. 1423 */ 1424 wait_ops_state(p, SCX_OPSS_DISPATCHING); 1425 BUG_ON(atomic_long_read(&p->scx.ops_state) != SCX_OPSS_NONE); 1426 break; 1427 } 1428 } 1429 1430 static bool dequeue_task_scx(struct rq *rq, struct task_struct *p, int deq_flags) 1431 { 1432 struct scx_sched *sch = scx_root; 1433 1434 if (!(p->scx.flags & SCX_TASK_QUEUED)) { 1435 WARN_ON_ONCE(task_runnable(p)); 1436 return true; 1437 } 1438 1439 ops_dequeue(rq, p, deq_flags); 1440 1441 /* 1442 * A currently running task which is going off @rq first gets dequeued 1443 * and then stops running. As we want running <-> stopping transitions 1444 * to be contained within runnable <-> quiescent transitions, trigger 1445 * ->stopping() early here instead of in put_prev_task_scx(). 1446 * 1447 * @p may go through multiple stopping <-> running transitions between 1448 * here and put_prev_task_scx() if task attribute changes occur while 1449 * balance_scx() leaves @rq unlocked. However, they don't contain any 1450 * information meaningful to the BPF scheduler and can be suppressed by 1451 * skipping the callbacks if the task is !QUEUED. 1452 */ 1453 if (SCX_HAS_OP(sch, stopping) && task_current(rq, p)) { 1454 update_curr_scx(rq); 1455 SCX_CALL_OP_TASK(sch, SCX_KF_REST, stopping, rq, p, false); 1456 } 1457 1458 if (SCX_HAS_OP(sch, quiescent) && !task_on_rq_migrating(p)) 1459 SCX_CALL_OP_TASK(sch, SCX_KF_REST, quiescent, rq, p, deq_flags); 1460 1461 if (deq_flags & SCX_DEQ_SLEEP) 1462 p->scx.flags |= SCX_TASK_DEQD_FOR_SLEEP; 1463 else 1464 p->scx.flags &= ~SCX_TASK_DEQD_FOR_SLEEP; 1465 1466 p->scx.flags &= ~SCX_TASK_QUEUED; 1467 rq->scx.nr_running--; 1468 sub_nr_running(rq, 1); 1469 1470 dispatch_dequeue(rq, p); 1471 return true; 1472 } 1473 1474 static void yield_task_scx(struct rq *rq) 1475 { 1476 struct scx_sched *sch = scx_root; 1477 struct task_struct *p = rq->curr; 1478 1479 if (SCX_HAS_OP(sch, yield)) 1480 SCX_CALL_OP_2TASKS_RET(sch, SCX_KF_REST, yield, rq, p, NULL); 1481 else 1482 p->scx.slice = 0; 1483 } 1484 1485 static bool yield_to_task_scx(struct rq *rq, struct task_struct *to) 1486 { 1487 struct scx_sched *sch = scx_root; 1488 struct task_struct *from = rq->curr; 1489 1490 if (SCX_HAS_OP(sch, yield)) 1491 return SCX_CALL_OP_2TASKS_RET(sch, SCX_KF_REST, yield, rq, 1492 from, to); 1493 else 1494 return false; 1495 } 1496 1497 static void move_local_task_to_local_dsq(struct task_struct *p, u64 enq_flags, 1498 struct scx_dispatch_q *src_dsq, 1499 struct rq *dst_rq) 1500 { 1501 struct scx_dispatch_q *dst_dsq = &dst_rq->scx.local_dsq; 1502 1503 /* @dsq is locked and @p is on @dst_rq */ 1504 lockdep_assert_held(&src_dsq->lock); 1505 lockdep_assert_rq_held(dst_rq); 1506 1507 WARN_ON_ONCE(p->scx.holding_cpu >= 0); 1508 1509 if (enq_flags & (SCX_ENQ_HEAD | SCX_ENQ_PREEMPT)) 1510 list_add(&p->scx.dsq_list.node, &dst_dsq->list); 1511 else 1512 list_add_tail(&p->scx.dsq_list.node, &dst_dsq->list); 1513 1514 dsq_mod_nr(dst_dsq, 1); 1515 p->scx.dsq = dst_dsq; 1516 } 1517 1518 /** 1519 * move_remote_task_to_local_dsq - Move a task from a foreign rq to a local DSQ 1520 * @p: task to move 1521 * @enq_flags: %SCX_ENQ_* 1522 * @src_rq: rq to move the task from, locked on entry, released on return 1523 * @dst_rq: rq to move the task into, locked on return 1524 * 1525 * Move @p which is currently on @src_rq to @dst_rq's local DSQ. 1526 */ 1527 static void move_remote_task_to_local_dsq(struct task_struct *p, u64 enq_flags, 1528 struct rq *src_rq, struct rq *dst_rq) 1529 { 1530 lockdep_assert_rq_held(src_rq); 1531 1532 /* the following marks @p MIGRATING which excludes dequeue */ 1533 deactivate_task(src_rq, p, 0); 1534 set_task_cpu(p, cpu_of(dst_rq)); 1535 p->scx.sticky_cpu = cpu_of(dst_rq); 1536 1537 raw_spin_rq_unlock(src_rq); 1538 raw_spin_rq_lock(dst_rq); 1539 1540 /* 1541 * We want to pass scx-specific enq_flags but activate_task() will 1542 * truncate the upper 32 bit. As we own @rq, we can pass them through 1543 * @rq->scx.extra_enq_flags instead. 1544 */ 1545 WARN_ON_ONCE(!cpumask_test_cpu(cpu_of(dst_rq), p->cpus_ptr)); 1546 WARN_ON_ONCE(dst_rq->scx.extra_enq_flags); 1547 dst_rq->scx.extra_enq_flags = enq_flags; 1548 activate_task(dst_rq, p, 0); 1549 dst_rq->scx.extra_enq_flags = 0; 1550 } 1551 1552 /* 1553 * Similar to kernel/sched/core.c::is_cpu_allowed(). However, there are two 1554 * differences: 1555 * 1556 * - is_cpu_allowed() asks "Can this task run on this CPU?" while 1557 * task_can_run_on_remote_rq() asks "Can the BPF scheduler migrate the task to 1558 * this CPU?". 1559 * 1560 * While migration is disabled, is_cpu_allowed() has to say "yes" as the task 1561 * must be allowed to finish on the CPU that it's currently on regardless of 1562 * the CPU state. However, task_can_run_on_remote_rq() must say "no" as the 1563 * BPF scheduler shouldn't attempt to migrate a task which has migration 1564 * disabled. 1565 * 1566 * - The BPF scheduler is bypassed while the rq is offline and we can always say 1567 * no to the BPF scheduler initiated migrations while offline. 1568 * 1569 * The caller must ensure that @p and @rq are on different CPUs. 1570 */ 1571 static bool task_can_run_on_remote_rq(struct scx_sched *sch, 1572 struct task_struct *p, struct rq *rq, 1573 bool enforce) 1574 { 1575 int cpu = cpu_of(rq); 1576 1577 WARN_ON_ONCE(task_cpu(p) == cpu); 1578 1579 /* 1580 * If @p has migration disabled, @p->cpus_ptr is updated to contain only 1581 * the pinned CPU in migrate_disable_switch() while @p is being switched 1582 * out. However, put_prev_task_scx() is called before @p->cpus_ptr is 1583 * updated and thus another CPU may see @p on a DSQ inbetween leading to 1584 * @p passing the below task_allowed_on_cpu() check while migration is 1585 * disabled. 1586 * 1587 * Test the migration disabled state first as the race window is narrow 1588 * and the BPF scheduler failing to check migration disabled state can 1589 * easily be masked if task_allowed_on_cpu() is done first. 1590 */ 1591 if (unlikely(is_migration_disabled(p))) { 1592 if (enforce) 1593 scx_error(sch, "SCX_DSQ_LOCAL[_ON] cannot move migration disabled %s[%d] from CPU %d to %d", 1594 p->comm, p->pid, task_cpu(p), cpu); 1595 return false; 1596 } 1597 1598 /* 1599 * We don't require the BPF scheduler to avoid dispatching to offline 1600 * CPUs mostly for convenience but also because CPUs can go offline 1601 * between scx_bpf_dsq_insert() calls and here. Trigger error iff the 1602 * picked CPU is outside the allowed mask. 1603 */ 1604 if (!task_allowed_on_cpu(p, cpu)) { 1605 if (enforce) 1606 scx_error(sch, "SCX_DSQ_LOCAL[_ON] target CPU %d not allowed for %s[%d]", 1607 cpu, p->comm, p->pid); 1608 return false; 1609 } 1610 1611 if (!scx_rq_online(rq)) { 1612 if (enforce) 1613 __scx_add_event(sch, SCX_EV_DISPATCH_LOCAL_DSQ_OFFLINE, 1); 1614 return false; 1615 } 1616 1617 return true; 1618 } 1619 1620 /** 1621 * unlink_dsq_and_lock_src_rq() - Unlink task from its DSQ and lock its task_rq 1622 * @p: target task 1623 * @dsq: locked DSQ @p is currently on 1624 * @src_rq: rq @p is currently on, stable with @dsq locked 1625 * 1626 * Called with @dsq locked but no rq's locked. We want to move @p to a different 1627 * DSQ, including any local DSQ, but are not locking @src_rq. Locking @src_rq is 1628 * required when transferring into a local DSQ. Even when transferring into a 1629 * non-local DSQ, it's better to use the same mechanism to protect against 1630 * dequeues and maintain the invariant that @p->scx.dsq can only change while 1631 * @src_rq is locked, which e.g. scx_dump_task() depends on. 1632 * 1633 * We want to grab @src_rq but that can deadlock if we try while locking @dsq, 1634 * so we want to unlink @p from @dsq, drop its lock and then lock @src_rq. As 1635 * this may race with dequeue, which can't drop the rq lock or fail, do a little 1636 * dancing from our side. 1637 * 1638 * @p->scx.holding_cpu is set to this CPU before @dsq is unlocked. If @p gets 1639 * dequeued after we unlock @dsq but before locking @src_rq, the holding_cpu 1640 * would be cleared to -1. While other cpus may have updated it to different 1641 * values afterwards, as this operation can't be preempted or recurse, the 1642 * holding_cpu can never become this CPU again before we're done. Thus, we can 1643 * tell whether we lost to dequeue by testing whether the holding_cpu still 1644 * points to this CPU. See dispatch_dequeue() for the counterpart. 1645 * 1646 * On return, @dsq is unlocked and @src_rq is locked. Returns %true if @p is 1647 * still valid. %false if lost to dequeue. 1648 */ 1649 static bool unlink_dsq_and_lock_src_rq(struct task_struct *p, 1650 struct scx_dispatch_q *dsq, 1651 struct rq *src_rq) 1652 { 1653 s32 cpu = raw_smp_processor_id(); 1654 1655 lockdep_assert_held(&dsq->lock); 1656 1657 WARN_ON_ONCE(p->scx.holding_cpu >= 0); 1658 task_unlink_from_dsq(p, dsq); 1659 p->scx.holding_cpu = cpu; 1660 1661 raw_spin_unlock(&dsq->lock); 1662 raw_spin_rq_lock(src_rq); 1663 1664 /* task_rq couldn't have changed if we're still the holding cpu */ 1665 return likely(p->scx.holding_cpu == cpu) && 1666 !WARN_ON_ONCE(src_rq != task_rq(p)); 1667 } 1668 1669 static bool consume_remote_task(struct rq *this_rq, struct task_struct *p, 1670 struct scx_dispatch_q *dsq, struct rq *src_rq) 1671 { 1672 raw_spin_rq_unlock(this_rq); 1673 1674 if (unlink_dsq_and_lock_src_rq(p, dsq, src_rq)) { 1675 move_remote_task_to_local_dsq(p, 0, src_rq, this_rq); 1676 return true; 1677 } else { 1678 raw_spin_rq_unlock(src_rq); 1679 raw_spin_rq_lock(this_rq); 1680 return false; 1681 } 1682 } 1683 1684 /** 1685 * move_task_between_dsqs() - Move a task from one DSQ to another 1686 * @sch: scx_sched being operated on 1687 * @p: target task 1688 * @enq_flags: %SCX_ENQ_* 1689 * @src_dsq: DSQ @p is currently on, must not be a local DSQ 1690 * @dst_dsq: DSQ @p is being moved to, can be any DSQ 1691 * 1692 * Must be called with @p's task_rq and @src_dsq locked. If @dst_dsq is a local 1693 * DSQ and @p is on a different CPU, @p will be migrated and thus its task_rq 1694 * will change. As @p's task_rq is locked, this function doesn't need to use the 1695 * holding_cpu mechanism. 1696 * 1697 * On return, @src_dsq is unlocked and only @p's new task_rq, which is the 1698 * return value, is locked. 1699 */ 1700 static struct rq *move_task_between_dsqs(struct scx_sched *sch, 1701 struct task_struct *p, u64 enq_flags, 1702 struct scx_dispatch_q *src_dsq, 1703 struct scx_dispatch_q *dst_dsq) 1704 { 1705 struct rq *src_rq = task_rq(p), *dst_rq; 1706 1707 BUG_ON(src_dsq->id == SCX_DSQ_LOCAL); 1708 lockdep_assert_held(&src_dsq->lock); 1709 lockdep_assert_rq_held(src_rq); 1710 1711 if (dst_dsq->id == SCX_DSQ_LOCAL) { 1712 dst_rq = container_of(dst_dsq, struct rq, scx.local_dsq); 1713 if (src_rq != dst_rq && 1714 unlikely(!task_can_run_on_remote_rq(sch, p, dst_rq, true))) { 1715 dst_dsq = find_global_dsq(sch, p); 1716 dst_rq = src_rq; 1717 } 1718 } else { 1719 /* no need to migrate if destination is a non-local DSQ */ 1720 dst_rq = src_rq; 1721 } 1722 1723 /* 1724 * Move @p into $dst_dsq. If $dst_dsq is the local DSQ of a different 1725 * CPU, @p will be migrated. 1726 */ 1727 if (dst_dsq->id == SCX_DSQ_LOCAL) { 1728 /* @p is going from a non-local DSQ to a local DSQ */ 1729 if (src_rq == dst_rq) { 1730 task_unlink_from_dsq(p, src_dsq); 1731 move_local_task_to_local_dsq(p, enq_flags, 1732 src_dsq, dst_rq); 1733 raw_spin_unlock(&src_dsq->lock); 1734 } else { 1735 raw_spin_unlock(&src_dsq->lock); 1736 move_remote_task_to_local_dsq(p, enq_flags, 1737 src_rq, dst_rq); 1738 } 1739 } else { 1740 /* 1741 * @p is going from a non-local DSQ to a non-local DSQ. As 1742 * $src_dsq is already locked, do an abbreviated dequeue. 1743 */ 1744 task_unlink_from_dsq(p, src_dsq); 1745 p->scx.dsq = NULL; 1746 raw_spin_unlock(&src_dsq->lock); 1747 1748 dispatch_enqueue(sch, dst_dsq, p, enq_flags); 1749 } 1750 1751 return dst_rq; 1752 } 1753 1754 /* 1755 * A poorly behaving BPF scheduler can live-lock the system by e.g. incessantly 1756 * banging on the same DSQ on a large NUMA system to the point where switching 1757 * to the bypass mode can take a long time. Inject artificial delays while the 1758 * bypass mode is switching to guarantee timely completion. 1759 */ 1760 static void scx_breather(struct rq *rq) 1761 { 1762 u64 until; 1763 1764 lockdep_assert_rq_held(rq); 1765 1766 if (likely(!atomic_read(&scx_breather_depth))) 1767 return; 1768 1769 raw_spin_rq_unlock(rq); 1770 1771 until = ktime_get_ns() + NSEC_PER_MSEC; 1772 1773 do { 1774 int cnt = 1024; 1775 while (atomic_read(&scx_breather_depth) && --cnt) 1776 cpu_relax(); 1777 } while (atomic_read(&scx_breather_depth) && 1778 time_before64(ktime_get_ns(), until)); 1779 1780 raw_spin_rq_lock(rq); 1781 } 1782 1783 static bool consume_dispatch_q(struct scx_sched *sch, struct rq *rq, 1784 struct scx_dispatch_q *dsq) 1785 { 1786 struct task_struct *p; 1787 retry: 1788 /* 1789 * This retry loop can repeatedly race against scx_bypass() dequeueing 1790 * tasks from @dsq trying to put the system into the bypass mode. On 1791 * some multi-socket machines (e.g. 2x Intel 8480c), this can live-lock 1792 * the machine into soft lockups. Give a breather. 1793 */ 1794 scx_breather(rq); 1795 1796 /* 1797 * The caller can't expect to successfully consume a task if the task's 1798 * addition to @dsq isn't guaranteed to be visible somehow. Test 1799 * @dsq->list without locking and skip if it seems empty. 1800 */ 1801 if (list_empty(&dsq->list)) 1802 return false; 1803 1804 raw_spin_lock(&dsq->lock); 1805 1806 nldsq_for_each_task(p, dsq) { 1807 struct rq *task_rq = task_rq(p); 1808 1809 if (rq == task_rq) { 1810 task_unlink_from_dsq(p, dsq); 1811 move_local_task_to_local_dsq(p, 0, dsq, rq); 1812 raw_spin_unlock(&dsq->lock); 1813 return true; 1814 } 1815 1816 if (task_can_run_on_remote_rq(sch, p, rq, false)) { 1817 if (likely(consume_remote_task(rq, p, dsq, task_rq))) 1818 return true; 1819 goto retry; 1820 } 1821 } 1822 1823 raw_spin_unlock(&dsq->lock); 1824 return false; 1825 } 1826 1827 static bool consume_global_dsq(struct scx_sched *sch, struct rq *rq) 1828 { 1829 int node = cpu_to_node(cpu_of(rq)); 1830 1831 return consume_dispatch_q(sch, rq, sch->global_dsqs[node]); 1832 } 1833 1834 /** 1835 * dispatch_to_local_dsq - Dispatch a task to a local dsq 1836 * @sch: scx_sched being operated on 1837 * @rq: current rq which is locked 1838 * @dst_dsq: destination DSQ 1839 * @p: task to dispatch 1840 * @enq_flags: %SCX_ENQ_* 1841 * 1842 * We're holding @rq lock and want to dispatch @p to @dst_dsq which is a local 1843 * DSQ. This function performs all the synchronization dancing needed because 1844 * local DSQs are protected with rq locks. 1845 * 1846 * The caller must have exclusive ownership of @p (e.g. through 1847 * %SCX_OPSS_DISPATCHING). 1848 */ 1849 static void dispatch_to_local_dsq(struct scx_sched *sch, struct rq *rq, 1850 struct scx_dispatch_q *dst_dsq, 1851 struct task_struct *p, u64 enq_flags) 1852 { 1853 struct rq *src_rq = task_rq(p); 1854 struct rq *dst_rq = container_of(dst_dsq, struct rq, scx.local_dsq); 1855 struct rq *locked_rq = rq; 1856 1857 /* 1858 * We're synchronized against dequeue through DISPATCHING. As @p can't 1859 * be dequeued, its task_rq and cpus_allowed are stable too. 1860 * 1861 * If dispatching to @rq that @p is already on, no lock dancing needed. 1862 */ 1863 if (rq == src_rq && rq == dst_rq) { 1864 dispatch_enqueue(sch, dst_dsq, p, 1865 enq_flags | SCX_ENQ_CLEAR_OPSS); 1866 return; 1867 } 1868 1869 if (src_rq != dst_rq && 1870 unlikely(!task_can_run_on_remote_rq(sch, p, dst_rq, true))) { 1871 dispatch_enqueue(sch, find_global_dsq(sch, p), p, 1872 enq_flags | SCX_ENQ_CLEAR_OPSS); 1873 return; 1874 } 1875 1876 /* 1877 * @p is on a possibly remote @src_rq which we need to lock to move the 1878 * task. If dequeue is in progress, it'd be locking @src_rq and waiting 1879 * on DISPATCHING, so we can't grab @src_rq lock while holding 1880 * DISPATCHING. 1881 * 1882 * As DISPATCHING guarantees that @p is wholly ours, we can pretend that 1883 * we're moving from a DSQ and use the same mechanism - mark the task 1884 * under transfer with holding_cpu, release DISPATCHING and then follow 1885 * the same protocol. See unlink_dsq_and_lock_src_rq(). 1886 */ 1887 p->scx.holding_cpu = raw_smp_processor_id(); 1888 1889 /* store_release ensures that dequeue sees the above */ 1890 atomic_long_set_release(&p->scx.ops_state, SCX_OPSS_NONE); 1891 1892 /* switch to @src_rq lock */ 1893 if (locked_rq != src_rq) { 1894 raw_spin_rq_unlock(locked_rq); 1895 locked_rq = src_rq; 1896 raw_spin_rq_lock(src_rq); 1897 } 1898 1899 /* task_rq couldn't have changed if we're still the holding cpu */ 1900 if (likely(p->scx.holding_cpu == raw_smp_processor_id()) && 1901 !WARN_ON_ONCE(src_rq != task_rq(p))) { 1902 /* 1903 * If @p is staying on the same rq, there's no need to go 1904 * through the full deactivate/activate cycle. Optimize by 1905 * abbreviating move_remote_task_to_local_dsq(). 1906 */ 1907 if (src_rq == dst_rq) { 1908 p->scx.holding_cpu = -1; 1909 dispatch_enqueue(sch, &dst_rq->scx.local_dsq, p, 1910 enq_flags); 1911 } else { 1912 move_remote_task_to_local_dsq(p, enq_flags, 1913 src_rq, dst_rq); 1914 /* task has been moved to dst_rq, which is now locked */ 1915 locked_rq = dst_rq; 1916 } 1917 1918 /* if the destination CPU is idle, wake it up */ 1919 if (sched_class_above(p->sched_class, dst_rq->curr->sched_class)) 1920 resched_curr(dst_rq); 1921 } 1922 1923 /* switch back to @rq lock */ 1924 if (locked_rq != rq) { 1925 raw_spin_rq_unlock(locked_rq); 1926 raw_spin_rq_lock(rq); 1927 } 1928 } 1929 1930 /** 1931 * finish_dispatch - Asynchronously finish dispatching a task 1932 * @rq: current rq which is locked 1933 * @p: task to finish dispatching 1934 * @qseq_at_dispatch: qseq when @p started getting dispatched 1935 * @dsq_id: destination DSQ ID 1936 * @enq_flags: %SCX_ENQ_* 1937 * 1938 * Dispatching to local DSQs may need to wait for queueing to complete or 1939 * require rq lock dancing. As we don't wanna do either while inside 1940 * ops.dispatch() to avoid locking order inversion, we split dispatching into 1941 * two parts. scx_bpf_dsq_insert() which is called by ops.dispatch() records the 1942 * task and its qseq. Once ops.dispatch() returns, this function is called to 1943 * finish up. 1944 * 1945 * There is no guarantee that @p is still valid for dispatching or even that it 1946 * was valid in the first place. Make sure that the task is still owned by the 1947 * BPF scheduler and claim the ownership before dispatching. 1948 */ 1949 static void finish_dispatch(struct scx_sched *sch, struct rq *rq, 1950 struct task_struct *p, 1951 unsigned long qseq_at_dispatch, 1952 u64 dsq_id, u64 enq_flags) 1953 { 1954 struct scx_dispatch_q *dsq; 1955 unsigned long opss; 1956 1957 touch_core_sched_dispatch(rq, p); 1958 retry: 1959 /* 1960 * No need for _acquire here. @p is accessed only after a successful 1961 * try_cmpxchg to DISPATCHING. 1962 */ 1963 opss = atomic_long_read(&p->scx.ops_state); 1964 1965 switch (opss & SCX_OPSS_STATE_MASK) { 1966 case SCX_OPSS_DISPATCHING: 1967 case SCX_OPSS_NONE: 1968 /* someone else already got to it */ 1969 return; 1970 case SCX_OPSS_QUEUED: 1971 /* 1972 * If qseq doesn't match, @p has gone through at least one 1973 * dispatch/dequeue and re-enqueue cycle between 1974 * scx_bpf_dsq_insert() and here and we have no claim on it. 1975 */ 1976 if ((opss & SCX_OPSS_QSEQ_MASK) != qseq_at_dispatch) 1977 return; 1978 1979 /* 1980 * While we know @p is accessible, we don't yet have a claim on 1981 * it - the BPF scheduler is allowed to dispatch tasks 1982 * spuriously and there can be a racing dequeue attempt. Let's 1983 * claim @p by atomically transitioning it from QUEUED to 1984 * DISPATCHING. 1985 */ 1986 if (likely(atomic_long_try_cmpxchg(&p->scx.ops_state, &opss, 1987 SCX_OPSS_DISPATCHING))) 1988 break; 1989 goto retry; 1990 case SCX_OPSS_QUEUEING: 1991 /* 1992 * do_enqueue_task() is in the process of transferring the task 1993 * to the BPF scheduler while holding @p's rq lock. As we aren't 1994 * holding any kernel or BPF resource that the enqueue path may 1995 * depend upon, it's safe to wait. 1996 */ 1997 wait_ops_state(p, opss); 1998 goto retry; 1999 } 2000 2001 BUG_ON(!(p->scx.flags & SCX_TASK_QUEUED)); 2002 2003 dsq = find_dsq_for_dispatch(sch, this_rq(), dsq_id, p); 2004 2005 if (dsq->id == SCX_DSQ_LOCAL) 2006 dispatch_to_local_dsq(sch, rq, dsq, p, enq_flags); 2007 else 2008 dispatch_enqueue(sch, dsq, p, enq_flags | SCX_ENQ_CLEAR_OPSS); 2009 } 2010 2011 static void flush_dispatch_buf(struct scx_sched *sch, struct rq *rq) 2012 { 2013 struct scx_dsp_ctx *dspc = this_cpu_ptr(scx_dsp_ctx); 2014 u32 u; 2015 2016 for (u = 0; u < dspc->cursor; u++) { 2017 struct scx_dsp_buf_ent *ent = &dspc->buf[u]; 2018 2019 finish_dispatch(sch, rq, ent->task, ent->qseq, ent->dsq_id, 2020 ent->enq_flags); 2021 } 2022 2023 dspc->nr_tasks += dspc->cursor; 2024 dspc->cursor = 0; 2025 } 2026 2027 static inline void maybe_queue_balance_callback(struct rq *rq) 2028 { 2029 lockdep_assert_rq_held(rq); 2030 2031 if (!(rq->scx.flags & SCX_RQ_BAL_CB_PENDING)) 2032 return; 2033 2034 queue_balance_callback(rq, &rq->scx.deferred_bal_cb, 2035 deferred_bal_cb_workfn); 2036 2037 rq->scx.flags &= ~SCX_RQ_BAL_CB_PENDING; 2038 } 2039 2040 static int balance_one(struct rq *rq, struct task_struct *prev) 2041 { 2042 struct scx_sched *sch = scx_root; 2043 struct scx_dsp_ctx *dspc = this_cpu_ptr(scx_dsp_ctx); 2044 bool prev_on_scx = prev->sched_class == &ext_sched_class; 2045 bool prev_on_rq = prev->scx.flags & SCX_TASK_QUEUED; 2046 int nr_loops = SCX_DSP_MAX_LOOPS; 2047 2048 lockdep_assert_rq_held(rq); 2049 rq->scx.flags |= SCX_RQ_IN_BALANCE; 2050 rq->scx.flags &= ~(SCX_RQ_BAL_PENDING | SCX_RQ_BAL_KEEP); 2051 2052 if ((sch->ops.flags & SCX_OPS_HAS_CPU_PREEMPT) && 2053 unlikely(rq->scx.cpu_released)) { 2054 /* 2055 * If the previous sched_class for the current CPU was not SCX, 2056 * notify the BPF scheduler that it again has control of the 2057 * core. This callback complements ->cpu_release(), which is 2058 * emitted in switch_class(). 2059 */ 2060 if (SCX_HAS_OP(sch, cpu_acquire)) 2061 SCX_CALL_OP(sch, SCX_KF_REST, cpu_acquire, rq, 2062 cpu_of(rq), NULL); 2063 rq->scx.cpu_released = false; 2064 } 2065 2066 if (prev_on_scx) { 2067 update_curr_scx(rq); 2068 2069 /* 2070 * If @prev is runnable & has slice left, it has priority and 2071 * fetching more just increases latency for the fetched tasks. 2072 * Tell pick_task_scx() to keep running @prev. If the BPF 2073 * scheduler wants to handle this explicitly, it should 2074 * implement ->cpu_release(). 2075 * 2076 * See scx_disable_workfn() for the explanation on the bypassing 2077 * test. 2078 */ 2079 if (prev_on_rq && prev->scx.slice && !scx_rq_bypassing(rq)) { 2080 rq->scx.flags |= SCX_RQ_BAL_KEEP; 2081 goto has_tasks; 2082 } 2083 } 2084 2085 /* if there already are tasks to run, nothing to do */ 2086 if (rq->scx.local_dsq.nr) 2087 goto has_tasks; 2088 2089 if (consume_global_dsq(sch, rq)) 2090 goto has_tasks; 2091 2092 if (unlikely(!SCX_HAS_OP(sch, dispatch)) || 2093 scx_rq_bypassing(rq) || !scx_rq_online(rq)) 2094 goto no_tasks; 2095 2096 dspc->rq = rq; 2097 2098 /* 2099 * The dispatch loop. Because flush_dispatch_buf() may drop the rq lock, 2100 * the local DSQ might still end up empty after a successful 2101 * ops.dispatch(). If the local DSQ is empty even after ops.dispatch() 2102 * produced some tasks, retry. The BPF scheduler may depend on this 2103 * looping behavior to simplify its implementation. 2104 */ 2105 do { 2106 dspc->nr_tasks = 0; 2107 2108 SCX_CALL_OP(sch, SCX_KF_DISPATCH, dispatch, rq, 2109 cpu_of(rq), prev_on_scx ? prev : NULL); 2110 2111 flush_dispatch_buf(sch, rq); 2112 2113 if (prev_on_rq && prev->scx.slice) { 2114 rq->scx.flags |= SCX_RQ_BAL_KEEP; 2115 goto has_tasks; 2116 } 2117 if (rq->scx.local_dsq.nr) 2118 goto has_tasks; 2119 if (consume_global_dsq(sch, rq)) 2120 goto has_tasks; 2121 2122 /* 2123 * ops.dispatch() can trap us in this loop by repeatedly 2124 * dispatching ineligible tasks. Break out once in a while to 2125 * allow the watchdog to run. As IRQ can't be enabled in 2126 * balance(), we want to complete this scheduling cycle and then 2127 * start a new one. IOW, we want to call resched_curr() on the 2128 * next, most likely idle, task, not the current one. Use 2129 * scx_kick_cpu() for deferred kicking. 2130 */ 2131 if (unlikely(!--nr_loops)) { 2132 scx_kick_cpu(sch, cpu_of(rq), 0); 2133 break; 2134 } 2135 } while (dspc->nr_tasks); 2136 2137 no_tasks: 2138 /* 2139 * Didn't find another task to run. Keep running @prev unless 2140 * %SCX_OPS_ENQ_LAST is in effect. 2141 */ 2142 if (prev_on_rq && 2143 (!(sch->ops.flags & SCX_OPS_ENQ_LAST) || scx_rq_bypassing(rq))) { 2144 rq->scx.flags |= SCX_RQ_BAL_KEEP; 2145 __scx_add_event(sch, SCX_EV_DISPATCH_KEEP_LAST, 1); 2146 goto has_tasks; 2147 } 2148 rq->scx.flags &= ~SCX_RQ_IN_BALANCE; 2149 return false; 2150 2151 has_tasks: 2152 rq->scx.flags &= ~SCX_RQ_IN_BALANCE; 2153 return true; 2154 } 2155 2156 static int balance_scx(struct rq *rq, struct task_struct *prev, 2157 struct rq_flags *rf) 2158 { 2159 int ret; 2160 2161 rq_unpin_lock(rq, rf); 2162 2163 ret = balance_one(rq, prev); 2164 2165 #ifdef CONFIG_SCHED_SMT 2166 /* 2167 * When core-sched is enabled, this ops.balance() call will be followed 2168 * by pick_task_scx() on this CPU and the SMT siblings. Balance the 2169 * siblings too. 2170 */ 2171 if (sched_core_enabled(rq)) { 2172 const struct cpumask *smt_mask = cpu_smt_mask(cpu_of(rq)); 2173 int scpu; 2174 2175 for_each_cpu_andnot(scpu, smt_mask, cpumask_of(cpu_of(rq))) { 2176 struct rq *srq = cpu_rq(scpu); 2177 struct task_struct *sprev = srq->curr; 2178 2179 WARN_ON_ONCE(__rq_lockp(rq) != __rq_lockp(srq)); 2180 update_rq_clock(srq); 2181 balance_one(srq, sprev); 2182 } 2183 } 2184 #endif 2185 rq_repin_lock(rq, rf); 2186 2187 maybe_queue_balance_callback(rq); 2188 2189 return ret; 2190 } 2191 2192 static void process_ddsp_deferred_locals(struct rq *rq) 2193 { 2194 struct task_struct *p; 2195 2196 lockdep_assert_rq_held(rq); 2197 2198 /* 2199 * Now that @rq can be unlocked, execute the deferred enqueueing of 2200 * tasks directly dispatched to the local DSQs of other CPUs. See 2201 * direct_dispatch(). Keep popping from the head instead of using 2202 * list_for_each_entry_safe() as dispatch_local_dsq() may unlock @rq 2203 * temporarily. 2204 */ 2205 while ((p = list_first_entry_or_null(&rq->scx.ddsp_deferred_locals, 2206 struct task_struct, scx.dsq_list.node))) { 2207 struct scx_sched *sch = scx_root; 2208 struct scx_dispatch_q *dsq; 2209 2210 list_del_init(&p->scx.dsq_list.node); 2211 2212 dsq = find_dsq_for_dispatch(sch, rq, p->scx.ddsp_dsq_id, p); 2213 if (!WARN_ON_ONCE(dsq->id != SCX_DSQ_LOCAL)) 2214 dispatch_to_local_dsq(sch, rq, dsq, p, 2215 p->scx.ddsp_enq_flags); 2216 } 2217 } 2218 2219 static void set_next_task_scx(struct rq *rq, struct task_struct *p, bool first) 2220 { 2221 struct scx_sched *sch = scx_root; 2222 2223 if (p->scx.flags & SCX_TASK_QUEUED) { 2224 /* 2225 * Core-sched might decide to execute @p before it is 2226 * dispatched. Call ops_dequeue() to notify the BPF scheduler. 2227 */ 2228 ops_dequeue(rq, p, SCX_DEQ_CORE_SCHED_EXEC); 2229 dispatch_dequeue(rq, p); 2230 } 2231 2232 p->se.exec_start = rq_clock_task(rq); 2233 2234 /* see dequeue_task_scx() on why we skip when !QUEUED */ 2235 if (SCX_HAS_OP(sch, running) && (p->scx.flags & SCX_TASK_QUEUED)) 2236 SCX_CALL_OP_TASK(sch, SCX_KF_REST, running, rq, p); 2237 2238 clr_task_runnable(p, true); 2239 2240 /* 2241 * @p is getting newly scheduled or got kicked after someone updated its 2242 * slice. Refresh whether tick can be stopped. See scx_can_stop_tick(). 2243 */ 2244 if ((p->scx.slice == SCX_SLICE_INF) != 2245 (bool)(rq->scx.flags & SCX_RQ_CAN_STOP_TICK)) { 2246 if (p->scx.slice == SCX_SLICE_INF) 2247 rq->scx.flags |= SCX_RQ_CAN_STOP_TICK; 2248 else 2249 rq->scx.flags &= ~SCX_RQ_CAN_STOP_TICK; 2250 2251 sched_update_tick_dependency(rq); 2252 2253 /* 2254 * For now, let's refresh the load_avgs just when transitioning 2255 * in and out of nohz. In the future, we might want to add a 2256 * mechanism which calls the following periodically on 2257 * tick-stopped CPUs. 2258 */ 2259 update_other_load_avgs(rq); 2260 } 2261 } 2262 2263 static enum scx_cpu_preempt_reason 2264 preempt_reason_from_class(const struct sched_class *class) 2265 { 2266 if (class == &stop_sched_class) 2267 return SCX_CPU_PREEMPT_STOP; 2268 if (class == &dl_sched_class) 2269 return SCX_CPU_PREEMPT_DL; 2270 if (class == &rt_sched_class) 2271 return SCX_CPU_PREEMPT_RT; 2272 return SCX_CPU_PREEMPT_UNKNOWN; 2273 } 2274 2275 static void switch_class(struct rq *rq, struct task_struct *next) 2276 { 2277 struct scx_sched *sch = scx_root; 2278 const struct sched_class *next_class = next->sched_class; 2279 2280 /* 2281 * Pairs with the smp_load_acquire() issued by a CPU in 2282 * kick_cpus_irq_workfn() who is waiting for this CPU to perform a 2283 * resched. 2284 */ 2285 smp_store_release(&rq->scx.pnt_seq, rq->scx.pnt_seq + 1); 2286 if (!(sch->ops.flags & SCX_OPS_HAS_CPU_PREEMPT)) 2287 return; 2288 2289 /* 2290 * The callback is conceptually meant to convey that the CPU is no 2291 * longer under the control of SCX. Therefore, don't invoke the callback 2292 * if the next class is below SCX (in which case the BPF scheduler has 2293 * actively decided not to schedule any tasks on the CPU). 2294 */ 2295 if (sched_class_above(&ext_sched_class, next_class)) 2296 return; 2297 2298 /* 2299 * At this point we know that SCX was preempted by a higher priority 2300 * sched_class, so invoke the ->cpu_release() callback if we have not 2301 * done so already. We only send the callback once between SCX being 2302 * preempted, and it regaining control of the CPU. 2303 * 2304 * ->cpu_release() complements ->cpu_acquire(), which is emitted the 2305 * next time that balance_scx() is invoked. 2306 */ 2307 if (!rq->scx.cpu_released) { 2308 if (SCX_HAS_OP(sch, cpu_release)) { 2309 struct scx_cpu_release_args args = { 2310 .reason = preempt_reason_from_class(next_class), 2311 .task = next, 2312 }; 2313 2314 SCX_CALL_OP(sch, SCX_KF_CPU_RELEASE, cpu_release, rq, 2315 cpu_of(rq), &args); 2316 } 2317 rq->scx.cpu_released = true; 2318 } 2319 } 2320 2321 static void put_prev_task_scx(struct rq *rq, struct task_struct *p, 2322 struct task_struct *next) 2323 { 2324 struct scx_sched *sch = scx_root; 2325 update_curr_scx(rq); 2326 2327 /* see dequeue_task_scx() on why we skip when !QUEUED */ 2328 if (SCX_HAS_OP(sch, stopping) && (p->scx.flags & SCX_TASK_QUEUED)) 2329 SCX_CALL_OP_TASK(sch, SCX_KF_REST, stopping, rq, p, true); 2330 2331 if (p->scx.flags & SCX_TASK_QUEUED) { 2332 set_task_runnable(rq, p); 2333 2334 /* 2335 * If @p has slice left and is being put, @p is getting 2336 * preempted by a higher priority scheduler class or core-sched 2337 * forcing a different task. Leave it at the head of the local 2338 * DSQ. 2339 */ 2340 if (p->scx.slice && !scx_rq_bypassing(rq)) { 2341 dispatch_enqueue(sch, &rq->scx.local_dsq, p, 2342 SCX_ENQ_HEAD); 2343 goto switch_class; 2344 } 2345 2346 /* 2347 * If @p is runnable but we're about to enter a lower 2348 * sched_class, %SCX_OPS_ENQ_LAST must be set. Tell 2349 * ops.enqueue() that @p is the only one available for this cpu, 2350 * which should trigger an explicit follow-up scheduling event. 2351 */ 2352 if (sched_class_above(&ext_sched_class, next->sched_class)) { 2353 WARN_ON_ONCE(!(sch->ops.flags & SCX_OPS_ENQ_LAST)); 2354 do_enqueue_task(rq, p, SCX_ENQ_LAST, -1); 2355 } else { 2356 do_enqueue_task(rq, p, 0, -1); 2357 } 2358 } 2359 2360 switch_class: 2361 if (next && next->sched_class != &ext_sched_class) 2362 switch_class(rq, next); 2363 } 2364 2365 static struct task_struct *first_local_task(struct rq *rq) 2366 { 2367 return list_first_entry_or_null(&rq->scx.local_dsq.list, 2368 struct task_struct, scx.dsq_list.node); 2369 } 2370 2371 static struct task_struct *pick_task_scx(struct rq *rq) 2372 { 2373 struct task_struct *prev = rq->curr; 2374 struct task_struct *p; 2375 bool keep_prev = rq->scx.flags & SCX_RQ_BAL_KEEP; 2376 bool kick_idle = false; 2377 2378 /* 2379 * WORKAROUND: 2380 * 2381 * %SCX_RQ_BAL_KEEP should be set iff $prev is on SCX as it must just 2382 * have gone through balance_scx(). Unfortunately, there currently is a 2383 * bug where fair could say yes on balance() but no on pick_task(), 2384 * which then ends up calling pick_task_scx() without preceding 2385 * balance_scx(). 2386 * 2387 * Keep running @prev if possible and avoid stalling from entering idle 2388 * without balancing. 2389 * 2390 * Once fair is fixed, remove the workaround and trigger WARN_ON_ONCE() 2391 * if pick_task_scx() is called without preceding balance_scx(). 2392 */ 2393 if (unlikely(rq->scx.flags & SCX_RQ_BAL_PENDING)) { 2394 if (prev->scx.flags & SCX_TASK_QUEUED) { 2395 keep_prev = true; 2396 } else { 2397 keep_prev = false; 2398 kick_idle = true; 2399 } 2400 } else if (unlikely(keep_prev && 2401 prev->sched_class != &ext_sched_class)) { 2402 /* 2403 * Can happen while enabling as SCX_RQ_BAL_PENDING assertion is 2404 * conditional on scx_enabled() and may have been skipped. 2405 */ 2406 WARN_ON_ONCE(scx_enable_state() == SCX_ENABLED); 2407 keep_prev = false; 2408 } 2409 2410 /* 2411 * If balance_scx() is telling us to keep running @prev, replenish slice 2412 * if necessary and keep running @prev. Otherwise, pop the first one 2413 * from the local DSQ. 2414 */ 2415 if (keep_prev) { 2416 p = prev; 2417 if (!p->scx.slice) 2418 refill_task_slice_dfl(rcu_dereference_sched(scx_root), p); 2419 } else { 2420 p = first_local_task(rq); 2421 if (!p) { 2422 if (kick_idle) 2423 scx_kick_cpu(rcu_dereference_sched(scx_root), 2424 cpu_of(rq), SCX_KICK_IDLE); 2425 return NULL; 2426 } 2427 2428 if (unlikely(!p->scx.slice)) { 2429 struct scx_sched *sch = rcu_dereference_sched(scx_root); 2430 2431 if (!scx_rq_bypassing(rq) && !sch->warned_zero_slice) { 2432 printk_deferred(KERN_WARNING "sched_ext: %s[%d] has zero slice in %s()\n", 2433 p->comm, p->pid, __func__); 2434 sch->warned_zero_slice = true; 2435 } 2436 refill_task_slice_dfl(sch, p); 2437 } 2438 } 2439 2440 return p; 2441 } 2442 2443 #ifdef CONFIG_SCHED_CORE 2444 /** 2445 * scx_prio_less - Task ordering for core-sched 2446 * @a: task A 2447 * @b: task B 2448 * @in_fi: in forced idle state 2449 * 2450 * Core-sched is implemented as an additional scheduling layer on top of the 2451 * usual sched_class'es and needs to find out the expected task ordering. For 2452 * SCX, core-sched calls this function to interrogate the task ordering. 2453 * 2454 * Unless overridden by ops.core_sched_before(), @p->scx.core_sched_at is used 2455 * to implement the default task ordering. The older the timestamp, the higher 2456 * priority the task - the global FIFO ordering matching the default scheduling 2457 * behavior. 2458 * 2459 * When ops.core_sched_before() is enabled, @p->scx.core_sched_at is used to 2460 * implement FIFO ordering within each local DSQ. See pick_task_scx(). 2461 */ 2462 bool scx_prio_less(const struct task_struct *a, const struct task_struct *b, 2463 bool in_fi) 2464 { 2465 struct scx_sched *sch = scx_root; 2466 2467 /* 2468 * The const qualifiers are dropped from task_struct pointers when 2469 * calling ops.core_sched_before(). Accesses are controlled by the 2470 * verifier. 2471 */ 2472 if (SCX_HAS_OP(sch, core_sched_before) && 2473 !scx_rq_bypassing(task_rq(a))) 2474 return SCX_CALL_OP_2TASKS_RET(sch, SCX_KF_REST, core_sched_before, 2475 NULL, 2476 (struct task_struct *)a, 2477 (struct task_struct *)b); 2478 else 2479 return time_after64(a->scx.core_sched_at, b->scx.core_sched_at); 2480 } 2481 #endif /* CONFIG_SCHED_CORE */ 2482 2483 static int select_task_rq_scx(struct task_struct *p, int prev_cpu, int wake_flags) 2484 { 2485 struct scx_sched *sch = scx_root; 2486 bool rq_bypass; 2487 2488 /* 2489 * sched_exec() calls with %WF_EXEC when @p is about to exec(2) as it 2490 * can be a good migration opportunity with low cache and memory 2491 * footprint. Returning a CPU different than @prev_cpu triggers 2492 * immediate rq migration. However, for SCX, as the current rq 2493 * association doesn't dictate where the task is going to run, this 2494 * doesn't fit well. If necessary, we can later add a dedicated method 2495 * which can decide to preempt self to force it through the regular 2496 * scheduling path. 2497 */ 2498 if (unlikely(wake_flags & WF_EXEC)) 2499 return prev_cpu; 2500 2501 rq_bypass = scx_rq_bypassing(task_rq(p)); 2502 if (likely(SCX_HAS_OP(sch, select_cpu)) && !rq_bypass) { 2503 s32 cpu; 2504 struct task_struct **ddsp_taskp; 2505 2506 ddsp_taskp = this_cpu_ptr(&direct_dispatch_task); 2507 WARN_ON_ONCE(*ddsp_taskp); 2508 *ddsp_taskp = p; 2509 2510 cpu = SCX_CALL_OP_TASK_RET(sch, 2511 SCX_KF_ENQUEUE | SCX_KF_SELECT_CPU, 2512 select_cpu, NULL, p, prev_cpu, 2513 wake_flags); 2514 p->scx.selected_cpu = cpu; 2515 *ddsp_taskp = NULL; 2516 if (ops_cpu_valid(sch, cpu, "from ops.select_cpu()")) 2517 return cpu; 2518 else 2519 return prev_cpu; 2520 } else { 2521 s32 cpu; 2522 2523 cpu = scx_select_cpu_dfl(p, prev_cpu, wake_flags, NULL, 0); 2524 if (cpu >= 0) { 2525 refill_task_slice_dfl(sch, p); 2526 p->scx.ddsp_dsq_id = SCX_DSQ_LOCAL; 2527 } else { 2528 cpu = prev_cpu; 2529 } 2530 p->scx.selected_cpu = cpu; 2531 2532 if (rq_bypass) 2533 __scx_add_event(sch, SCX_EV_BYPASS_DISPATCH, 1); 2534 return cpu; 2535 } 2536 } 2537 2538 static void task_woken_scx(struct rq *rq, struct task_struct *p) 2539 { 2540 run_deferred(rq); 2541 } 2542 2543 static void set_cpus_allowed_scx(struct task_struct *p, 2544 struct affinity_context *ac) 2545 { 2546 struct scx_sched *sch = scx_root; 2547 2548 set_cpus_allowed_common(p, ac); 2549 2550 /* 2551 * The effective cpumask is stored in @p->cpus_ptr which may temporarily 2552 * differ from the configured one in @p->cpus_mask. Always tell the bpf 2553 * scheduler the effective one. 2554 * 2555 * Fine-grained memory write control is enforced by BPF making the const 2556 * designation pointless. Cast it away when calling the operation. 2557 */ 2558 if (SCX_HAS_OP(sch, set_cpumask)) 2559 SCX_CALL_OP_TASK(sch, SCX_KF_REST, set_cpumask, NULL, 2560 p, (struct cpumask *)p->cpus_ptr); 2561 } 2562 2563 static void handle_hotplug(struct rq *rq, bool online) 2564 { 2565 struct scx_sched *sch = scx_root; 2566 int cpu = cpu_of(rq); 2567 2568 atomic_long_inc(&scx_hotplug_seq); 2569 2570 /* 2571 * scx_root updates are protected by cpus_read_lock() and will stay 2572 * stable here. Note that we can't depend on scx_enabled() test as the 2573 * hotplug ops need to be enabled before __scx_enabled is set. 2574 */ 2575 if (unlikely(!sch)) 2576 return; 2577 2578 if (scx_enabled()) 2579 scx_idle_update_selcpu_topology(&sch->ops); 2580 2581 if (online && SCX_HAS_OP(sch, cpu_online)) 2582 SCX_CALL_OP(sch, SCX_KF_UNLOCKED, cpu_online, NULL, cpu); 2583 else if (!online && SCX_HAS_OP(sch, cpu_offline)) 2584 SCX_CALL_OP(sch, SCX_KF_UNLOCKED, cpu_offline, NULL, cpu); 2585 else 2586 scx_exit(sch, SCX_EXIT_UNREG_KERN, 2587 SCX_ECODE_ACT_RESTART | SCX_ECODE_RSN_HOTPLUG, 2588 "cpu %d going %s, exiting scheduler", cpu, 2589 online ? "online" : "offline"); 2590 } 2591 2592 void scx_rq_activate(struct rq *rq) 2593 { 2594 handle_hotplug(rq, true); 2595 } 2596 2597 void scx_rq_deactivate(struct rq *rq) 2598 { 2599 handle_hotplug(rq, false); 2600 } 2601 2602 static void rq_online_scx(struct rq *rq) 2603 { 2604 rq->scx.flags |= SCX_RQ_ONLINE; 2605 } 2606 2607 static void rq_offline_scx(struct rq *rq) 2608 { 2609 rq->scx.flags &= ~SCX_RQ_ONLINE; 2610 } 2611 2612 2613 static bool check_rq_for_timeouts(struct rq *rq) 2614 { 2615 struct scx_sched *sch; 2616 struct task_struct *p; 2617 struct rq_flags rf; 2618 bool timed_out = false; 2619 2620 rq_lock_irqsave(rq, &rf); 2621 sch = rcu_dereference_bh(scx_root); 2622 if (unlikely(!sch)) 2623 goto out_unlock; 2624 2625 list_for_each_entry(p, &rq->scx.runnable_list, scx.runnable_node) { 2626 unsigned long last_runnable = p->scx.runnable_at; 2627 2628 if (unlikely(time_after(jiffies, 2629 last_runnable + scx_watchdog_timeout))) { 2630 u32 dur_ms = jiffies_to_msecs(jiffies - last_runnable); 2631 2632 scx_exit(sch, SCX_EXIT_ERROR_STALL, 0, 2633 "%s[%d] failed to run for %u.%03us", 2634 p->comm, p->pid, dur_ms / 1000, dur_ms % 1000); 2635 timed_out = true; 2636 break; 2637 } 2638 } 2639 out_unlock: 2640 rq_unlock_irqrestore(rq, &rf); 2641 return timed_out; 2642 } 2643 2644 static void scx_watchdog_workfn(struct work_struct *work) 2645 { 2646 int cpu; 2647 2648 WRITE_ONCE(scx_watchdog_timestamp, jiffies); 2649 2650 for_each_online_cpu(cpu) { 2651 if (unlikely(check_rq_for_timeouts(cpu_rq(cpu)))) 2652 break; 2653 2654 cond_resched(); 2655 } 2656 queue_delayed_work(system_unbound_wq, to_delayed_work(work), 2657 scx_watchdog_timeout / 2); 2658 } 2659 2660 void scx_tick(struct rq *rq) 2661 { 2662 struct scx_sched *sch; 2663 unsigned long last_check; 2664 2665 if (!scx_enabled()) 2666 return; 2667 2668 sch = rcu_dereference_bh(scx_root); 2669 if (unlikely(!sch)) 2670 return; 2671 2672 last_check = READ_ONCE(scx_watchdog_timestamp); 2673 if (unlikely(time_after(jiffies, 2674 last_check + READ_ONCE(scx_watchdog_timeout)))) { 2675 u32 dur_ms = jiffies_to_msecs(jiffies - last_check); 2676 2677 scx_exit(sch, SCX_EXIT_ERROR_STALL, 0, 2678 "watchdog failed to check in for %u.%03us", 2679 dur_ms / 1000, dur_ms % 1000); 2680 } 2681 2682 update_other_load_avgs(rq); 2683 } 2684 2685 static void task_tick_scx(struct rq *rq, struct task_struct *curr, int queued) 2686 { 2687 struct scx_sched *sch = scx_root; 2688 2689 update_curr_scx(rq); 2690 2691 /* 2692 * While disabling, always resched and refresh core-sched timestamp as 2693 * we can't trust the slice management or ops.core_sched_before(). 2694 */ 2695 if (scx_rq_bypassing(rq)) { 2696 curr->scx.slice = 0; 2697 touch_core_sched(rq, curr); 2698 } else if (SCX_HAS_OP(sch, tick)) { 2699 SCX_CALL_OP_TASK(sch, SCX_KF_REST, tick, rq, curr); 2700 } 2701 2702 if (!curr->scx.slice) 2703 resched_curr(rq); 2704 } 2705 2706 #ifdef CONFIG_EXT_GROUP_SCHED 2707 static struct cgroup *tg_cgrp(struct task_group *tg) 2708 { 2709 /* 2710 * If CGROUP_SCHED is disabled, @tg is NULL. If @tg is an autogroup, 2711 * @tg->css.cgroup is NULL. In both cases, @tg can be treated as the 2712 * root cgroup. 2713 */ 2714 if (tg && tg->css.cgroup) 2715 return tg->css.cgroup; 2716 else 2717 return &cgrp_dfl_root.cgrp; 2718 } 2719 2720 #define SCX_INIT_TASK_ARGS_CGROUP(tg) .cgroup = tg_cgrp(tg), 2721 2722 #else /* CONFIG_EXT_GROUP_SCHED */ 2723 2724 #define SCX_INIT_TASK_ARGS_CGROUP(tg) 2725 2726 #endif /* CONFIG_EXT_GROUP_SCHED */ 2727 2728 static enum scx_task_state scx_get_task_state(const struct task_struct *p) 2729 { 2730 return (p->scx.flags & SCX_TASK_STATE_MASK) >> SCX_TASK_STATE_SHIFT; 2731 } 2732 2733 static void scx_set_task_state(struct task_struct *p, enum scx_task_state state) 2734 { 2735 enum scx_task_state prev_state = scx_get_task_state(p); 2736 bool warn = false; 2737 2738 BUILD_BUG_ON(SCX_TASK_NR_STATES > (1 << SCX_TASK_STATE_BITS)); 2739 2740 switch (state) { 2741 case SCX_TASK_NONE: 2742 break; 2743 case SCX_TASK_INIT: 2744 warn = prev_state != SCX_TASK_NONE; 2745 break; 2746 case SCX_TASK_READY: 2747 warn = prev_state == SCX_TASK_NONE; 2748 break; 2749 case SCX_TASK_ENABLED: 2750 warn = prev_state != SCX_TASK_READY; 2751 break; 2752 default: 2753 warn = true; 2754 return; 2755 } 2756 2757 WARN_ONCE(warn, "sched_ext: Invalid task state transition %d -> %d for %s[%d]", 2758 prev_state, state, p->comm, p->pid); 2759 2760 p->scx.flags &= ~SCX_TASK_STATE_MASK; 2761 p->scx.flags |= state << SCX_TASK_STATE_SHIFT; 2762 } 2763 2764 static int scx_init_task(struct task_struct *p, struct task_group *tg, bool fork) 2765 { 2766 struct scx_sched *sch = scx_root; 2767 int ret; 2768 2769 p->scx.disallow = false; 2770 2771 if (SCX_HAS_OP(sch, init_task)) { 2772 struct scx_init_task_args args = { 2773 SCX_INIT_TASK_ARGS_CGROUP(tg) 2774 .fork = fork, 2775 }; 2776 2777 ret = SCX_CALL_OP_RET(sch, SCX_KF_UNLOCKED, init_task, NULL, 2778 p, &args); 2779 if (unlikely(ret)) { 2780 ret = ops_sanitize_err(sch, "init_task", ret); 2781 return ret; 2782 } 2783 } 2784 2785 scx_set_task_state(p, SCX_TASK_INIT); 2786 2787 if (p->scx.disallow) { 2788 if (!fork) { 2789 struct rq *rq; 2790 struct rq_flags rf; 2791 2792 rq = task_rq_lock(p, &rf); 2793 2794 /* 2795 * We're in the load path and @p->policy will be applied 2796 * right after. Reverting @p->policy here and rejecting 2797 * %SCHED_EXT transitions from scx_check_setscheduler() 2798 * guarantees that if ops.init_task() sets @p->disallow, 2799 * @p can never be in SCX. 2800 */ 2801 if (p->policy == SCHED_EXT) { 2802 p->policy = SCHED_NORMAL; 2803 atomic_long_inc(&scx_nr_rejected); 2804 } 2805 2806 task_rq_unlock(rq, p, &rf); 2807 } else if (p->policy == SCHED_EXT) { 2808 scx_error(sch, "ops.init_task() set task->scx.disallow for %s[%d] during fork", 2809 p->comm, p->pid); 2810 } 2811 } 2812 2813 p->scx.flags |= SCX_TASK_RESET_RUNNABLE_AT; 2814 return 0; 2815 } 2816 2817 static void scx_enable_task(struct task_struct *p) 2818 { 2819 struct scx_sched *sch = scx_root; 2820 struct rq *rq = task_rq(p); 2821 u32 weight; 2822 2823 lockdep_assert_rq_held(rq); 2824 2825 /* 2826 * Set the weight before calling ops.enable() so that the scheduler 2827 * doesn't see a stale value if they inspect the task struct. 2828 */ 2829 if (task_has_idle_policy(p)) 2830 weight = WEIGHT_IDLEPRIO; 2831 else 2832 weight = sched_prio_to_weight[p->static_prio - MAX_RT_PRIO]; 2833 2834 p->scx.weight = sched_weight_to_cgroup(weight); 2835 2836 if (SCX_HAS_OP(sch, enable)) 2837 SCX_CALL_OP_TASK(sch, SCX_KF_REST, enable, rq, p); 2838 scx_set_task_state(p, SCX_TASK_ENABLED); 2839 2840 if (SCX_HAS_OP(sch, set_weight)) 2841 SCX_CALL_OP_TASK(sch, SCX_KF_REST, set_weight, rq, 2842 p, p->scx.weight); 2843 } 2844 2845 static void scx_disable_task(struct task_struct *p) 2846 { 2847 struct scx_sched *sch = scx_root; 2848 struct rq *rq = task_rq(p); 2849 2850 lockdep_assert_rq_held(rq); 2851 WARN_ON_ONCE(scx_get_task_state(p) != SCX_TASK_ENABLED); 2852 2853 if (SCX_HAS_OP(sch, disable)) 2854 SCX_CALL_OP_TASK(sch, SCX_KF_REST, disable, rq, p); 2855 scx_set_task_state(p, SCX_TASK_READY); 2856 } 2857 2858 static void scx_exit_task(struct task_struct *p) 2859 { 2860 struct scx_sched *sch = scx_root; 2861 struct scx_exit_task_args args = { 2862 .cancelled = false, 2863 }; 2864 2865 lockdep_assert_rq_held(task_rq(p)); 2866 2867 switch (scx_get_task_state(p)) { 2868 case SCX_TASK_NONE: 2869 return; 2870 case SCX_TASK_INIT: 2871 args.cancelled = true; 2872 break; 2873 case SCX_TASK_READY: 2874 break; 2875 case SCX_TASK_ENABLED: 2876 scx_disable_task(p); 2877 break; 2878 default: 2879 WARN_ON_ONCE(true); 2880 return; 2881 } 2882 2883 if (SCX_HAS_OP(sch, exit_task)) 2884 SCX_CALL_OP_TASK(sch, SCX_KF_REST, exit_task, task_rq(p), 2885 p, &args); 2886 scx_set_task_state(p, SCX_TASK_NONE); 2887 } 2888 2889 void init_scx_entity(struct sched_ext_entity *scx) 2890 { 2891 memset(scx, 0, sizeof(*scx)); 2892 INIT_LIST_HEAD(&scx->dsq_list.node); 2893 RB_CLEAR_NODE(&scx->dsq_priq); 2894 scx->sticky_cpu = -1; 2895 scx->holding_cpu = -1; 2896 INIT_LIST_HEAD(&scx->runnable_node); 2897 scx->runnable_at = jiffies; 2898 scx->ddsp_dsq_id = SCX_DSQ_INVALID; 2899 scx->slice = SCX_SLICE_DFL; 2900 } 2901 2902 void scx_pre_fork(struct task_struct *p) 2903 { 2904 /* 2905 * BPF scheduler enable/disable paths want to be able to iterate and 2906 * update all tasks which can become complex when racing forks. As 2907 * enable/disable are very cold paths, let's use a percpu_rwsem to 2908 * exclude forks. 2909 */ 2910 percpu_down_read(&scx_fork_rwsem); 2911 } 2912 2913 int scx_fork(struct task_struct *p) 2914 { 2915 percpu_rwsem_assert_held(&scx_fork_rwsem); 2916 2917 if (scx_init_task_enabled) 2918 return scx_init_task(p, task_group(p), true); 2919 else 2920 return 0; 2921 } 2922 2923 void scx_post_fork(struct task_struct *p) 2924 { 2925 if (scx_init_task_enabled) { 2926 scx_set_task_state(p, SCX_TASK_READY); 2927 2928 /* 2929 * Enable the task immediately if it's running on sched_ext. 2930 * Otherwise, it'll be enabled in switching_to_scx() if and 2931 * when it's ever configured to run with a SCHED_EXT policy. 2932 */ 2933 if (p->sched_class == &ext_sched_class) { 2934 struct rq_flags rf; 2935 struct rq *rq; 2936 2937 rq = task_rq_lock(p, &rf); 2938 scx_enable_task(p); 2939 task_rq_unlock(rq, p, &rf); 2940 } 2941 } 2942 2943 spin_lock_irq(&scx_tasks_lock); 2944 list_add_tail(&p->scx.tasks_node, &scx_tasks); 2945 spin_unlock_irq(&scx_tasks_lock); 2946 2947 percpu_up_read(&scx_fork_rwsem); 2948 } 2949 2950 void scx_cancel_fork(struct task_struct *p) 2951 { 2952 if (scx_enabled()) { 2953 struct rq *rq; 2954 struct rq_flags rf; 2955 2956 rq = task_rq_lock(p, &rf); 2957 WARN_ON_ONCE(scx_get_task_state(p) >= SCX_TASK_READY); 2958 scx_exit_task(p); 2959 task_rq_unlock(rq, p, &rf); 2960 } 2961 2962 percpu_up_read(&scx_fork_rwsem); 2963 } 2964 2965 void sched_ext_free(struct task_struct *p) 2966 { 2967 unsigned long flags; 2968 2969 spin_lock_irqsave(&scx_tasks_lock, flags); 2970 list_del_init(&p->scx.tasks_node); 2971 spin_unlock_irqrestore(&scx_tasks_lock, flags); 2972 2973 /* 2974 * @p is off scx_tasks and wholly ours. scx_enable()'s READY -> ENABLED 2975 * transitions can't race us. Disable ops for @p. 2976 */ 2977 if (scx_get_task_state(p) != SCX_TASK_NONE) { 2978 struct rq_flags rf; 2979 struct rq *rq; 2980 2981 rq = task_rq_lock(p, &rf); 2982 scx_exit_task(p); 2983 task_rq_unlock(rq, p, &rf); 2984 } 2985 } 2986 2987 static void reweight_task_scx(struct rq *rq, struct task_struct *p, 2988 const struct load_weight *lw) 2989 { 2990 struct scx_sched *sch = scx_root; 2991 2992 lockdep_assert_rq_held(task_rq(p)); 2993 2994 p->scx.weight = sched_weight_to_cgroup(scale_load_down(lw->weight)); 2995 if (SCX_HAS_OP(sch, set_weight)) 2996 SCX_CALL_OP_TASK(sch, SCX_KF_REST, set_weight, rq, 2997 p, p->scx.weight); 2998 } 2999 3000 static void prio_changed_scx(struct rq *rq, struct task_struct *p, int oldprio) 3001 { 3002 } 3003 3004 static void switching_to_scx(struct rq *rq, struct task_struct *p) 3005 { 3006 struct scx_sched *sch = scx_root; 3007 3008 scx_enable_task(p); 3009 3010 /* 3011 * set_cpus_allowed_scx() is not called while @p is associated with a 3012 * different scheduler class. Keep the BPF scheduler up-to-date. 3013 */ 3014 if (SCX_HAS_OP(sch, set_cpumask)) 3015 SCX_CALL_OP_TASK(sch, SCX_KF_REST, set_cpumask, rq, 3016 p, (struct cpumask *)p->cpus_ptr); 3017 } 3018 3019 static void switched_from_scx(struct rq *rq, struct task_struct *p) 3020 { 3021 scx_disable_task(p); 3022 } 3023 3024 static void wakeup_preempt_scx(struct rq *rq, struct task_struct *p,int wake_flags) {} 3025 static void switched_to_scx(struct rq *rq, struct task_struct *p) {} 3026 3027 int scx_check_setscheduler(struct task_struct *p, int policy) 3028 { 3029 lockdep_assert_rq_held(task_rq(p)); 3030 3031 /* if disallow, reject transitioning into SCX */ 3032 if (scx_enabled() && READ_ONCE(p->scx.disallow) && 3033 p->policy != policy && policy == SCHED_EXT) 3034 return -EACCES; 3035 3036 return 0; 3037 } 3038 3039 #ifdef CONFIG_NO_HZ_FULL 3040 bool scx_can_stop_tick(struct rq *rq) 3041 { 3042 struct task_struct *p = rq->curr; 3043 3044 if (scx_rq_bypassing(rq)) 3045 return false; 3046 3047 if (p->sched_class != &ext_sched_class) 3048 return true; 3049 3050 /* 3051 * @rq can dispatch from different DSQs, so we can't tell whether it 3052 * needs the tick or not by looking at nr_running. Allow stopping ticks 3053 * iff the BPF scheduler indicated so. See set_next_task_scx(). 3054 */ 3055 return rq->scx.flags & SCX_RQ_CAN_STOP_TICK; 3056 } 3057 #endif 3058 3059 #ifdef CONFIG_EXT_GROUP_SCHED 3060 3061 DEFINE_STATIC_PERCPU_RWSEM(scx_cgroup_ops_rwsem); 3062 static bool scx_cgroup_enabled; 3063 3064 void scx_tg_init(struct task_group *tg) 3065 { 3066 tg->scx.weight = CGROUP_WEIGHT_DFL; 3067 tg->scx.bw_period_us = default_bw_period_us(); 3068 tg->scx.bw_quota_us = RUNTIME_INF; 3069 } 3070 3071 int scx_tg_online(struct task_group *tg) 3072 { 3073 struct scx_sched *sch = scx_root; 3074 int ret = 0; 3075 3076 WARN_ON_ONCE(tg->scx.flags & (SCX_TG_ONLINE | SCX_TG_INITED)); 3077 3078 if (scx_cgroup_enabled) { 3079 if (SCX_HAS_OP(sch, cgroup_init)) { 3080 struct scx_cgroup_init_args args = 3081 { .weight = tg->scx.weight, 3082 .bw_period_us = tg->scx.bw_period_us, 3083 .bw_quota_us = tg->scx.bw_quota_us, 3084 .bw_burst_us = tg->scx.bw_burst_us }; 3085 3086 ret = SCX_CALL_OP_RET(sch, SCX_KF_UNLOCKED, cgroup_init, 3087 NULL, tg->css.cgroup, &args); 3088 if (ret) 3089 ret = ops_sanitize_err(sch, "cgroup_init", ret); 3090 } 3091 if (ret == 0) 3092 tg->scx.flags |= SCX_TG_ONLINE | SCX_TG_INITED; 3093 } else { 3094 tg->scx.flags |= SCX_TG_ONLINE; 3095 } 3096 3097 return ret; 3098 } 3099 3100 void scx_tg_offline(struct task_group *tg) 3101 { 3102 struct scx_sched *sch = scx_root; 3103 3104 WARN_ON_ONCE(!(tg->scx.flags & SCX_TG_ONLINE)); 3105 3106 if (scx_cgroup_enabled && SCX_HAS_OP(sch, cgroup_exit) && 3107 (tg->scx.flags & SCX_TG_INITED)) 3108 SCX_CALL_OP(sch, SCX_KF_UNLOCKED, cgroup_exit, NULL, 3109 tg->css.cgroup); 3110 tg->scx.flags &= ~(SCX_TG_ONLINE | SCX_TG_INITED); 3111 } 3112 3113 int scx_cgroup_can_attach(struct cgroup_taskset *tset) 3114 { 3115 struct scx_sched *sch = scx_root; 3116 struct cgroup_subsys_state *css; 3117 struct task_struct *p; 3118 int ret; 3119 3120 if (!scx_cgroup_enabled) 3121 return 0; 3122 3123 cgroup_taskset_for_each(p, css, tset) { 3124 struct cgroup *from = tg_cgrp(task_group(p)); 3125 struct cgroup *to = tg_cgrp(css_tg(css)); 3126 3127 WARN_ON_ONCE(p->scx.cgrp_moving_from); 3128 3129 /* 3130 * sched_move_task() omits identity migrations. Let's match the 3131 * behavior so that ops.cgroup_prep_move() and ops.cgroup_move() 3132 * always match one-to-one. 3133 */ 3134 if (from == to) 3135 continue; 3136 3137 if (SCX_HAS_OP(sch, cgroup_prep_move)) { 3138 ret = SCX_CALL_OP_RET(sch, SCX_KF_UNLOCKED, 3139 cgroup_prep_move, NULL, 3140 p, from, css->cgroup); 3141 if (ret) 3142 goto err; 3143 } 3144 3145 p->scx.cgrp_moving_from = from; 3146 } 3147 3148 return 0; 3149 3150 err: 3151 cgroup_taskset_for_each(p, css, tset) { 3152 if (SCX_HAS_OP(sch, cgroup_cancel_move) && 3153 p->scx.cgrp_moving_from) 3154 SCX_CALL_OP(sch, SCX_KF_UNLOCKED, cgroup_cancel_move, NULL, 3155 p, p->scx.cgrp_moving_from, css->cgroup); 3156 p->scx.cgrp_moving_from = NULL; 3157 } 3158 3159 return ops_sanitize_err(sch, "cgroup_prep_move", ret); 3160 } 3161 3162 void scx_cgroup_move_task(struct task_struct *p) 3163 { 3164 struct scx_sched *sch = scx_root; 3165 3166 if (!scx_cgroup_enabled) 3167 return; 3168 3169 /* 3170 * @p must have ops.cgroup_prep_move() called on it and thus 3171 * cgrp_moving_from set. 3172 */ 3173 if (SCX_HAS_OP(sch, cgroup_move) && 3174 !WARN_ON_ONCE(!p->scx.cgrp_moving_from)) 3175 SCX_CALL_OP_TASK(sch, SCX_KF_UNLOCKED, cgroup_move, NULL, 3176 p, p->scx.cgrp_moving_from, 3177 tg_cgrp(task_group(p))); 3178 p->scx.cgrp_moving_from = NULL; 3179 } 3180 3181 void scx_cgroup_cancel_attach(struct cgroup_taskset *tset) 3182 { 3183 struct scx_sched *sch = scx_root; 3184 struct cgroup_subsys_state *css; 3185 struct task_struct *p; 3186 3187 if (!scx_cgroup_enabled) 3188 return; 3189 3190 cgroup_taskset_for_each(p, css, tset) { 3191 if (SCX_HAS_OP(sch, cgroup_cancel_move) && 3192 p->scx.cgrp_moving_from) 3193 SCX_CALL_OP(sch, SCX_KF_UNLOCKED, cgroup_cancel_move, NULL, 3194 p, p->scx.cgrp_moving_from, css->cgroup); 3195 p->scx.cgrp_moving_from = NULL; 3196 } 3197 } 3198 3199 void scx_group_set_weight(struct task_group *tg, unsigned long weight) 3200 { 3201 struct scx_sched *sch = scx_root; 3202 3203 percpu_down_read(&scx_cgroup_ops_rwsem); 3204 3205 if (scx_cgroup_enabled && SCX_HAS_OP(sch, cgroup_set_weight) && 3206 tg->scx.weight != weight) 3207 SCX_CALL_OP(sch, SCX_KF_UNLOCKED, cgroup_set_weight, NULL, 3208 tg_cgrp(tg), weight); 3209 3210 tg->scx.weight = weight; 3211 3212 percpu_up_read(&scx_cgroup_ops_rwsem); 3213 } 3214 3215 void scx_group_set_idle(struct task_group *tg, bool idle) 3216 { 3217 /* TODO: Implement ops->cgroup_set_idle() */ 3218 } 3219 3220 void scx_group_set_bandwidth(struct task_group *tg, 3221 u64 period_us, u64 quota_us, u64 burst_us) 3222 { 3223 struct scx_sched *sch = scx_root; 3224 3225 percpu_down_read(&scx_cgroup_ops_rwsem); 3226 3227 if (scx_cgroup_enabled && SCX_HAS_OP(sch, cgroup_set_bandwidth) && 3228 (tg->scx.bw_period_us != period_us || 3229 tg->scx.bw_quota_us != quota_us || 3230 tg->scx.bw_burst_us != burst_us)) 3231 SCX_CALL_OP(sch, SCX_KF_UNLOCKED, cgroup_set_bandwidth, NULL, 3232 tg_cgrp(tg), period_us, quota_us, burst_us); 3233 3234 tg->scx.bw_period_us = period_us; 3235 tg->scx.bw_quota_us = quota_us; 3236 tg->scx.bw_burst_us = burst_us; 3237 3238 percpu_up_read(&scx_cgroup_ops_rwsem); 3239 } 3240 3241 static void scx_cgroup_lock(void) 3242 { 3243 percpu_down_write(&scx_cgroup_ops_rwsem); 3244 cgroup_lock(); 3245 } 3246 3247 static void scx_cgroup_unlock(void) 3248 { 3249 cgroup_unlock(); 3250 percpu_up_write(&scx_cgroup_ops_rwsem); 3251 } 3252 3253 #else /* CONFIG_EXT_GROUP_SCHED */ 3254 3255 static void scx_cgroup_lock(void) {} 3256 static void scx_cgroup_unlock(void) {} 3257 3258 #endif /* CONFIG_EXT_GROUP_SCHED */ 3259 3260 /* 3261 * Omitted operations: 3262 * 3263 * - wakeup_preempt: NOOP as it isn't useful in the wakeup path because the task 3264 * isn't tied to the CPU at that point. Preemption is implemented by resetting 3265 * the victim task's slice to 0 and triggering reschedule on the target CPU. 3266 * 3267 * - migrate_task_rq: Unnecessary as task to cpu mapping is transient. 3268 * 3269 * - task_fork/dead: We need fork/dead notifications for all tasks regardless of 3270 * their current sched_class. Call them directly from sched core instead. 3271 */ 3272 DEFINE_SCHED_CLASS(ext) = { 3273 .enqueue_task = enqueue_task_scx, 3274 .dequeue_task = dequeue_task_scx, 3275 .yield_task = yield_task_scx, 3276 .yield_to_task = yield_to_task_scx, 3277 3278 .wakeup_preempt = wakeup_preempt_scx, 3279 3280 .balance = balance_scx, 3281 .pick_task = pick_task_scx, 3282 3283 .put_prev_task = put_prev_task_scx, 3284 .set_next_task = set_next_task_scx, 3285 3286 .select_task_rq = select_task_rq_scx, 3287 .task_woken = task_woken_scx, 3288 .set_cpus_allowed = set_cpus_allowed_scx, 3289 3290 .rq_online = rq_online_scx, 3291 .rq_offline = rq_offline_scx, 3292 3293 .task_tick = task_tick_scx, 3294 3295 .switching_to = switching_to_scx, 3296 .switched_from = switched_from_scx, 3297 .switched_to = switched_to_scx, 3298 .reweight_task = reweight_task_scx, 3299 .prio_changed = prio_changed_scx, 3300 3301 .update_curr = update_curr_scx, 3302 3303 #ifdef CONFIG_UCLAMP_TASK 3304 .uclamp_enabled = 1, 3305 #endif 3306 }; 3307 3308 static void init_dsq(struct scx_dispatch_q *dsq, u64 dsq_id) 3309 { 3310 memset(dsq, 0, sizeof(*dsq)); 3311 3312 raw_spin_lock_init(&dsq->lock); 3313 INIT_LIST_HEAD(&dsq->list); 3314 dsq->id = dsq_id; 3315 } 3316 3317 static void free_dsq_irq_workfn(struct irq_work *irq_work) 3318 { 3319 struct llist_node *to_free = llist_del_all(&dsqs_to_free); 3320 struct scx_dispatch_q *dsq, *tmp_dsq; 3321 3322 llist_for_each_entry_safe(dsq, tmp_dsq, to_free, free_node) 3323 kfree_rcu(dsq, rcu); 3324 } 3325 3326 static DEFINE_IRQ_WORK(free_dsq_irq_work, free_dsq_irq_workfn); 3327 3328 static void destroy_dsq(struct scx_sched *sch, u64 dsq_id) 3329 { 3330 struct scx_dispatch_q *dsq; 3331 unsigned long flags; 3332 3333 rcu_read_lock(); 3334 3335 dsq = find_user_dsq(sch, dsq_id); 3336 if (!dsq) 3337 goto out_unlock_rcu; 3338 3339 raw_spin_lock_irqsave(&dsq->lock, flags); 3340 3341 if (dsq->nr) { 3342 scx_error(sch, "attempting to destroy in-use dsq 0x%016llx (nr=%u)", 3343 dsq->id, dsq->nr); 3344 goto out_unlock_dsq; 3345 } 3346 3347 if (rhashtable_remove_fast(&sch->dsq_hash, &dsq->hash_node, 3348 dsq_hash_params)) 3349 goto out_unlock_dsq; 3350 3351 /* 3352 * Mark dead by invalidating ->id to prevent dispatch_enqueue() from 3353 * queueing more tasks. As this function can be called from anywhere, 3354 * freeing is bounced through an irq work to avoid nesting RCU 3355 * operations inside scheduler locks. 3356 */ 3357 dsq->id = SCX_DSQ_INVALID; 3358 llist_add(&dsq->free_node, &dsqs_to_free); 3359 irq_work_queue(&free_dsq_irq_work); 3360 3361 out_unlock_dsq: 3362 raw_spin_unlock_irqrestore(&dsq->lock, flags); 3363 out_unlock_rcu: 3364 rcu_read_unlock(); 3365 } 3366 3367 #ifdef CONFIG_EXT_GROUP_SCHED 3368 static void scx_cgroup_exit(struct scx_sched *sch) 3369 { 3370 struct cgroup_subsys_state *css; 3371 3372 scx_cgroup_enabled = false; 3373 3374 /* 3375 * scx_tg_on/offline() are excluded through cgroup_lock(). If we walk 3376 * cgroups and exit all the inited ones, all online cgroups are exited. 3377 */ 3378 css_for_each_descendant_post(css, &root_task_group.css) { 3379 struct task_group *tg = css_tg(css); 3380 3381 if (!(tg->scx.flags & SCX_TG_INITED)) 3382 continue; 3383 tg->scx.flags &= ~SCX_TG_INITED; 3384 3385 if (!sch->ops.cgroup_exit) 3386 continue; 3387 3388 SCX_CALL_OP(sch, SCX_KF_UNLOCKED, cgroup_exit, NULL, 3389 css->cgroup); 3390 } 3391 } 3392 3393 static int scx_cgroup_init(struct scx_sched *sch) 3394 { 3395 struct cgroup_subsys_state *css; 3396 int ret; 3397 3398 /* 3399 * scx_tg_on/offline() are excluded through cgroup_lock(). If we walk 3400 * cgroups and init, all online cgroups are initialized. 3401 */ 3402 css_for_each_descendant_pre(css, &root_task_group.css) { 3403 struct task_group *tg = css_tg(css); 3404 struct scx_cgroup_init_args args = { 3405 .weight = tg->scx.weight, 3406 .bw_period_us = tg->scx.bw_period_us, 3407 .bw_quota_us = tg->scx.bw_quota_us, 3408 .bw_burst_us = tg->scx.bw_burst_us, 3409 }; 3410 3411 if ((tg->scx.flags & 3412 (SCX_TG_ONLINE | SCX_TG_INITED)) != SCX_TG_ONLINE) 3413 continue; 3414 3415 if (!sch->ops.cgroup_init) { 3416 tg->scx.flags |= SCX_TG_INITED; 3417 continue; 3418 } 3419 3420 ret = SCX_CALL_OP_RET(sch, SCX_KF_UNLOCKED, cgroup_init, NULL, 3421 css->cgroup, &args); 3422 if (ret) { 3423 css_put(css); 3424 scx_error(sch, "ops.cgroup_init() failed (%d)", ret); 3425 return ret; 3426 } 3427 tg->scx.flags |= SCX_TG_INITED; 3428 } 3429 3430 WARN_ON_ONCE(scx_cgroup_enabled); 3431 scx_cgroup_enabled = true; 3432 3433 return 0; 3434 } 3435 3436 #else 3437 static void scx_cgroup_exit(struct scx_sched *sch) {} 3438 static int scx_cgroup_init(struct scx_sched *sch) { return 0; } 3439 #endif 3440 3441 3442 /******************************************************************************** 3443 * Sysfs interface and ops enable/disable. 3444 */ 3445 3446 #define SCX_ATTR(_name) \ 3447 static struct kobj_attribute scx_attr_##_name = { \ 3448 .attr = { .name = __stringify(_name), .mode = 0444 }, \ 3449 .show = scx_attr_##_name##_show, \ 3450 } 3451 3452 static ssize_t scx_attr_state_show(struct kobject *kobj, 3453 struct kobj_attribute *ka, char *buf) 3454 { 3455 return sysfs_emit(buf, "%s\n", scx_enable_state_str[scx_enable_state()]); 3456 } 3457 SCX_ATTR(state); 3458 3459 static ssize_t scx_attr_switch_all_show(struct kobject *kobj, 3460 struct kobj_attribute *ka, char *buf) 3461 { 3462 return sysfs_emit(buf, "%d\n", READ_ONCE(scx_switching_all)); 3463 } 3464 SCX_ATTR(switch_all); 3465 3466 static ssize_t scx_attr_nr_rejected_show(struct kobject *kobj, 3467 struct kobj_attribute *ka, char *buf) 3468 { 3469 return sysfs_emit(buf, "%ld\n", atomic_long_read(&scx_nr_rejected)); 3470 } 3471 SCX_ATTR(nr_rejected); 3472 3473 static ssize_t scx_attr_hotplug_seq_show(struct kobject *kobj, 3474 struct kobj_attribute *ka, char *buf) 3475 { 3476 return sysfs_emit(buf, "%ld\n", atomic_long_read(&scx_hotplug_seq)); 3477 } 3478 SCX_ATTR(hotplug_seq); 3479 3480 static ssize_t scx_attr_enable_seq_show(struct kobject *kobj, 3481 struct kobj_attribute *ka, char *buf) 3482 { 3483 return sysfs_emit(buf, "%ld\n", atomic_long_read(&scx_enable_seq)); 3484 } 3485 SCX_ATTR(enable_seq); 3486 3487 static struct attribute *scx_global_attrs[] = { 3488 &scx_attr_state.attr, 3489 &scx_attr_switch_all.attr, 3490 &scx_attr_nr_rejected.attr, 3491 &scx_attr_hotplug_seq.attr, 3492 &scx_attr_enable_seq.attr, 3493 NULL, 3494 }; 3495 3496 static const struct attribute_group scx_global_attr_group = { 3497 .attrs = scx_global_attrs, 3498 }; 3499 3500 static void free_exit_info(struct scx_exit_info *ei); 3501 3502 static void scx_sched_free_rcu_work(struct work_struct *work) 3503 { 3504 struct rcu_work *rcu_work = to_rcu_work(work); 3505 struct scx_sched *sch = container_of(rcu_work, struct scx_sched, rcu_work); 3506 struct rhashtable_iter rht_iter; 3507 struct scx_dispatch_q *dsq; 3508 int node; 3509 3510 irq_work_sync(&sch->error_irq_work); 3511 kthread_stop(sch->helper->task); 3512 3513 free_percpu(sch->pcpu); 3514 3515 for_each_node_state(node, N_POSSIBLE) 3516 kfree(sch->global_dsqs[node]); 3517 kfree(sch->global_dsqs); 3518 3519 rhashtable_walk_enter(&sch->dsq_hash, &rht_iter); 3520 do { 3521 rhashtable_walk_start(&rht_iter); 3522 3523 while ((dsq = rhashtable_walk_next(&rht_iter)) && !IS_ERR(dsq)) 3524 destroy_dsq(sch, dsq->id); 3525 3526 rhashtable_walk_stop(&rht_iter); 3527 } while (dsq == ERR_PTR(-EAGAIN)); 3528 rhashtable_walk_exit(&rht_iter); 3529 3530 rhashtable_free_and_destroy(&sch->dsq_hash, NULL, NULL); 3531 free_exit_info(sch->exit_info); 3532 kfree(sch); 3533 } 3534 3535 static void scx_kobj_release(struct kobject *kobj) 3536 { 3537 struct scx_sched *sch = container_of(kobj, struct scx_sched, kobj); 3538 3539 INIT_RCU_WORK(&sch->rcu_work, scx_sched_free_rcu_work); 3540 queue_rcu_work(system_unbound_wq, &sch->rcu_work); 3541 } 3542 3543 static ssize_t scx_attr_ops_show(struct kobject *kobj, 3544 struct kobj_attribute *ka, char *buf) 3545 { 3546 return sysfs_emit(buf, "%s\n", scx_root->ops.name); 3547 } 3548 SCX_ATTR(ops); 3549 3550 #define scx_attr_event_show(buf, at, events, kind) ({ \ 3551 sysfs_emit_at(buf, at, "%s %llu\n", #kind, (events)->kind); \ 3552 }) 3553 3554 static ssize_t scx_attr_events_show(struct kobject *kobj, 3555 struct kobj_attribute *ka, char *buf) 3556 { 3557 struct scx_sched *sch = container_of(kobj, struct scx_sched, kobj); 3558 struct scx_event_stats events; 3559 int at = 0; 3560 3561 scx_read_events(sch, &events); 3562 at += scx_attr_event_show(buf, at, &events, SCX_EV_SELECT_CPU_FALLBACK); 3563 at += scx_attr_event_show(buf, at, &events, SCX_EV_DISPATCH_LOCAL_DSQ_OFFLINE); 3564 at += scx_attr_event_show(buf, at, &events, SCX_EV_DISPATCH_KEEP_LAST); 3565 at += scx_attr_event_show(buf, at, &events, SCX_EV_ENQ_SKIP_EXITING); 3566 at += scx_attr_event_show(buf, at, &events, SCX_EV_ENQ_SKIP_MIGRATION_DISABLED); 3567 at += scx_attr_event_show(buf, at, &events, SCX_EV_REFILL_SLICE_DFL); 3568 at += scx_attr_event_show(buf, at, &events, SCX_EV_BYPASS_DURATION); 3569 at += scx_attr_event_show(buf, at, &events, SCX_EV_BYPASS_DISPATCH); 3570 at += scx_attr_event_show(buf, at, &events, SCX_EV_BYPASS_ACTIVATE); 3571 return at; 3572 } 3573 SCX_ATTR(events); 3574 3575 static struct attribute *scx_sched_attrs[] = { 3576 &scx_attr_ops.attr, 3577 &scx_attr_events.attr, 3578 NULL, 3579 }; 3580 ATTRIBUTE_GROUPS(scx_sched); 3581 3582 static const struct kobj_type scx_ktype = { 3583 .release = scx_kobj_release, 3584 .sysfs_ops = &kobj_sysfs_ops, 3585 .default_groups = scx_sched_groups, 3586 }; 3587 3588 static int scx_uevent(const struct kobject *kobj, struct kobj_uevent_env *env) 3589 { 3590 return add_uevent_var(env, "SCXOPS=%s", scx_root->ops.name); 3591 } 3592 3593 static const struct kset_uevent_ops scx_uevent_ops = { 3594 .uevent = scx_uevent, 3595 }; 3596 3597 /* 3598 * Used by sched_fork() and __setscheduler_prio() to pick the matching 3599 * sched_class. dl/rt are already handled. 3600 */ 3601 bool task_should_scx(int policy) 3602 { 3603 if (!scx_enabled() || unlikely(scx_enable_state() == SCX_DISABLING)) 3604 return false; 3605 if (READ_ONCE(scx_switching_all)) 3606 return true; 3607 return policy == SCHED_EXT; 3608 } 3609 3610 bool scx_allow_ttwu_queue(const struct task_struct *p) 3611 { 3612 struct scx_sched *sch; 3613 3614 if (!scx_enabled()) 3615 return true; 3616 3617 sch = rcu_dereference_sched(scx_root); 3618 if (unlikely(!sch)) 3619 return true; 3620 3621 if (sch->ops.flags & SCX_OPS_ALLOW_QUEUED_WAKEUP) 3622 return true; 3623 3624 if (unlikely(p->sched_class != &ext_sched_class)) 3625 return true; 3626 3627 return false; 3628 } 3629 3630 /** 3631 * scx_rcu_cpu_stall - sched_ext RCU CPU stall handler 3632 * 3633 * While there are various reasons why RCU CPU stalls can occur on a system 3634 * that may not be caused by the current BPF scheduler, try kicking out the 3635 * current scheduler in an attempt to recover the system to a good state before 3636 * issuing panics. 3637 */ 3638 bool scx_rcu_cpu_stall(void) 3639 { 3640 struct scx_sched *sch; 3641 3642 rcu_read_lock(); 3643 3644 sch = rcu_dereference(scx_root); 3645 if (unlikely(!sch)) { 3646 rcu_read_unlock(); 3647 return false; 3648 } 3649 3650 switch (scx_enable_state()) { 3651 case SCX_ENABLING: 3652 case SCX_ENABLED: 3653 break; 3654 default: 3655 rcu_read_unlock(); 3656 return false; 3657 } 3658 3659 scx_error(sch, "RCU CPU stall detected!"); 3660 rcu_read_unlock(); 3661 3662 return true; 3663 } 3664 3665 /** 3666 * scx_softlockup - sched_ext softlockup handler 3667 * @dur_s: number of seconds of CPU stuck due to soft lockup 3668 * 3669 * On some multi-socket setups (e.g. 2x Intel 8480c), the BPF scheduler can 3670 * live-lock the system by making many CPUs target the same DSQ to the point 3671 * where soft-lockup detection triggers. This function is called from 3672 * soft-lockup watchdog when the triggering point is close and tries to unjam 3673 * the system by enabling the breather and aborting the BPF scheduler. 3674 */ 3675 void scx_softlockup(u32 dur_s) 3676 { 3677 struct scx_sched *sch; 3678 3679 rcu_read_lock(); 3680 3681 sch = rcu_dereference(scx_root); 3682 if (unlikely(!sch)) 3683 goto out_unlock; 3684 3685 switch (scx_enable_state()) { 3686 case SCX_ENABLING: 3687 case SCX_ENABLED: 3688 break; 3689 default: 3690 goto out_unlock; 3691 } 3692 3693 /* allow only one instance, cleared at the end of scx_bypass() */ 3694 if (test_and_set_bit(0, &scx_in_softlockup)) 3695 goto out_unlock; 3696 3697 printk_deferred(KERN_ERR "sched_ext: Soft lockup - CPU%d stuck for %us, disabling \"%s\"\n", 3698 smp_processor_id(), dur_s, scx_root->ops.name); 3699 3700 /* 3701 * Some CPUs may be trapped in the dispatch paths. Enable breather 3702 * immediately; otherwise, we might even be able to get to scx_bypass(). 3703 */ 3704 atomic_inc(&scx_breather_depth); 3705 3706 scx_error(sch, "soft lockup - CPU#%d stuck for %us", smp_processor_id(), dur_s); 3707 out_unlock: 3708 rcu_read_unlock(); 3709 } 3710 3711 static void scx_clear_softlockup(void) 3712 { 3713 if (test_and_clear_bit(0, &scx_in_softlockup)) 3714 atomic_dec(&scx_breather_depth); 3715 } 3716 3717 /** 3718 * scx_bypass - [Un]bypass scx_ops and guarantee forward progress 3719 * @bypass: true for bypass, false for unbypass 3720 * 3721 * Bypassing guarantees that all runnable tasks make forward progress without 3722 * trusting the BPF scheduler. We can't grab any mutexes or rwsems as they might 3723 * be held by tasks that the BPF scheduler is forgetting to run, which 3724 * unfortunately also excludes toggling the static branches. 3725 * 3726 * Let's work around by overriding a couple ops and modifying behaviors based on 3727 * the DISABLING state and then cycling the queued tasks through dequeue/enqueue 3728 * to force global FIFO scheduling. 3729 * 3730 * - ops.select_cpu() is ignored and the default select_cpu() is used. 3731 * 3732 * - ops.enqueue() is ignored and tasks are queued in simple global FIFO order. 3733 * %SCX_OPS_ENQ_LAST is also ignored. 3734 * 3735 * - ops.dispatch() is ignored. 3736 * 3737 * - balance_scx() does not set %SCX_RQ_BAL_KEEP on non-zero slice as slice 3738 * can't be trusted. Whenever a tick triggers, the running task is rotated to 3739 * the tail of the queue with core_sched_at touched. 3740 * 3741 * - pick_next_task() suppresses zero slice warning. 3742 * 3743 * - scx_kick_cpu() is disabled to avoid irq_work malfunction during PM 3744 * operations. 3745 * 3746 * - scx_prio_less() reverts to the default core_sched_at order. 3747 */ 3748 static void scx_bypass(bool bypass) 3749 { 3750 static DEFINE_RAW_SPINLOCK(bypass_lock); 3751 static unsigned long bypass_timestamp; 3752 struct scx_sched *sch; 3753 unsigned long flags; 3754 int cpu; 3755 3756 raw_spin_lock_irqsave(&bypass_lock, flags); 3757 sch = rcu_dereference_bh(scx_root); 3758 3759 if (bypass) { 3760 scx_bypass_depth++; 3761 WARN_ON_ONCE(scx_bypass_depth <= 0); 3762 if (scx_bypass_depth != 1) 3763 goto unlock; 3764 bypass_timestamp = ktime_get_ns(); 3765 if (sch) 3766 scx_add_event(sch, SCX_EV_BYPASS_ACTIVATE, 1); 3767 } else { 3768 scx_bypass_depth--; 3769 WARN_ON_ONCE(scx_bypass_depth < 0); 3770 if (scx_bypass_depth != 0) 3771 goto unlock; 3772 if (sch) 3773 scx_add_event(sch, SCX_EV_BYPASS_DURATION, 3774 ktime_get_ns() - bypass_timestamp); 3775 } 3776 3777 atomic_inc(&scx_breather_depth); 3778 3779 /* 3780 * No task property is changing. We just need to make sure all currently 3781 * queued tasks are re-queued according to the new scx_rq_bypassing() 3782 * state. As an optimization, walk each rq's runnable_list instead of 3783 * the scx_tasks list. 3784 * 3785 * This function can't trust the scheduler and thus can't use 3786 * cpus_read_lock(). Walk all possible CPUs instead of online. 3787 */ 3788 for_each_possible_cpu(cpu) { 3789 struct rq *rq = cpu_rq(cpu); 3790 struct task_struct *p, *n; 3791 3792 raw_spin_rq_lock(rq); 3793 3794 if (bypass) { 3795 WARN_ON_ONCE(rq->scx.flags & SCX_RQ_BYPASSING); 3796 rq->scx.flags |= SCX_RQ_BYPASSING; 3797 } else { 3798 WARN_ON_ONCE(!(rq->scx.flags & SCX_RQ_BYPASSING)); 3799 rq->scx.flags &= ~SCX_RQ_BYPASSING; 3800 } 3801 3802 /* 3803 * We need to guarantee that no tasks are on the BPF scheduler 3804 * while bypassing. Either we see enabled or the enable path 3805 * sees scx_rq_bypassing() before moving tasks to SCX. 3806 */ 3807 if (!scx_enabled()) { 3808 raw_spin_rq_unlock(rq); 3809 continue; 3810 } 3811 3812 /* 3813 * The use of list_for_each_entry_safe_reverse() is required 3814 * because each task is going to be removed from and added back 3815 * to the runnable_list during iteration. Because they're added 3816 * to the tail of the list, safe reverse iteration can still 3817 * visit all nodes. 3818 */ 3819 list_for_each_entry_safe_reverse(p, n, &rq->scx.runnable_list, 3820 scx.runnable_node) { 3821 struct sched_enq_and_set_ctx ctx; 3822 3823 /* cycling deq/enq is enough, see the function comment */ 3824 sched_deq_and_put_task(p, DEQUEUE_SAVE | DEQUEUE_MOVE, &ctx); 3825 sched_enq_and_set_task(&ctx); 3826 } 3827 3828 /* resched to restore ticks and idle state */ 3829 if (cpu_online(cpu) || cpu == smp_processor_id()) 3830 resched_curr(rq); 3831 3832 raw_spin_rq_unlock(rq); 3833 } 3834 3835 atomic_dec(&scx_breather_depth); 3836 unlock: 3837 raw_spin_unlock_irqrestore(&bypass_lock, flags); 3838 scx_clear_softlockup(); 3839 } 3840 3841 static void free_exit_info(struct scx_exit_info *ei) 3842 { 3843 kvfree(ei->dump); 3844 kfree(ei->msg); 3845 kfree(ei->bt); 3846 kfree(ei); 3847 } 3848 3849 static struct scx_exit_info *alloc_exit_info(size_t exit_dump_len) 3850 { 3851 struct scx_exit_info *ei; 3852 3853 ei = kzalloc(sizeof(*ei), GFP_KERNEL); 3854 if (!ei) 3855 return NULL; 3856 3857 ei->bt = kcalloc(SCX_EXIT_BT_LEN, sizeof(ei->bt[0]), GFP_KERNEL); 3858 ei->msg = kzalloc(SCX_EXIT_MSG_LEN, GFP_KERNEL); 3859 ei->dump = kvzalloc(exit_dump_len, GFP_KERNEL); 3860 3861 if (!ei->bt || !ei->msg || !ei->dump) { 3862 free_exit_info(ei); 3863 return NULL; 3864 } 3865 3866 return ei; 3867 } 3868 3869 static const char *scx_exit_reason(enum scx_exit_kind kind) 3870 { 3871 switch (kind) { 3872 case SCX_EXIT_UNREG: 3873 return "unregistered from user space"; 3874 case SCX_EXIT_UNREG_BPF: 3875 return "unregistered from BPF"; 3876 case SCX_EXIT_UNREG_KERN: 3877 return "unregistered from the main kernel"; 3878 case SCX_EXIT_SYSRQ: 3879 return "disabled by sysrq-S"; 3880 case SCX_EXIT_ERROR: 3881 return "runtime error"; 3882 case SCX_EXIT_ERROR_BPF: 3883 return "scx_bpf_error"; 3884 case SCX_EXIT_ERROR_STALL: 3885 return "runnable task stall"; 3886 default: 3887 return "<UNKNOWN>"; 3888 } 3889 } 3890 3891 static void free_kick_pseqs_rcu(struct rcu_head *rcu) 3892 { 3893 struct scx_kick_pseqs *pseqs = container_of(rcu, struct scx_kick_pseqs, rcu); 3894 3895 kvfree(pseqs); 3896 } 3897 3898 static void free_kick_pseqs(void) 3899 { 3900 int cpu; 3901 3902 for_each_possible_cpu(cpu) { 3903 struct scx_kick_pseqs **pseqs = per_cpu_ptr(&scx_kick_pseqs, cpu); 3904 struct scx_kick_pseqs *to_free; 3905 3906 to_free = rcu_replace_pointer(*pseqs, NULL, true); 3907 if (to_free) 3908 call_rcu(&to_free->rcu, free_kick_pseqs_rcu); 3909 } 3910 } 3911 3912 static void scx_disable_workfn(struct kthread_work *work) 3913 { 3914 struct scx_sched *sch = container_of(work, struct scx_sched, disable_work); 3915 struct scx_exit_info *ei = sch->exit_info; 3916 struct scx_task_iter sti; 3917 struct task_struct *p; 3918 int kind, cpu; 3919 3920 kind = atomic_read(&sch->exit_kind); 3921 while (true) { 3922 if (kind == SCX_EXIT_DONE) /* already disabled? */ 3923 return; 3924 WARN_ON_ONCE(kind == SCX_EXIT_NONE); 3925 if (atomic_try_cmpxchg(&sch->exit_kind, &kind, SCX_EXIT_DONE)) 3926 break; 3927 } 3928 ei->kind = kind; 3929 ei->reason = scx_exit_reason(ei->kind); 3930 3931 /* guarantee forward progress by bypassing scx_ops */ 3932 scx_bypass(true); 3933 3934 switch (scx_set_enable_state(SCX_DISABLING)) { 3935 case SCX_DISABLING: 3936 WARN_ONCE(true, "sched_ext: duplicate disabling instance?"); 3937 break; 3938 case SCX_DISABLED: 3939 pr_warn("sched_ext: ops error detected without ops (%s)\n", 3940 sch->exit_info->msg); 3941 WARN_ON_ONCE(scx_set_enable_state(SCX_DISABLED) != SCX_DISABLING); 3942 goto done; 3943 default: 3944 break; 3945 } 3946 3947 /* 3948 * Here, every runnable task is guaranteed to make forward progress and 3949 * we can safely use blocking synchronization constructs. Actually 3950 * disable ops. 3951 */ 3952 mutex_lock(&scx_enable_mutex); 3953 3954 static_branch_disable(&__scx_switched_all); 3955 WRITE_ONCE(scx_switching_all, false); 3956 3957 /* 3958 * Shut down cgroup support before tasks so that the cgroup attach path 3959 * doesn't race against scx_exit_task(). 3960 */ 3961 scx_cgroup_lock(); 3962 scx_cgroup_exit(sch); 3963 scx_cgroup_unlock(); 3964 3965 /* 3966 * The BPF scheduler is going away. All tasks including %TASK_DEAD ones 3967 * must be switched out and exited synchronously. 3968 */ 3969 percpu_down_write(&scx_fork_rwsem); 3970 3971 scx_init_task_enabled = false; 3972 3973 scx_task_iter_start(&sti); 3974 while ((p = scx_task_iter_next_locked(&sti))) { 3975 const struct sched_class *old_class = p->sched_class; 3976 const struct sched_class *new_class = 3977 __setscheduler_class(p->policy, p->prio); 3978 struct sched_enq_and_set_ctx ctx; 3979 3980 if (old_class != new_class && p->se.sched_delayed) 3981 dequeue_task(task_rq(p), p, DEQUEUE_SLEEP | DEQUEUE_DELAYED); 3982 3983 sched_deq_and_put_task(p, DEQUEUE_SAVE | DEQUEUE_MOVE, &ctx); 3984 3985 p->sched_class = new_class; 3986 check_class_changing(task_rq(p), p, old_class); 3987 3988 sched_enq_and_set_task(&ctx); 3989 3990 check_class_changed(task_rq(p), p, old_class, p->prio); 3991 scx_exit_task(p); 3992 } 3993 scx_task_iter_stop(&sti); 3994 percpu_up_write(&scx_fork_rwsem); 3995 3996 /* 3997 * Invalidate all the rq clocks to prevent getting outdated 3998 * rq clocks from a previous scx scheduler. 3999 */ 4000 for_each_possible_cpu(cpu) { 4001 struct rq *rq = cpu_rq(cpu); 4002 scx_rq_clock_invalidate(rq); 4003 } 4004 4005 /* no task is on scx, turn off all the switches and flush in-progress calls */ 4006 static_branch_disable(&__scx_enabled); 4007 bitmap_zero(sch->has_op, SCX_OPI_END); 4008 scx_idle_disable(); 4009 synchronize_rcu(); 4010 4011 if (ei->kind >= SCX_EXIT_ERROR) { 4012 pr_err("sched_ext: BPF scheduler \"%s\" disabled (%s)\n", 4013 sch->ops.name, ei->reason); 4014 4015 if (ei->msg[0] != '\0') 4016 pr_err("sched_ext: %s: %s\n", sch->ops.name, ei->msg); 4017 #ifdef CONFIG_STACKTRACE 4018 stack_trace_print(ei->bt, ei->bt_len, 2); 4019 #endif 4020 } else { 4021 pr_info("sched_ext: BPF scheduler \"%s\" disabled (%s)\n", 4022 sch->ops.name, ei->reason); 4023 } 4024 4025 if (sch->ops.exit) 4026 SCX_CALL_OP(sch, SCX_KF_UNLOCKED, exit, NULL, ei); 4027 4028 cancel_delayed_work_sync(&scx_watchdog_work); 4029 4030 /* 4031 * scx_root clearing must be inside cpus_read_lock(). See 4032 * handle_hotplug(). 4033 */ 4034 cpus_read_lock(); 4035 RCU_INIT_POINTER(scx_root, NULL); 4036 cpus_read_unlock(); 4037 4038 /* 4039 * Delete the kobject from the hierarchy synchronously. Otherwise, sysfs 4040 * could observe an object of the same name still in the hierarchy when 4041 * the next scheduler is loaded. 4042 */ 4043 kobject_del(&sch->kobj); 4044 4045 free_percpu(scx_dsp_ctx); 4046 scx_dsp_ctx = NULL; 4047 scx_dsp_max_batch = 0; 4048 free_kick_pseqs(); 4049 4050 mutex_unlock(&scx_enable_mutex); 4051 4052 WARN_ON_ONCE(scx_set_enable_state(SCX_DISABLED) != SCX_DISABLING); 4053 done: 4054 scx_bypass(false); 4055 } 4056 4057 static void scx_disable(enum scx_exit_kind kind) 4058 { 4059 int none = SCX_EXIT_NONE; 4060 struct scx_sched *sch; 4061 4062 if (WARN_ON_ONCE(kind == SCX_EXIT_NONE || kind == SCX_EXIT_DONE)) 4063 kind = SCX_EXIT_ERROR; 4064 4065 rcu_read_lock(); 4066 sch = rcu_dereference(scx_root); 4067 if (sch) { 4068 atomic_try_cmpxchg(&sch->exit_kind, &none, kind); 4069 kthread_queue_work(sch->helper, &sch->disable_work); 4070 } 4071 rcu_read_unlock(); 4072 } 4073 4074 static void dump_newline(struct seq_buf *s) 4075 { 4076 trace_sched_ext_dump(""); 4077 4078 /* @s may be zero sized and seq_buf triggers WARN if so */ 4079 if (s->size) 4080 seq_buf_putc(s, '\n'); 4081 } 4082 4083 static __printf(2, 3) void dump_line(struct seq_buf *s, const char *fmt, ...) 4084 { 4085 va_list args; 4086 4087 #ifdef CONFIG_TRACEPOINTS 4088 if (trace_sched_ext_dump_enabled()) { 4089 /* protected by scx_dump_state()::dump_lock */ 4090 static char line_buf[SCX_EXIT_MSG_LEN]; 4091 4092 va_start(args, fmt); 4093 vscnprintf(line_buf, sizeof(line_buf), fmt, args); 4094 va_end(args); 4095 4096 trace_sched_ext_dump(line_buf); 4097 } 4098 #endif 4099 /* @s may be zero sized and seq_buf triggers WARN if so */ 4100 if (s->size) { 4101 va_start(args, fmt); 4102 seq_buf_vprintf(s, fmt, args); 4103 va_end(args); 4104 4105 seq_buf_putc(s, '\n'); 4106 } 4107 } 4108 4109 static void dump_stack_trace(struct seq_buf *s, const char *prefix, 4110 const unsigned long *bt, unsigned int len) 4111 { 4112 unsigned int i; 4113 4114 for (i = 0; i < len; i++) 4115 dump_line(s, "%s%pS", prefix, (void *)bt[i]); 4116 } 4117 4118 static void ops_dump_init(struct seq_buf *s, const char *prefix) 4119 { 4120 struct scx_dump_data *dd = &scx_dump_data; 4121 4122 lockdep_assert_irqs_disabled(); 4123 4124 dd->cpu = smp_processor_id(); /* allow scx_bpf_dump() */ 4125 dd->first = true; 4126 dd->cursor = 0; 4127 dd->s = s; 4128 dd->prefix = prefix; 4129 } 4130 4131 static void ops_dump_flush(void) 4132 { 4133 struct scx_dump_data *dd = &scx_dump_data; 4134 char *line = dd->buf.line; 4135 4136 if (!dd->cursor) 4137 return; 4138 4139 /* 4140 * There's something to flush and this is the first line. Insert a blank 4141 * line to distinguish ops dump. 4142 */ 4143 if (dd->first) { 4144 dump_newline(dd->s); 4145 dd->first = false; 4146 } 4147 4148 /* 4149 * There may be multiple lines in $line. Scan and emit each line 4150 * separately. 4151 */ 4152 while (true) { 4153 char *end = line; 4154 char c; 4155 4156 while (*end != '\n' && *end != '\0') 4157 end++; 4158 4159 /* 4160 * If $line overflowed, it may not have newline at the end. 4161 * Always emit with a newline. 4162 */ 4163 c = *end; 4164 *end = '\0'; 4165 dump_line(dd->s, "%s%s", dd->prefix, line); 4166 if (c == '\0') 4167 break; 4168 4169 /* move to the next line */ 4170 end++; 4171 if (*end == '\0') 4172 break; 4173 line = end; 4174 } 4175 4176 dd->cursor = 0; 4177 } 4178 4179 static void ops_dump_exit(void) 4180 { 4181 ops_dump_flush(); 4182 scx_dump_data.cpu = -1; 4183 } 4184 4185 static void scx_dump_task(struct seq_buf *s, struct scx_dump_ctx *dctx, 4186 struct task_struct *p, char marker) 4187 { 4188 static unsigned long bt[SCX_EXIT_BT_LEN]; 4189 struct scx_sched *sch = scx_root; 4190 char dsq_id_buf[19] = "(n/a)"; 4191 unsigned long ops_state = atomic_long_read(&p->scx.ops_state); 4192 unsigned int bt_len = 0; 4193 4194 if (p->scx.dsq) 4195 scnprintf(dsq_id_buf, sizeof(dsq_id_buf), "0x%llx", 4196 (unsigned long long)p->scx.dsq->id); 4197 4198 dump_newline(s); 4199 dump_line(s, " %c%c %s[%d] %+ldms", 4200 marker, task_state_to_char(p), p->comm, p->pid, 4201 jiffies_delta_msecs(p->scx.runnable_at, dctx->at_jiffies)); 4202 dump_line(s, " scx_state/flags=%u/0x%x dsq_flags=0x%x ops_state/qseq=%lu/%lu", 4203 scx_get_task_state(p), p->scx.flags & ~SCX_TASK_STATE_MASK, 4204 p->scx.dsq_flags, ops_state & SCX_OPSS_STATE_MASK, 4205 ops_state >> SCX_OPSS_QSEQ_SHIFT); 4206 dump_line(s, " sticky/holding_cpu=%d/%d dsq_id=%s", 4207 p->scx.sticky_cpu, p->scx.holding_cpu, dsq_id_buf); 4208 dump_line(s, " dsq_vtime=%llu slice=%llu weight=%u", 4209 p->scx.dsq_vtime, p->scx.slice, p->scx.weight); 4210 dump_line(s, " cpus=%*pb no_mig=%u", cpumask_pr_args(p->cpus_ptr), 4211 p->migration_disabled); 4212 4213 if (SCX_HAS_OP(sch, dump_task)) { 4214 ops_dump_init(s, " "); 4215 SCX_CALL_OP(sch, SCX_KF_REST, dump_task, NULL, dctx, p); 4216 ops_dump_exit(); 4217 } 4218 4219 #ifdef CONFIG_STACKTRACE 4220 bt_len = stack_trace_save_tsk(p, bt, SCX_EXIT_BT_LEN, 1); 4221 #endif 4222 if (bt_len) { 4223 dump_newline(s); 4224 dump_stack_trace(s, " ", bt, bt_len); 4225 } 4226 } 4227 4228 static void scx_dump_state(struct scx_exit_info *ei, size_t dump_len) 4229 { 4230 static DEFINE_SPINLOCK(dump_lock); 4231 static const char trunc_marker[] = "\n\n~~~~ TRUNCATED ~~~~\n"; 4232 struct scx_sched *sch = scx_root; 4233 struct scx_dump_ctx dctx = { 4234 .kind = ei->kind, 4235 .exit_code = ei->exit_code, 4236 .reason = ei->reason, 4237 .at_ns = ktime_get_ns(), 4238 .at_jiffies = jiffies, 4239 }; 4240 struct seq_buf s; 4241 struct scx_event_stats events; 4242 unsigned long flags; 4243 char *buf; 4244 int cpu; 4245 4246 spin_lock_irqsave(&dump_lock, flags); 4247 4248 seq_buf_init(&s, ei->dump, dump_len); 4249 4250 if (ei->kind == SCX_EXIT_NONE) { 4251 dump_line(&s, "Debug dump triggered by %s", ei->reason); 4252 } else { 4253 dump_line(&s, "%s[%d] triggered exit kind %d:", 4254 current->comm, current->pid, ei->kind); 4255 dump_line(&s, " %s (%s)", ei->reason, ei->msg); 4256 dump_newline(&s); 4257 dump_line(&s, "Backtrace:"); 4258 dump_stack_trace(&s, " ", ei->bt, ei->bt_len); 4259 } 4260 4261 if (SCX_HAS_OP(sch, dump)) { 4262 ops_dump_init(&s, ""); 4263 SCX_CALL_OP(sch, SCX_KF_UNLOCKED, dump, NULL, &dctx); 4264 ops_dump_exit(); 4265 } 4266 4267 dump_newline(&s); 4268 dump_line(&s, "CPU states"); 4269 dump_line(&s, "----------"); 4270 4271 for_each_possible_cpu(cpu) { 4272 struct rq *rq = cpu_rq(cpu); 4273 struct rq_flags rf; 4274 struct task_struct *p; 4275 struct seq_buf ns; 4276 size_t avail, used; 4277 bool idle; 4278 4279 rq_lock(rq, &rf); 4280 4281 idle = list_empty(&rq->scx.runnable_list) && 4282 rq->curr->sched_class == &idle_sched_class; 4283 4284 if (idle && !SCX_HAS_OP(sch, dump_cpu)) 4285 goto next; 4286 4287 /* 4288 * We don't yet know whether ops.dump_cpu() will produce output 4289 * and we may want to skip the default CPU dump if it doesn't. 4290 * Use a nested seq_buf to generate the standard dump so that we 4291 * can decide whether to commit later. 4292 */ 4293 avail = seq_buf_get_buf(&s, &buf); 4294 seq_buf_init(&ns, buf, avail); 4295 4296 dump_newline(&ns); 4297 dump_line(&ns, "CPU %-4d: nr_run=%u flags=0x%x cpu_rel=%d ops_qseq=%lu pnt_seq=%lu", 4298 cpu, rq->scx.nr_running, rq->scx.flags, 4299 rq->scx.cpu_released, rq->scx.ops_qseq, 4300 rq->scx.pnt_seq); 4301 dump_line(&ns, " curr=%s[%d] class=%ps", 4302 rq->curr->comm, rq->curr->pid, 4303 rq->curr->sched_class); 4304 if (!cpumask_empty(rq->scx.cpus_to_kick)) 4305 dump_line(&ns, " cpus_to_kick : %*pb", 4306 cpumask_pr_args(rq->scx.cpus_to_kick)); 4307 if (!cpumask_empty(rq->scx.cpus_to_kick_if_idle)) 4308 dump_line(&ns, " idle_to_kick : %*pb", 4309 cpumask_pr_args(rq->scx.cpus_to_kick_if_idle)); 4310 if (!cpumask_empty(rq->scx.cpus_to_preempt)) 4311 dump_line(&ns, " cpus_to_preempt: %*pb", 4312 cpumask_pr_args(rq->scx.cpus_to_preempt)); 4313 if (!cpumask_empty(rq->scx.cpus_to_wait)) 4314 dump_line(&ns, " cpus_to_wait : %*pb", 4315 cpumask_pr_args(rq->scx.cpus_to_wait)); 4316 4317 used = seq_buf_used(&ns); 4318 if (SCX_HAS_OP(sch, dump_cpu)) { 4319 ops_dump_init(&ns, " "); 4320 SCX_CALL_OP(sch, SCX_KF_REST, dump_cpu, NULL, 4321 &dctx, cpu, idle); 4322 ops_dump_exit(); 4323 } 4324 4325 /* 4326 * If idle && nothing generated by ops.dump_cpu(), there's 4327 * nothing interesting. Skip. 4328 */ 4329 if (idle && used == seq_buf_used(&ns)) 4330 goto next; 4331 4332 /* 4333 * $s may already have overflowed when $ns was created. If so, 4334 * calling commit on it will trigger BUG. 4335 */ 4336 if (avail) { 4337 seq_buf_commit(&s, seq_buf_used(&ns)); 4338 if (seq_buf_has_overflowed(&ns)) 4339 seq_buf_set_overflow(&s); 4340 } 4341 4342 if (rq->curr->sched_class == &ext_sched_class) 4343 scx_dump_task(&s, &dctx, rq->curr, '*'); 4344 4345 list_for_each_entry(p, &rq->scx.runnable_list, scx.runnable_node) 4346 scx_dump_task(&s, &dctx, p, ' '); 4347 next: 4348 rq_unlock(rq, &rf); 4349 } 4350 4351 dump_newline(&s); 4352 dump_line(&s, "Event counters"); 4353 dump_line(&s, "--------------"); 4354 4355 scx_read_events(sch, &events); 4356 scx_dump_event(s, &events, SCX_EV_SELECT_CPU_FALLBACK); 4357 scx_dump_event(s, &events, SCX_EV_DISPATCH_LOCAL_DSQ_OFFLINE); 4358 scx_dump_event(s, &events, SCX_EV_DISPATCH_KEEP_LAST); 4359 scx_dump_event(s, &events, SCX_EV_ENQ_SKIP_EXITING); 4360 scx_dump_event(s, &events, SCX_EV_ENQ_SKIP_MIGRATION_DISABLED); 4361 scx_dump_event(s, &events, SCX_EV_REFILL_SLICE_DFL); 4362 scx_dump_event(s, &events, SCX_EV_BYPASS_DURATION); 4363 scx_dump_event(s, &events, SCX_EV_BYPASS_DISPATCH); 4364 scx_dump_event(s, &events, SCX_EV_BYPASS_ACTIVATE); 4365 4366 if (seq_buf_has_overflowed(&s) && dump_len >= sizeof(trunc_marker)) 4367 memcpy(ei->dump + dump_len - sizeof(trunc_marker), 4368 trunc_marker, sizeof(trunc_marker)); 4369 4370 spin_unlock_irqrestore(&dump_lock, flags); 4371 } 4372 4373 static void scx_error_irq_workfn(struct irq_work *irq_work) 4374 { 4375 struct scx_sched *sch = container_of(irq_work, struct scx_sched, error_irq_work); 4376 struct scx_exit_info *ei = sch->exit_info; 4377 4378 if (ei->kind >= SCX_EXIT_ERROR) 4379 scx_dump_state(ei, sch->ops.exit_dump_len); 4380 4381 kthread_queue_work(sch->helper, &sch->disable_work); 4382 } 4383 4384 static void scx_vexit(struct scx_sched *sch, 4385 enum scx_exit_kind kind, s64 exit_code, 4386 const char *fmt, va_list args) 4387 { 4388 struct scx_exit_info *ei = sch->exit_info; 4389 int none = SCX_EXIT_NONE; 4390 4391 if (!atomic_try_cmpxchg(&sch->exit_kind, &none, kind)) 4392 return; 4393 4394 ei->exit_code = exit_code; 4395 #ifdef CONFIG_STACKTRACE 4396 if (kind >= SCX_EXIT_ERROR) 4397 ei->bt_len = stack_trace_save(ei->bt, SCX_EXIT_BT_LEN, 1); 4398 #endif 4399 vscnprintf(ei->msg, SCX_EXIT_MSG_LEN, fmt, args); 4400 4401 /* 4402 * Set ei->kind and ->reason for scx_dump_state(). They'll be set again 4403 * in scx_disable_workfn(). 4404 */ 4405 ei->kind = kind; 4406 ei->reason = scx_exit_reason(ei->kind); 4407 4408 irq_work_queue(&sch->error_irq_work); 4409 } 4410 4411 static int alloc_kick_pseqs(void) 4412 { 4413 int cpu; 4414 4415 /* 4416 * Allocate per-CPU arrays sized by nr_cpu_ids. Use kvzalloc as size 4417 * can exceed percpu allocator limits on large machines. 4418 */ 4419 for_each_possible_cpu(cpu) { 4420 struct scx_kick_pseqs **pseqs = per_cpu_ptr(&scx_kick_pseqs, cpu); 4421 struct scx_kick_pseqs *new_pseqs; 4422 4423 WARN_ON_ONCE(rcu_access_pointer(*pseqs)); 4424 4425 new_pseqs = kvzalloc_node(struct_size(new_pseqs, seqs, nr_cpu_ids), 4426 GFP_KERNEL, cpu_to_node(cpu)); 4427 if (!new_pseqs) { 4428 free_kick_pseqs(); 4429 return -ENOMEM; 4430 } 4431 4432 rcu_assign_pointer(*pseqs, new_pseqs); 4433 } 4434 4435 return 0; 4436 } 4437 4438 static struct scx_sched *scx_alloc_and_add_sched(struct sched_ext_ops *ops) 4439 { 4440 struct scx_sched *sch; 4441 int node, ret; 4442 4443 sch = kzalloc(sizeof(*sch), GFP_KERNEL); 4444 if (!sch) 4445 return ERR_PTR(-ENOMEM); 4446 4447 sch->exit_info = alloc_exit_info(ops->exit_dump_len); 4448 if (!sch->exit_info) { 4449 ret = -ENOMEM; 4450 goto err_free_sch; 4451 } 4452 4453 ret = rhashtable_init(&sch->dsq_hash, &dsq_hash_params); 4454 if (ret < 0) 4455 goto err_free_ei; 4456 4457 sch->global_dsqs = kcalloc(nr_node_ids, sizeof(sch->global_dsqs[0]), 4458 GFP_KERNEL); 4459 if (!sch->global_dsqs) { 4460 ret = -ENOMEM; 4461 goto err_free_hash; 4462 } 4463 4464 for_each_node_state(node, N_POSSIBLE) { 4465 struct scx_dispatch_q *dsq; 4466 4467 dsq = kzalloc_node(sizeof(*dsq), GFP_KERNEL, node); 4468 if (!dsq) { 4469 ret = -ENOMEM; 4470 goto err_free_gdsqs; 4471 } 4472 4473 init_dsq(dsq, SCX_DSQ_GLOBAL); 4474 sch->global_dsqs[node] = dsq; 4475 } 4476 4477 sch->pcpu = alloc_percpu(struct scx_sched_pcpu); 4478 if (!sch->pcpu) 4479 goto err_free_gdsqs; 4480 4481 sch->helper = kthread_run_worker(0, "sched_ext_helper"); 4482 if (!sch->helper) 4483 goto err_free_pcpu; 4484 sched_set_fifo(sch->helper->task); 4485 4486 atomic_set(&sch->exit_kind, SCX_EXIT_NONE); 4487 init_irq_work(&sch->error_irq_work, scx_error_irq_workfn); 4488 kthread_init_work(&sch->disable_work, scx_disable_workfn); 4489 sch->ops = *ops; 4490 ops->priv = sch; 4491 4492 sch->kobj.kset = scx_kset; 4493 ret = kobject_init_and_add(&sch->kobj, &scx_ktype, NULL, "root"); 4494 if (ret < 0) 4495 goto err_stop_helper; 4496 4497 return sch; 4498 4499 err_stop_helper: 4500 kthread_stop(sch->helper->task); 4501 err_free_pcpu: 4502 free_percpu(sch->pcpu); 4503 err_free_gdsqs: 4504 for_each_node_state(node, N_POSSIBLE) 4505 kfree(sch->global_dsqs[node]); 4506 kfree(sch->global_dsqs); 4507 err_free_hash: 4508 rhashtable_free_and_destroy(&sch->dsq_hash, NULL, NULL); 4509 err_free_ei: 4510 free_exit_info(sch->exit_info); 4511 err_free_sch: 4512 kfree(sch); 4513 return ERR_PTR(ret); 4514 } 4515 4516 static int check_hotplug_seq(struct scx_sched *sch, 4517 const struct sched_ext_ops *ops) 4518 { 4519 unsigned long long global_hotplug_seq; 4520 4521 /* 4522 * If a hotplug event has occurred between when a scheduler was 4523 * initialized, and when we were able to attach, exit and notify user 4524 * space about it. 4525 */ 4526 if (ops->hotplug_seq) { 4527 global_hotplug_seq = atomic_long_read(&scx_hotplug_seq); 4528 if (ops->hotplug_seq != global_hotplug_seq) { 4529 scx_exit(sch, SCX_EXIT_UNREG_KERN, 4530 SCX_ECODE_ACT_RESTART | SCX_ECODE_RSN_HOTPLUG, 4531 "expected hotplug seq %llu did not match actual %llu", 4532 ops->hotplug_seq, global_hotplug_seq); 4533 return -EBUSY; 4534 } 4535 } 4536 4537 return 0; 4538 } 4539 4540 static int validate_ops(struct scx_sched *sch, const struct sched_ext_ops *ops) 4541 { 4542 /* 4543 * It doesn't make sense to specify the SCX_OPS_ENQ_LAST flag if the 4544 * ops.enqueue() callback isn't implemented. 4545 */ 4546 if ((ops->flags & SCX_OPS_ENQ_LAST) && !ops->enqueue) { 4547 scx_error(sch, "SCX_OPS_ENQ_LAST requires ops.enqueue() to be implemented"); 4548 return -EINVAL; 4549 } 4550 4551 /* 4552 * SCX_OPS_BUILTIN_IDLE_PER_NODE requires built-in CPU idle 4553 * selection policy to be enabled. 4554 */ 4555 if ((ops->flags & SCX_OPS_BUILTIN_IDLE_PER_NODE) && 4556 (ops->update_idle && !(ops->flags & SCX_OPS_KEEP_BUILTIN_IDLE))) { 4557 scx_error(sch, "SCX_OPS_BUILTIN_IDLE_PER_NODE requires CPU idle selection enabled"); 4558 return -EINVAL; 4559 } 4560 4561 if (ops->flags & SCX_OPS_HAS_CGROUP_WEIGHT) 4562 pr_warn("SCX_OPS_HAS_CGROUP_WEIGHT is deprecated and a noop\n"); 4563 4564 return 0; 4565 } 4566 4567 static int scx_enable(struct sched_ext_ops *ops, struct bpf_link *link) 4568 { 4569 struct scx_sched *sch; 4570 struct scx_task_iter sti; 4571 struct task_struct *p; 4572 unsigned long timeout; 4573 int i, cpu, ret; 4574 4575 if (!cpumask_equal(housekeeping_cpumask(HK_TYPE_DOMAIN), 4576 cpu_possible_mask)) { 4577 pr_err("sched_ext: Not compatible with \"isolcpus=\" domain isolation\n"); 4578 return -EINVAL; 4579 } 4580 4581 mutex_lock(&scx_enable_mutex); 4582 4583 ret = alloc_kick_pseqs(); 4584 if (ret) 4585 goto err_unlock; 4586 4587 if (scx_enable_state() != SCX_DISABLED) { 4588 ret = -EBUSY; 4589 goto err_free_pseqs; 4590 } 4591 4592 sch = scx_alloc_and_add_sched(ops); 4593 if (IS_ERR(sch)) { 4594 ret = PTR_ERR(sch); 4595 goto err_free_pseqs; 4596 } 4597 4598 /* 4599 * Transition to ENABLING and clear exit info to arm the disable path. 4600 * Failure triggers full disabling from here on. 4601 */ 4602 WARN_ON_ONCE(scx_set_enable_state(SCX_ENABLING) != SCX_DISABLED); 4603 WARN_ON_ONCE(scx_root); 4604 4605 atomic_long_set(&scx_nr_rejected, 0); 4606 4607 for_each_possible_cpu(cpu) 4608 cpu_rq(cpu)->scx.cpuperf_target = SCX_CPUPERF_ONE; 4609 4610 /* 4611 * Keep CPUs stable during enable so that the BPF scheduler can track 4612 * online CPUs by watching ->on/offline_cpu() after ->init(). 4613 */ 4614 cpus_read_lock(); 4615 4616 /* 4617 * Make the scheduler instance visible. Must be inside cpus_read_lock(). 4618 * See handle_hotplug(). 4619 */ 4620 rcu_assign_pointer(scx_root, sch); 4621 4622 scx_idle_enable(ops); 4623 4624 if (sch->ops.init) { 4625 ret = SCX_CALL_OP_RET(sch, SCX_KF_UNLOCKED, init, NULL); 4626 if (ret) { 4627 ret = ops_sanitize_err(sch, "init", ret); 4628 cpus_read_unlock(); 4629 scx_error(sch, "ops.init() failed (%d)", ret); 4630 goto err_disable; 4631 } 4632 sch->exit_info->flags |= SCX_EFLAG_INITIALIZED; 4633 } 4634 4635 for (i = SCX_OPI_CPU_HOTPLUG_BEGIN; i < SCX_OPI_CPU_HOTPLUG_END; i++) 4636 if (((void (**)(void))ops)[i]) 4637 set_bit(i, sch->has_op); 4638 4639 ret = check_hotplug_seq(sch, ops); 4640 if (ret) { 4641 cpus_read_unlock(); 4642 goto err_disable; 4643 } 4644 scx_idle_update_selcpu_topology(ops); 4645 4646 cpus_read_unlock(); 4647 4648 ret = validate_ops(sch, ops); 4649 if (ret) 4650 goto err_disable; 4651 4652 WARN_ON_ONCE(scx_dsp_ctx); 4653 scx_dsp_max_batch = ops->dispatch_max_batch ?: SCX_DSP_DFL_MAX_BATCH; 4654 scx_dsp_ctx = __alloc_percpu(struct_size_t(struct scx_dsp_ctx, buf, 4655 scx_dsp_max_batch), 4656 __alignof__(struct scx_dsp_ctx)); 4657 if (!scx_dsp_ctx) { 4658 ret = -ENOMEM; 4659 goto err_disable; 4660 } 4661 4662 if (ops->timeout_ms) 4663 timeout = msecs_to_jiffies(ops->timeout_ms); 4664 else 4665 timeout = SCX_WATCHDOG_MAX_TIMEOUT; 4666 4667 WRITE_ONCE(scx_watchdog_timeout, timeout); 4668 WRITE_ONCE(scx_watchdog_timestamp, jiffies); 4669 queue_delayed_work(system_unbound_wq, &scx_watchdog_work, 4670 scx_watchdog_timeout / 2); 4671 4672 /* 4673 * Once __scx_enabled is set, %current can be switched to SCX anytime. 4674 * This can lead to stalls as some BPF schedulers (e.g. userspace 4675 * scheduling) may not function correctly before all tasks are switched. 4676 * Init in bypass mode to guarantee forward progress. 4677 */ 4678 scx_bypass(true); 4679 4680 for (i = SCX_OPI_NORMAL_BEGIN; i < SCX_OPI_NORMAL_END; i++) 4681 if (((void (**)(void))ops)[i]) 4682 set_bit(i, sch->has_op); 4683 4684 if (sch->ops.cpu_acquire || sch->ops.cpu_release) 4685 sch->ops.flags |= SCX_OPS_HAS_CPU_PREEMPT; 4686 4687 /* 4688 * Lock out forks, cgroup on/offlining and moves before opening the 4689 * floodgate so that they don't wander into the operations prematurely. 4690 */ 4691 percpu_down_write(&scx_fork_rwsem); 4692 4693 WARN_ON_ONCE(scx_init_task_enabled); 4694 scx_init_task_enabled = true; 4695 4696 /* 4697 * Enable ops for every task. Fork is excluded by scx_fork_rwsem 4698 * preventing new tasks from being added. No need to exclude tasks 4699 * leaving as sched_ext_free() can handle both prepped and enabled 4700 * tasks. Prep all tasks first and then enable them with preemption 4701 * disabled. 4702 * 4703 * All cgroups should be initialized before scx_init_task() so that the 4704 * BPF scheduler can reliably track each task's cgroup membership from 4705 * scx_init_task(). Lock out cgroup on/offlining and task migrations 4706 * while tasks are being initialized so that scx_cgroup_can_attach() 4707 * never sees uninitialized tasks. 4708 */ 4709 scx_cgroup_lock(); 4710 ret = scx_cgroup_init(sch); 4711 if (ret) 4712 goto err_disable_unlock_all; 4713 4714 scx_task_iter_start(&sti); 4715 while ((p = scx_task_iter_next_locked(&sti))) { 4716 /* 4717 * @p may already be dead, have lost all its usages counts and 4718 * be waiting for RCU grace period before being freed. @p can't 4719 * be initialized for SCX in such cases and should be ignored. 4720 */ 4721 if (!tryget_task_struct(p)) 4722 continue; 4723 4724 scx_task_iter_unlock(&sti); 4725 4726 ret = scx_init_task(p, task_group(p), false); 4727 if (ret) { 4728 put_task_struct(p); 4729 scx_task_iter_stop(&sti); 4730 scx_error(sch, "ops.init_task() failed (%d) for %s[%d]", 4731 ret, p->comm, p->pid); 4732 goto err_disable_unlock_all; 4733 } 4734 4735 scx_set_task_state(p, SCX_TASK_READY); 4736 4737 put_task_struct(p); 4738 } 4739 scx_task_iter_stop(&sti); 4740 scx_cgroup_unlock(); 4741 percpu_up_write(&scx_fork_rwsem); 4742 4743 /* 4744 * All tasks are READY. It's safe to turn on scx_enabled() and switch 4745 * all eligible tasks. 4746 */ 4747 WRITE_ONCE(scx_switching_all, !(ops->flags & SCX_OPS_SWITCH_PARTIAL)); 4748 static_branch_enable(&__scx_enabled); 4749 4750 /* 4751 * We're fully committed and can't fail. The task READY -> ENABLED 4752 * transitions here are synchronized against sched_ext_free() through 4753 * scx_tasks_lock. 4754 */ 4755 percpu_down_write(&scx_fork_rwsem); 4756 scx_task_iter_start(&sti); 4757 while ((p = scx_task_iter_next_locked(&sti))) { 4758 const struct sched_class *old_class = p->sched_class; 4759 const struct sched_class *new_class = 4760 __setscheduler_class(p->policy, p->prio); 4761 struct sched_enq_and_set_ctx ctx; 4762 4763 if (!tryget_task_struct(p)) 4764 continue; 4765 4766 if (old_class != new_class && p->se.sched_delayed) 4767 dequeue_task(task_rq(p), p, DEQUEUE_SLEEP | DEQUEUE_DELAYED); 4768 4769 sched_deq_and_put_task(p, DEQUEUE_SAVE | DEQUEUE_MOVE, &ctx); 4770 4771 p->scx.slice = SCX_SLICE_DFL; 4772 p->sched_class = new_class; 4773 check_class_changing(task_rq(p), p, old_class); 4774 4775 sched_enq_and_set_task(&ctx); 4776 4777 check_class_changed(task_rq(p), p, old_class, p->prio); 4778 put_task_struct(p); 4779 } 4780 scx_task_iter_stop(&sti); 4781 percpu_up_write(&scx_fork_rwsem); 4782 4783 scx_bypass(false); 4784 4785 if (!scx_tryset_enable_state(SCX_ENABLED, SCX_ENABLING)) { 4786 WARN_ON_ONCE(atomic_read(&sch->exit_kind) == SCX_EXIT_NONE); 4787 goto err_disable; 4788 } 4789 4790 if (!(ops->flags & SCX_OPS_SWITCH_PARTIAL)) 4791 static_branch_enable(&__scx_switched_all); 4792 4793 pr_info("sched_ext: BPF scheduler \"%s\" enabled%s\n", 4794 sch->ops.name, scx_switched_all() ? "" : " (partial)"); 4795 kobject_uevent(&sch->kobj, KOBJ_ADD); 4796 mutex_unlock(&scx_enable_mutex); 4797 4798 atomic_long_inc(&scx_enable_seq); 4799 4800 return 0; 4801 4802 err_free_pseqs: 4803 free_kick_pseqs(); 4804 err_unlock: 4805 mutex_unlock(&scx_enable_mutex); 4806 return ret; 4807 4808 err_disable_unlock_all: 4809 scx_cgroup_unlock(); 4810 percpu_up_write(&scx_fork_rwsem); 4811 /* we'll soon enter disable path, keep bypass on */ 4812 err_disable: 4813 mutex_unlock(&scx_enable_mutex); 4814 /* 4815 * Returning an error code here would not pass all the error information 4816 * to userspace. Record errno using scx_error() for cases scx_error() 4817 * wasn't already invoked and exit indicating success so that the error 4818 * is notified through ops.exit() with all the details. 4819 * 4820 * Flush scx_disable_work to ensure that error is reported before init 4821 * completion. sch's base reference will be put by bpf_scx_unreg(). 4822 */ 4823 scx_error(sch, "scx_enable() failed (%d)", ret); 4824 kthread_flush_work(&sch->disable_work); 4825 return 0; 4826 } 4827 4828 4829 /******************************************************************************** 4830 * bpf_struct_ops plumbing. 4831 */ 4832 #include <linux/bpf_verifier.h> 4833 #include <linux/bpf.h> 4834 #include <linux/btf.h> 4835 4836 static const struct btf_type *task_struct_type; 4837 4838 static bool bpf_scx_is_valid_access(int off, int size, 4839 enum bpf_access_type type, 4840 const struct bpf_prog *prog, 4841 struct bpf_insn_access_aux *info) 4842 { 4843 if (type != BPF_READ) 4844 return false; 4845 if (off < 0 || off >= sizeof(__u64) * MAX_BPF_FUNC_ARGS) 4846 return false; 4847 if (off % size != 0) 4848 return false; 4849 4850 return btf_ctx_access(off, size, type, prog, info); 4851 } 4852 4853 static int bpf_scx_btf_struct_access(struct bpf_verifier_log *log, 4854 const struct bpf_reg_state *reg, int off, 4855 int size) 4856 { 4857 const struct btf_type *t; 4858 4859 t = btf_type_by_id(reg->btf, reg->btf_id); 4860 if (t == task_struct_type) { 4861 if (off >= offsetof(struct task_struct, scx.slice) && 4862 off + size <= offsetofend(struct task_struct, scx.slice)) 4863 return SCALAR_VALUE; 4864 if (off >= offsetof(struct task_struct, scx.dsq_vtime) && 4865 off + size <= offsetofend(struct task_struct, scx.dsq_vtime)) 4866 return SCALAR_VALUE; 4867 if (off >= offsetof(struct task_struct, scx.disallow) && 4868 off + size <= offsetofend(struct task_struct, scx.disallow)) 4869 return SCALAR_VALUE; 4870 } 4871 4872 return -EACCES; 4873 } 4874 4875 static const struct bpf_verifier_ops bpf_scx_verifier_ops = { 4876 .get_func_proto = bpf_base_func_proto, 4877 .is_valid_access = bpf_scx_is_valid_access, 4878 .btf_struct_access = bpf_scx_btf_struct_access, 4879 }; 4880 4881 static int bpf_scx_init_member(const struct btf_type *t, 4882 const struct btf_member *member, 4883 void *kdata, const void *udata) 4884 { 4885 const struct sched_ext_ops *uops = udata; 4886 struct sched_ext_ops *ops = kdata; 4887 u32 moff = __btf_member_bit_offset(t, member) / 8; 4888 int ret; 4889 4890 switch (moff) { 4891 case offsetof(struct sched_ext_ops, dispatch_max_batch): 4892 if (*(u32 *)(udata + moff) > INT_MAX) 4893 return -E2BIG; 4894 ops->dispatch_max_batch = *(u32 *)(udata + moff); 4895 return 1; 4896 case offsetof(struct sched_ext_ops, flags): 4897 if (*(u64 *)(udata + moff) & ~SCX_OPS_ALL_FLAGS) 4898 return -EINVAL; 4899 ops->flags = *(u64 *)(udata + moff); 4900 return 1; 4901 case offsetof(struct sched_ext_ops, name): 4902 ret = bpf_obj_name_cpy(ops->name, uops->name, 4903 sizeof(ops->name)); 4904 if (ret < 0) 4905 return ret; 4906 if (ret == 0) 4907 return -EINVAL; 4908 return 1; 4909 case offsetof(struct sched_ext_ops, timeout_ms): 4910 if (msecs_to_jiffies(*(u32 *)(udata + moff)) > 4911 SCX_WATCHDOG_MAX_TIMEOUT) 4912 return -E2BIG; 4913 ops->timeout_ms = *(u32 *)(udata + moff); 4914 return 1; 4915 case offsetof(struct sched_ext_ops, exit_dump_len): 4916 ops->exit_dump_len = 4917 *(u32 *)(udata + moff) ?: SCX_EXIT_DUMP_DFL_LEN; 4918 return 1; 4919 case offsetof(struct sched_ext_ops, hotplug_seq): 4920 ops->hotplug_seq = *(u64 *)(udata + moff); 4921 return 1; 4922 } 4923 4924 return 0; 4925 } 4926 4927 static int bpf_scx_check_member(const struct btf_type *t, 4928 const struct btf_member *member, 4929 const struct bpf_prog *prog) 4930 { 4931 u32 moff = __btf_member_bit_offset(t, member) / 8; 4932 4933 switch (moff) { 4934 case offsetof(struct sched_ext_ops, init_task): 4935 #ifdef CONFIG_EXT_GROUP_SCHED 4936 case offsetof(struct sched_ext_ops, cgroup_init): 4937 case offsetof(struct sched_ext_ops, cgroup_exit): 4938 case offsetof(struct sched_ext_ops, cgroup_prep_move): 4939 #endif 4940 case offsetof(struct sched_ext_ops, cpu_online): 4941 case offsetof(struct sched_ext_ops, cpu_offline): 4942 case offsetof(struct sched_ext_ops, init): 4943 case offsetof(struct sched_ext_ops, exit): 4944 break; 4945 default: 4946 if (prog->sleepable) 4947 return -EINVAL; 4948 } 4949 4950 return 0; 4951 } 4952 4953 static int bpf_scx_reg(void *kdata, struct bpf_link *link) 4954 { 4955 return scx_enable(kdata, link); 4956 } 4957 4958 static void bpf_scx_unreg(void *kdata, struct bpf_link *link) 4959 { 4960 struct sched_ext_ops *ops = kdata; 4961 struct scx_sched *sch = ops->priv; 4962 4963 scx_disable(SCX_EXIT_UNREG); 4964 kthread_flush_work(&sch->disable_work); 4965 kobject_put(&sch->kobj); 4966 } 4967 4968 static int bpf_scx_init(struct btf *btf) 4969 { 4970 task_struct_type = btf_type_by_id(btf, btf_tracing_ids[BTF_TRACING_TYPE_TASK]); 4971 4972 return 0; 4973 } 4974 4975 static int bpf_scx_update(void *kdata, void *old_kdata, struct bpf_link *link) 4976 { 4977 /* 4978 * sched_ext does not support updating the actively-loaded BPF 4979 * scheduler, as registering a BPF scheduler can always fail if the 4980 * scheduler returns an error code for e.g. ops.init(), ops.init_task(), 4981 * etc. Similarly, we can always race with unregistration happening 4982 * elsewhere, such as with sysrq. 4983 */ 4984 return -EOPNOTSUPP; 4985 } 4986 4987 static int bpf_scx_validate(void *kdata) 4988 { 4989 return 0; 4990 } 4991 4992 static s32 sched_ext_ops__select_cpu(struct task_struct *p, s32 prev_cpu, u64 wake_flags) { return -EINVAL; } 4993 static void sched_ext_ops__enqueue(struct task_struct *p, u64 enq_flags) {} 4994 static void sched_ext_ops__dequeue(struct task_struct *p, u64 enq_flags) {} 4995 static void sched_ext_ops__dispatch(s32 prev_cpu, struct task_struct *prev__nullable) {} 4996 static void sched_ext_ops__tick(struct task_struct *p) {} 4997 static void sched_ext_ops__runnable(struct task_struct *p, u64 enq_flags) {} 4998 static void sched_ext_ops__running(struct task_struct *p) {} 4999 static void sched_ext_ops__stopping(struct task_struct *p, bool runnable) {} 5000 static void sched_ext_ops__quiescent(struct task_struct *p, u64 deq_flags) {} 5001 static bool sched_ext_ops__yield(struct task_struct *from, struct task_struct *to__nullable) { return false; } 5002 static bool sched_ext_ops__core_sched_before(struct task_struct *a, struct task_struct *b) { return false; } 5003 static void sched_ext_ops__set_weight(struct task_struct *p, u32 weight) {} 5004 static void sched_ext_ops__set_cpumask(struct task_struct *p, const struct cpumask *mask) {} 5005 static void sched_ext_ops__update_idle(s32 cpu, bool idle) {} 5006 static void sched_ext_ops__cpu_acquire(s32 cpu, struct scx_cpu_acquire_args *args) {} 5007 static void sched_ext_ops__cpu_release(s32 cpu, struct scx_cpu_release_args *args) {} 5008 static s32 sched_ext_ops__init_task(struct task_struct *p, struct scx_init_task_args *args) { return -EINVAL; } 5009 static void sched_ext_ops__exit_task(struct task_struct *p, struct scx_exit_task_args *args) {} 5010 static void sched_ext_ops__enable(struct task_struct *p) {} 5011 static void sched_ext_ops__disable(struct task_struct *p) {} 5012 #ifdef CONFIG_EXT_GROUP_SCHED 5013 static s32 sched_ext_ops__cgroup_init(struct cgroup *cgrp, struct scx_cgroup_init_args *args) { return -EINVAL; } 5014 static void sched_ext_ops__cgroup_exit(struct cgroup *cgrp) {} 5015 static s32 sched_ext_ops__cgroup_prep_move(struct task_struct *p, struct cgroup *from, struct cgroup *to) { return -EINVAL; } 5016 static void sched_ext_ops__cgroup_move(struct task_struct *p, struct cgroup *from, struct cgroup *to) {} 5017 static void sched_ext_ops__cgroup_cancel_move(struct task_struct *p, struct cgroup *from, struct cgroup *to) {} 5018 static void sched_ext_ops__cgroup_set_weight(struct cgroup *cgrp, u32 weight) {} 5019 static void sched_ext_ops__cgroup_set_bandwidth(struct cgroup *cgrp, u64 period_us, u64 quota_us, u64 burst_us) {} 5020 #endif 5021 static void sched_ext_ops__cpu_online(s32 cpu) {} 5022 static void sched_ext_ops__cpu_offline(s32 cpu) {} 5023 static s32 sched_ext_ops__init(void) { return -EINVAL; } 5024 static void sched_ext_ops__exit(struct scx_exit_info *info) {} 5025 static void sched_ext_ops__dump(struct scx_dump_ctx *ctx) {} 5026 static void sched_ext_ops__dump_cpu(struct scx_dump_ctx *ctx, s32 cpu, bool idle) {} 5027 static void sched_ext_ops__dump_task(struct scx_dump_ctx *ctx, struct task_struct *p) {} 5028 5029 static struct sched_ext_ops __bpf_ops_sched_ext_ops = { 5030 .select_cpu = sched_ext_ops__select_cpu, 5031 .enqueue = sched_ext_ops__enqueue, 5032 .dequeue = sched_ext_ops__dequeue, 5033 .dispatch = sched_ext_ops__dispatch, 5034 .tick = sched_ext_ops__tick, 5035 .runnable = sched_ext_ops__runnable, 5036 .running = sched_ext_ops__running, 5037 .stopping = sched_ext_ops__stopping, 5038 .quiescent = sched_ext_ops__quiescent, 5039 .yield = sched_ext_ops__yield, 5040 .core_sched_before = sched_ext_ops__core_sched_before, 5041 .set_weight = sched_ext_ops__set_weight, 5042 .set_cpumask = sched_ext_ops__set_cpumask, 5043 .update_idle = sched_ext_ops__update_idle, 5044 .cpu_acquire = sched_ext_ops__cpu_acquire, 5045 .cpu_release = sched_ext_ops__cpu_release, 5046 .init_task = sched_ext_ops__init_task, 5047 .exit_task = sched_ext_ops__exit_task, 5048 .enable = sched_ext_ops__enable, 5049 .disable = sched_ext_ops__disable, 5050 #ifdef CONFIG_EXT_GROUP_SCHED 5051 .cgroup_init = sched_ext_ops__cgroup_init, 5052 .cgroup_exit = sched_ext_ops__cgroup_exit, 5053 .cgroup_prep_move = sched_ext_ops__cgroup_prep_move, 5054 .cgroup_move = sched_ext_ops__cgroup_move, 5055 .cgroup_cancel_move = sched_ext_ops__cgroup_cancel_move, 5056 .cgroup_set_weight = sched_ext_ops__cgroup_set_weight, 5057 .cgroup_set_bandwidth = sched_ext_ops__cgroup_set_bandwidth, 5058 #endif 5059 .cpu_online = sched_ext_ops__cpu_online, 5060 .cpu_offline = sched_ext_ops__cpu_offline, 5061 .init = sched_ext_ops__init, 5062 .exit = sched_ext_ops__exit, 5063 .dump = sched_ext_ops__dump, 5064 .dump_cpu = sched_ext_ops__dump_cpu, 5065 .dump_task = sched_ext_ops__dump_task, 5066 }; 5067 5068 static struct bpf_struct_ops bpf_sched_ext_ops = { 5069 .verifier_ops = &bpf_scx_verifier_ops, 5070 .reg = bpf_scx_reg, 5071 .unreg = bpf_scx_unreg, 5072 .check_member = bpf_scx_check_member, 5073 .init_member = bpf_scx_init_member, 5074 .init = bpf_scx_init, 5075 .update = bpf_scx_update, 5076 .validate = bpf_scx_validate, 5077 .name = "sched_ext_ops", 5078 .owner = THIS_MODULE, 5079 .cfi_stubs = &__bpf_ops_sched_ext_ops 5080 }; 5081 5082 5083 /******************************************************************************** 5084 * System integration and init. 5085 */ 5086 5087 static void sysrq_handle_sched_ext_reset(u8 key) 5088 { 5089 scx_disable(SCX_EXIT_SYSRQ); 5090 } 5091 5092 static const struct sysrq_key_op sysrq_sched_ext_reset_op = { 5093 .handler = sysrq_handle_sched_ext_reset, 5094 .help_msg = "reset-sched-ext(S)", 5095 .action_msg = "Disable sched_ext and revert all tasks to CFS", 5096 .enable_mask = SYSRQ_ENABLE_RTNICE, 5097 }; 5098 5099 static void sysrq_handle_sched_ext_dump(u8 key) 5100 { 5101 struct scx_exit_info ei = { .kind = SCX_EXIT_NONE, .reason = "SysRq-D" }; 5102 5103 if (scx_enabled()) 5104 scx_dump_state(&ei, 0); 5105 } 5106 5107 static const struct sysrq_key_op sysrq_sched_ext_dump_op = { 5108 .handler = sysrq_handle_sched_ext_dump, 5109 .help_msg = "dump-sched-ext(D)", 5110 .action_msg = "Trigger sched_ext debug dump", 5111 .enable_mask = SYSRQ_ENABLE_RTNICE, 5112 }; 5113 5114 static bool can_skip_idle_kick(struct rq *rq) 5115 { 5116 lockdep_assert_rq_held(rq); 5117 5118 /* 5119 * We can skip idle kicking if @rq is going to go through at least one 5120 * full SCX scheduling cycle before going idle. Just checking whether 5121 * curr is not idle is insufficient because we could be racing 5122 * balance_one() trying to pull the next task from a remote rq, which 5123 * may fail, and @rq may become idle afterwards. 5124 * 5125 * The race window is small and we don't and can't guarantee that @rq is 5126 * only kicked while idle anyway. Skip only when sure. 5127 */ 5128 return !is_idle_task(rq->curr) && !(rq->scx.flags & SCX_RQ_IN_BALANCE); 5129 } 5130 5131 static bool kick_one_cpu(s32 cpu, struct rq *this_rq, unsigned long *pseqs) 5132 { 5133 struct rq *rq = cpu_rq(cpu); 5134 struct scx_rq *this_scx = &this_rq->scx; 5135 bool should_wait = false; 5136 unsigned long flags; 5137 5138 raw_spin_rq_lock_irqsave(rq, flags); 5139 5140 /* 5141 * During CPU hotplug, a CPU may depend on kicking itself to make 5142 * forward progress. Allow kicking self regardless of online state. 5143 */ 5144 if (cpu_online(cpu) || cpu == cpu_of(this_rq)) { 5145 if (cpumask_test_cpu(cpu, this_scx->cpus_to_preempt)) { 5146 if (rq->curr->sched_class == &ext_sched_class) 5147 rq->curr->scx.slice = 0; 5148 cpumask_clear_cpu(cpu, this_scx->cpus_to_preempt); 5149 } 5150 5151 if (cpumask_test_cpu(cpu, this_scx->cpus_to_wait)) { 5152 pseqs[cpu] = rq->scx.pnt_seq; 5153 should_wait = true; 5154 } 5155 5156 resched_curr(rq); 5157 } else { 5158 cpumask_clear_cpu(cpu, this_scx->cpus_to_preempt); 5159 cpumask_clear_cpu(cpu, this_scx->cpus_to_wait); 5160 } 5161 5162 raw_spin_rq_unlock_irqrestore(rq, flags); 5163 5164 return should_wait; 5165 } 5166 5167 static void kick_one_cpu_if_idle(s32 cpu, struct rq *this_rq) 5168 { 5169 struct rq *rq = cpu_rq(cpu); 5170 unsigned long flags; 5171 5172 raw_spin_rq_lock_irqsave(rq, flags); 5173 5174 if (!can_skip_idle_kick(rq) && 5175 (cpu_online(cpu) || cpu == cpu_of(this_rq))) 5176 resched_curr(rq); 5177 5178 raw_spin_rq_unlock_irqrestore(rq, flags); 5179 } 5180 5181 static void kick_cpus_irq_workfn(struct irq_work *irq_work) 5182 { 5183 struct rq *this_rq = this_rq(); 5184 struct scx_rq *this_scx = &this_rq->scx; 5185 struct scx_kick_pseqs __rcu *pseqs_pcpu = __this_cpu_read(scx_kick_pseqs); 5186 bool should_wait = false; 5187 unsigned long *pseqs; 5188 s32 cpu; 5189 5190 if (unlikely(!pseqs_pcpu)) { 5191 pr_warn_once("kick_cpus_irq_workfn() called with NULL scx_kick_pseqs"); 5192 return; 5193 } 5194 5195 pseqs = rcu_dereference_bh(pseqs_pcpu)->seqs; 5196 5197 for_each_cpu(cpu, this_scx->cpus_to_kick) { 5198 should_wait |= kick_one_cpu(cpu, this_rq, pseqs); 5199 cpumask_clear_cpu(cpu, this_scx->cpus_to_kick); 5200 cpumask_clear_cpu(cpu, this_scx->cpus_to_kick_if_idle); 5201 } 5202 5203 for_each_cpu(cpu, this_scx->cpus_to_kick_if_idle) { 5204 kick_one_cpu_if_idle(cpu, this_rq); 5205 cpumask_clear_cpu(cpu, this_scx->cpus_to_kick_if_idle); 5206 } 5207 5208 if (!should_wait) 5209 return; 5210 5211 for_each_cpu(cpu, this_scx->cpus_to_wait) { 5212 unsigned long *wait_pnt_seq = &cpu_rq(cpu)->scx.pnt_seq; 5213 5214 if (cpu != cpu_of(this_rq)) { 5215 /* 5216 * Pairs with smp_store_release() issued by this CPU in 5217 * switch_class() on the resched path. 5218 * 5219 * We busy-wait here to guarantee that no other task can 5220 * be scheduled on our core before the target CPU has 5221 * entered the resched path. 5222 */ 5223 while (smp_load_acquire(wait_pnt_seq) == pseqs[cpu]) 5224 cpu_relax(); 5225 } 5226 5227 cpumask_clear_cpu(cpu, this_scx->cpus_to_wait); 5228 } 5229 } 5230 5231 /** 5232 * print_scx_info - print out sched_ext scheduler state 5233 * @log_lvl: the log level to use when printing 5234 * @p: target task 5235 * 5236 * If a sched_ext scheduler is enabled, print the name and state of the 5237 * scheduler. If @p is on sched_ext, print further information about the task. 5238 * 5239 * This function can be safely called on any task as long as the task_struct 5240 * itself is accessible. While safe, this function isn't synchronized and may 5241 * print out mixups or garbages of limited length. 5242 */ 5243 void print_scx_info(const char *log_lvl, struct task_struct *p) 5244 { 5245 struct scx_sched *sch = scx_root; 5246 enum scx_enable_state state = scx_enable_state(); 5247 const char *all = READ_ONCE(scx_switching_all) ? "+all" : ""; 5248 char runnable_at_buf[22] = "?"; 5249 struct sched_class *class; 5250 unsigned long runnable_at; 5251 5252 if (state == SCX_DISABLED) 5253 return; 5254 5255 /* 5256 * Carefully check if the task was running on sched_ext, and then 5257 * carefully copy the time it's been runnable, and its state. 5258 */ 5259 if (copy_from_kernel_nofault(&class, &p->sched_class, sizeof(class)) || 5260 class != &ext_sched_class) { 5261 printk("%sSched_ext: %s (%s%s)", log_lvl, sch->ops.name, 5262 scx_enable_state_str[state], all); 5263 return; 5264 } 5265 5266 if (!copy_from_kernel_nofault(&runnable_at, &p->scx.runnable_at, 5267 sizeof(runnable_at))) 5268 scnprintf(runnable_at_buf, sizeof(runnable_at_buf), "%+ldms", 5269 jiffies_delta_msecs(runnable_at, jiffies)); 5270 5271 /* print everything onto one line to conserve console space */ 5272 printk("%sSched_ext: %s (%s%s), task: runnable_at=%s", 5273 log_lvl, sch->ops.name, scx_enable_state_str[state], all, 5274 runnable_at_buf); 5275 } 5276 5277 static int scx_pm_handler(struct notifier_block *nb, unsigned long event, void *ptr) 5278 { 5279 /* 5280 * SCX schedulers often have userspace components which are sometimes 5281 * involved in critial scheduling paths. PM operations involve freezing 5282 * userspace which can lead to scheduling misbehaviors including stalls. 5283 * Let's bypass while PM operations are in progress. 5284 */ 5285 switch (event) { 5286 case PM_HIBERNATION_PREPARE: 5287 case PM_SUSPEND_PREPARE: 5288 case PM_RESTORE_PREPARE: 5289 scx_bypass(true); 5290 break; 5291 case PM_POST_HIBERNATION: 5292 case PM_POST_SUSPEND: 5293 case PM_POST_RESTORE: 5294 scx_bypass(false); 5295 break; 5296 } 5297 5298 return NOTIFY_OK; 5299 } 5300 5301 static struct notifier_block scx_pm_notifier = { 5302 .notifier_call = scx_pm_handler, 5303 }; 5304 5305 void __init init_sched_ext_class(void) 5306 { 5307 s32 cpu, v; 5308 5309 /* 5310 * The following is to prevent the compiler from optimizing out the enum 5311 * definitions so that BPF scheduler implementations can use them 5312 * through the generated vmlinux.h. 5313 */ 5314 WRITE_ONCE(v, SCX_ENQ_WAKEUP | SCX_DEQ_SLEEP | SCX_KICK_PREEMPT | 5315 SCX_TG_ONLINE); 5316 5317 scx_idle_init_masks(); 5318 5319 for_each_possible_cpu(cpu) { 5320 struct rq *rq = cpu_rq(cpu); 5321 int n = cpu_to_node(cpu); 5322 5323 init_dsq(&rq->scx.local_dsq, SCX_DSQ_LOCAL); 5324 INIT_LIST_HEAD(&rq->scx.runnable_list); 5325 INIT_LIST_HEAD(&rq->scx.ddsp_deferred_locals); 5326 5327 BUG_ON(!zalloc_cpumask_var_node(&rq->scx.cpus_to_kick, GFP_KERNEL, n)); 5328 BUG_ON(!zalloc_cpumask_var_node(&rq->scx.cpus_to_kick_if_idle, GFP_KERNEL, n)); 5329 BUG_ON(!zalloc_cpumask_var_node(&rq->scx.cpus_to_preempt, GFP_KERNEL, n)); 5330 BUG_ON(!zalloc_cpumask_var_node(&rq->scx.cpus_to_wait, GFP_KERNEL, n)); 5331 init_irq_work(&rq->scx.deferred_irq_work, deferred_irq_workfn); 5332 init_irq_work(&rq->scx.kick_cpus_irq_work, kick_cpus_irq_workfn); 5333 5334 if (cpu_online(cpu)) 5335 cpu_rq(cpu)->scx.flags |= SCX_RQ_ONLINE; 5336 } 5337 5338 register_sysrq_key('S', &sysrq_sched_ext_reset_op); 5339 register_sysrq_key('D', &sysrq_sched_ext_dump_op); 5340 INIT_DELAYED_WORK(&scx_watchdog_work, scx_watchdog_workfn); 5341 } 5342 5343 5344 /******************************************************************************** 5345 * Helpers that can be called from the BPF scheduler. 5346 */ 5347 static bool scx_dsq_insert_preamble(struct scx_sched *sch, struct task_struct *p, 5348 u64 enq_flags) 5349 { 5350 if (!scx_kf_allowed(sch, SCX_KF_ENQUEUE | SCX_KF_DISPATCH)) 5351 return false; 5352 5353 lockdep_assert_irqs_disabled(); 5354 5355 if (unlikely(!p)) { 5356 scx_error(sch, "called with NULL task"); 5357 return false; 5358 } 5359 5360 if (unlikely(enq_flags & __SCX_ENQ_INTERNAL_MASK)) { 5361 scx_error(sch, "invalid enq_flags 0x%llx", enq_flags); 5362 return false; 5363 } 5364 5365 return true; 5366 } 5367 5368 static void scx_dsq_insert_commit(struct scx_sched *sch, struct task_struct *p, 5369 u64 dsq_id, u64 enq_flags) 5370 { 5371 struct scx_dsp_ctx *dspc = this_cpu_ptr(scx_dsp_ctx); 5372 struct task_struct *ddsp_task; 5373 5374 ddsp_task = __this_cpu_read(direct_dispatch_task); 5375 if (ddsp_task) { 5376 mark_direct_dispatch(sch, ddsp_task, p, dsq_id, enq_flags); 5377 return; 5378 } 5379 5380 if (unlikely(dspc->cursor >= scx_dsp_max_batch)) { 5381 scx_error(sch, "dispatch buffer overflow"); 5382 return; 5383 } 5384 5385 dspc->buf[dspc->cursor++] = (struct scx_dsp_buf_ent){ 5386 .task = p, 5387 .qseq = atomic_long_read(&p->scx.ops_state) & SCX_OPSS_QSEQ_MASK, 5388 .dsq_id = dsq_id, 5389 .enq_flags = enq_flags, 5390 }; 5391 } 5392 5393 __bpf_kfunc_start_defs(); 5394 5395 /** 5396 * scx_bpf_dsq_insert - Insert a task into the FIFO queue of a DSQ 5397 * @p: task_struct to insert 5398 * @dsq_id: DSQ to insert into 5399 * @slice: duration @p can run for in nsecs, 0 to keep the current value 5400 * @enq_flags: SCX_ENQ_* 5401 * 5402 * Insert @p into the FIFO queue of the DSQ identified by @dsq_id. It is safe to 5403 * call this function spuriously. Can be called from ops.enqueue(), 5404 * ops.select_cpu(), and ops.dispatch(). 5405 * 5406 * When called from ops.select_cpu() or ops.enqueue(), it's for direct dispatch 5407 * and @p must match the task being enqueued. 5408 * 5409 * When called from ops.select_cpu(), @enq_flags and @dsp_id are stored, and @p 5410 * will be directly inserted into the corresponding dispatch queue after 5411 * ops.select_cpu() returns. If @p is inserted into SCX_DSQ_LOCAL, it will be 5412 * inserted into the local DSQ of the CPU returned by ops.select_cpu(). 5413 * @enq_flags are OR'd with the enqueue flags on the enqueue path before the 5414 * task is inserted. 5415 * 5416 * When called from ops.dispatch(), there are no restrictions on @p or @dsq_id 5417 * and this function can be called upto ops.dispatch_max_batch times to insert 5418 * multiple tasks. scx_bpf_dispatch_nr_slots() returns the number of the 5419 * remaining slots. scx_bpf_dsq_move_to_local() flushes the batch and resets the 5420 * counter. 5421 * 5422 * This function doesn't have any locking restrictions and may be called under 5423 * BPF locks (in the future when BPF introduces more flexible locking). 5424 * 5425 * @p is allowed to run for @slice. The scheduling path is triggered on slice 5426 * exhaustion. If zero, the current residual slice is maintained. If 5427 * %SCX_SLICE_INF, @p never expires and the BPF scheduler must kick the CPU with 5428 * scx_bpf_kick_cpu() to trigger scheduling. 5429 */ 5430 __bpf_kfunc void scx_bpf_dsq_insert(struct task_struct *p, u64 dsq_id, u64 slice, 5431 u64 enq_flags) 5432 { 5433 struct scx_sched *sch; 5434 5435 guard(rcu)(); 5436 sch = rcu_dereference(scx_root); 5437 if (unlikely(!sch)) 5438 return; 5439 5440 if (!scx_dsq_insert_preamble(sch, p, enq_flags)) 5441 return; 5442 5443 if (slice) 5444 p->scx.slice = slice; 5445 else 5446 p->scx.slice = p->scx.slice ?: 1; 5447 5448 scx_dsq_insert_commit(sch, p, dsq_id, enq_flags); 5449 } 5450 5451 /** 5452 * scx_bpf_dsq_insert_vtime - Insert a task into the vtime priority queue of a DSQ 5453 * @p: task_struct to insert 5454 * @dsq_id: DSQ to insert into 5455 * @slice: duration @p can run for in nsecs, 0 to keep the current value 5456 * @vtime: @p's ordering inside the vtime-sorted queue of the target DSQ 5457 * @enq_flags: SCX_ENQ_* 5458 * 5459 * Insert @p into the vtime priority queue of the DSQ identified by @dsq_id. 5460 * Tasks queued into the priority queue are ordered by @vtime. All other aspects 5461 * are identical to scx_bpf_dsq_insert(). 5462 * 5463 * @vtime ordering is according to time_before64() which considers wrapping. A 5464 * numerically larger vtime may indicate an earlier position in the ordering and 5465 * vice-versa. 5466 * 5467 * A DSQ can only be used as a FIFO or priority queue at any given time and this 5468 * function must not be called on a DSQ which already has one or more FIFO tasks 5469 * queued and vice-versa. Also, the built-in DSQs (SCX_DSQ_LOCAL and 5470 * SCX_DSQ_GLOBAL) cannot be used as priority queues. 5471 */ 5472 __bpf_kfunc void scx_bpf_dsq_insert_vtime(struct task_struct *p, u64 dsq_id, 5473 u64 slice, u64 vtime, u64 enq_flags) 5474 { 5475 struct scx_sched *sch; 5476 5477 guard(rcu)(); 5478 sch = rcu_dereference(scx_root); 5479 if (unlikely(!sch)) 5480 return; 5481 5482 if (!scx_dsq_insert_preamble(sch, p, enq_flags)) 5483 return; 5484 5485 if (slice) 5486 p->scx.slice = slice; 5487 else 5488 p->scx.slice = p->scx.slice ?: 1; 5489 5490 p->scx.dsq_vtime = vtime; 5491 5492 scx_dsq_insert_commit(sch, p, dsq_id, enq_flags | SCX_ENQ_DSQ_PRIQ); 5493 } 5494 5495 __bpf_kfunc_end_defs(); 5496 5497 BTF_KFUNCS_START(scx_kfunc_ids_enqueue_dispatch) 5498 BTF_ID_FLAGS(func, scx_bpf_dsq_insert, KF_RCU) 5499 BTF_ID_FLAGS(func, scx_bpf_dsq_insert_vtime, KF_RCU) 5500 BTF_KFUNCS_END(scx_kfunc_ids_enqueue_dispatch) 5501 5502 static const struct btf_kfunc_id_set scx_kfunc_set_enqueue_dispatch = { 5503 .owner = THIS_MODULE, 5504 .set = &scx_kfunc_ids_enqueue_dispatch, 5505 }; 5506 5507 static bool scx_dsq_move(struct bpf_iter_scx_dsq_kern *kit, 5508 struct task_struct *p, u64 dsq_id, u64 enq_flags) 5509 { 5510 struct scx_sched *sch = scx_root; 5511 struct scx_dispatch_q *src_dsq = kit->dsq, *dst_dsq; 5512 struct rq *this_rq, *src_rq, *locked_rq; 5513 bool dispatched = false; 5514 bool in_balance; 5515 unsigned long flags; 5516 5517 if (!scx_kf_allowed_if_unlocked() && 5518 !scx_kf_allowed(sch, SCX_KF_DISPATCH)) 5519 return false; 5520 5521 /* 5522 * Can be called from either ops.dispatch() locking this_rq() or any 5523 * context where no rq lock is held. If latter, lock @p's task_rq which 5524 * we'll likely need anyway. 5525 */ 5526 src_rq = task_rq(p); 5527 5528 local_irq_save(flags); 5529 this_rq = this_rq(); 5530 in_balance = this_rq->scx.flags & SCX_RQ_IN_BALANCE; 5531 5532 if (in_balance) { 5533 if (this_rq != src_rq) { 5534 raw_spin_rq_unlock(this_rq); 5535 raw_spin_rq_lock(src_rq); 5536 } 5537 } else { 5538 raw_spin_rq_lock(src_rq); 5539 } 5540 5541 /* 5542 * If the BPF scheduler keeps calling this function repeatedly, it can 5543 * cause similar live-lock conditions as consume_dispatch_q(). Insert a 5544 * breather if necessary. 5545 */ 5546 scx_breather(src_rq); 5547 5548 locked_rq = src_rq; 5549 raw_spin_lock(&src_dsq->lock); 5550 5551 /* 5552 * Did someone else get to it? @p could have already left $src_dsq, got 5553 * re-enqueud, or be in the process of being consumed by someone else. 5554 */ 5555 if (unlikely(p->scx.dsq != src_dsq || 5556 u32_before(kit->cursor.priv, p->scx.dsq_seq) || 5557 p->scx.holding_cpu >= 0) || 5558 WARN_ON_ONCE(src_rq != task_rq(p))) { 5559 raw_spin_unlock(&src_dsq->lock); 5560 goto out; 5561 } 5562 5563 /* @p is still on $src_dsq and stable, determine the destination */ 5564 dst_dsq = find_dsq_for_dispatch(sch, this_rq, dsq_id, p); 5565 5566 /* 5567 * Apply vtime and slice updates before moving so that the new time is 5568 * visible before inserting into $dst_dsq. @p is still on $src_dsq but 5569 * this is safe as we're locking it. 5570 */ 5571 if (kit->cursor.flags & __SCX_DSQ_ITER_HAS_VTIME) 5572 p->scx.dsq_vtime = kit->vtime; 5573 if (kit->cursor.flags & __SCX_DSQ_ITER_HAS_SLICE) 5574 p->scx.slice = kit->slice; 5575 5576 /* execute move */ 5577 locked_rq = move_task_between_dsqs(sch, p, enq_flags, src_dsq, dst_dsq); 5578 dispatched = true; 5579 out: 5580 if (in_balance) { 5581 if (this_rq != locked_rq) { 5582 raw_spin_rq_unlock(locked_rq); 5583 raw_spin_rq_lock(this_rq); 5584 } 5585 } else { 5586 raw_spin_rq_unlock_irqrestore(locked_rq, flags); 5587 } 5588 5589 kit->cursor.flags &= ~(__SCX_DSQ_ITER_HAS_SLICE | 5590 __SCX_DSQ_ITER_HAS_VTIME); 5591 return dispatched; 5592 } 5593 5594 __bpf_kfunc_start_defs(); 5595 5596 /** 5597 * scx_bpf_dispatch_nr_slots - Return the number of remaining dispatch slots 5598 * 5599 * Can only be called from ops.dispatch(). 5600 */ 5601 __bpf_kfunc u32 scx_bpf_dispatch_nr_slots(void) 5602 { 5603 struct scx_sched *sch; 5604 5605 guard(rcu)(); 5606 5607 sch = rcu_dereference(scx_root); 5608 if (unlikely(!sch)) 5609 return 0; 5610 5611 if (!scx_kf_allowed(sch, SCX_KF_DISPATCH)) 5612 return 0; 5613 5614 return scx_dsp_max_batch - __this_cpu_read(scx_dsp_ctx->cursor); 5615 } 5616 5617 /** 5618 * scx_bpf_dispatch_cancel - Cancel the latest dispatch 5619 * 5620 * Cancel the latest dispatch. Can be called multiple times to cancel further 5621 * dispatches. Can only be called from ops.dispatch(). 5622 */ 5623 __bpf_kfunc void scx_bpf_dispatch_cancel(void) 5624 { 5625 struct scx_dsp_ctx *dspc = this_cpu_ptr(scx_dsp_ctx); 5626 struct scx_sched *sch; 5627 5628 guard(rcu)(); 5629 5630 sch = rcu_dereference(scx_root); 5631 if (unlikely(!sch)) 5632 return; 5633 5634 if (!scx_kf_allowed(sch, SCX_KF_DISPATCH)) 5635 return; 5636 5637 if (dspc->cursor > 0) 5638 dspc->cursor--; 5639 else 5640 scx_error(sch, "dispatch buffer underflow"); 5641 } 5642 5643 /** 5644 * scx_bpf_dsq_move_to_local - move a task from a DSQ to the current CPU's local DSQ 5645 * @dsq_id: DSQ to move task from 5646 * 5647 * Move a task from the non-local DSQ identified by @dsq_id to the current CPU's 5648 * local DSQ for execution. Can only be called from ops.dispatch(). 5649 * 5650 * This function flushes the in-flight dispatches from scx_bpf_dsq_insert() 5651 * before trying to move from the specified DSQ. It may also grab rq locks and 5652 * thus can't be called under any BPF locks. 5653 * 5654 * Returns %true if a task has been moved, %false if there isn't any task to 5655 * move. 5656 */ 5657 __bpf_kfunc bool scx_bpf_dsq_move_to_local(u64 dsq_id) 5658 { 5659 struct scx_dsp_ctx *dspc = this_cpu_ptr(scx_dsp_ctx); 5660 struct scx_dispatch_q *dsq; 5661 struct scx_sched *sch; 5662 5663 guard(rcu)(); 5664 5665 sch = rcu_dereference(scx_root); 5666 if (unlikely(!sch)) 5667 return false; 5668 5669 if (!scx_kf_allowed(sch, SCX_KF_DISPATCH)) 5670 return false; 5671 5672 flush_dispatch_buf(sch, dspc->rq); 5673 5674 dsq = find_user_dsq(sch, dsq_id); 5675 if (unlikely(!dsq)) { 5676 scx_error(sch, "invalid DSQ ID 0x%016llx", dsq_id); 5677 return false; 5678 } 5679 5680 if (consume_dispatch_q(sch, dspc->rq, dsq)) { 5681 /* 5682 * A successfully consumed task can be dequeued before it starts 5683 * running while the CPU is trying to migrate other dispatched 5684 * tasks. Bump nr_tasks to tell balance_scx() to retry on empty 5685 * local DSQ. 5686 */ 5687 dspc->nr_tasks++; 5688 return true; 5689 } else { 5690 return false; 5691 } 5692 } 5693 5694 /** 5695 * scx_bpf_dsq_move_set_slice - Override slice when moving between DSQs 5696 * @it__iter: DSQ iterator in progress 5697 * @slice: duration the moved task can run for in nsecs 5698 * 5699 * Override the slice of the next task that will be moved from @it__iter using 5700 * scx_bpf_dsq_move[_vtime](). If this function is not called, the previous 5701 * slice duration is kept. 5702 */ 5703 __bpf_kfunc void scx_bpf_dsq_move_set_slice(struct bpf_iter_scx_dsq *it__iter, 5704 u64 slice) 5705 { 5706 struct bpf_iter_scx_dsq_kern *kit = (void *)it__iter; 5707 5708 kit->slice = slice; 5709 kit->cursor.flags |= __SCX_DSQ_ITER_HAS_SLICE; 5710 } 5711 5712 /** 5713 * scx_bpf_dsq_move_set_vtime - Override vtime when moving between DSQs 5714 * @it__iter: DSQ iterator in progress 5715 * @vtime: task's ordering inside the vtime-sorted queue of the target DSQ 5716 * 5717 * Override the vtime of the next task that will be moved from @it__iter using 5718 * scx_bpf_dsq_move_vtime(). If this function is not called, the previous slice 5719 * vtime is kept. If scx_bpf_dsq_move() is used to dispatch the next task, the 5720 * override is ignored and cleared. 5721 */ 5722 __bpf_kfunc void scx_bpf_dsq_move_set_vtime(struct bpf_iter_scx_dsq *it__iter, 5723 u64 vtime) 5724 { 5725 struct bpf_iter_scx_dsq_kern *kit = (void *)it__iter; 5726 5727 kit->vtime = vtime; 5728 kit->cursor.flags |= __SCX_DSQ_ITER_HAS_VTIME; 5729 } 5730 5731 /** 5732 * scx_bpf_dsq_move - Move a task from DSQ iteration to a DSQ 5733 * @it__iter: DSQ iterator in progress 5734 * @p: task to transfer 5735 * @dsq_id: DSQ to move @p to 5736 * @enq_flags: SCX_ENQ_* 5737 * 5738 * Transfer @p which is on the DSQ currently iterated by @it__iter to the DSQ 5739 * specified by @dsq_id. All DSQs - local DSQs, global DSQ and user DSQs - can 5740 * be the destination. 5741 * 5742 * For the transfer to be successful, @p must still be on the DSQ and have been 5743 * queued before the DSQ iteration started. This function doesn't care whether 5744 * @p was obtained from the DSQ iteration. @p just has to be on the DSQ and have 5745 * been queued before the iteration started. 5746 * 5747 * @p's slice is kept by default. Use scx_bpf_dsq_move_set_slice() to update. 5748 * 5749 * Can be called from ops.dispatch() or any BPF context which doesn't hold a rq 5750 * lock (e.g. BPF timers or SYSCALL programs). 5751 * 5752 * Returns %true if @p has been consumed, %false if @p had already been consumed 5753 * or dequeued. 5754 */ 5755 __bpf_kfunc bool scx_bpf_dsq_move(struct bpf_iter_scx_dsq *it__iter, 5756 struct task_struct *p, u64 dsq_id, 5757 u64 enq_flags) 5758 { 5759 return scx_dsq_move((struct bpf_iter_scx_dsq_kern *)it__iter, 5760 p, dsq_id, enq_flags); 5761 } 5762 5763 /** 5764 * scx_bpf_dsq_move_vtime - Move a task from DSQ iteration to a PRIQ DSQ 5765 * @it__iter: DSQ iterator in progress 5766 * @p: task to transfer 5767 * @dsq_id: DSQ to move @p to 5768 * @enq_flags: SCX_ENQ_* 5769 * 5770 * Transfer @p which is on the DSQ currently iterated by @it__iter to the 5771 * priority queue of the DSQ specified by @dsq_id. The destination must be a 5772 * user DSQ as only user DSQs support priority queue. 5773 * 5774 * @p's slice and vtime are kept by default. Use scx_bpf_dsq_move_set_slice() 5775 * and scx_bpf_dsq_move_set_vtime() to update. 5776 * 5777 * All other aspects are identical to scx_bpf_dsq_move(). See 5778 * scx_bpf_dsq_insert_vtime() for more information on @vtime. 5779 */ 5780 __bpf_kfunc bool scx_bpf_dsq_move_vtime(struct bpf_iter_scx_dsq *it__iter, 5781 struct task_struct *p, u64 dsq_id, 5782 u64 enq_flags) 5783 { 5784 return scx_dsq_move((struct bpf_iter_scx_dsq_kern *)it__iter, 5785 p, dsq_id, enq_flags | SCX_ENQ_DSQ_PRIQ); 5786 } 5787 5788 __bpf_kfunc_end_defs(); 5789 5790 BTF_KFUNCS_START(scx_kfunc_ids_dispatch) 5791 BTF_ID_FLAGS(func, scx_bpf_dispatch_nr_slots) 5792 BTF_ID_FLAGS(func, scx_bpf_dispatch_cancel) 5793 BTF_ID_FLAGS(func, scx_bpf_dsq_move_to_local) 5794 BTF_ID_FLAGS(func, scx_bpf_dsq_move_set_slice, KF_RCU) 5795 BTF_ID_FLAGS(func, scx_bpf_dsq_move_set_vtime, KF_RCU) 5796 BTF_ID_FLAGS(func, scx_bpf_dsq_move, KF_RCU) 5797 BTF_ID_FLAGS(func, scx_bpf_dsq_move_vtime, KF_RCU) 5798 BTF_KFUNCS_END(scx_kfunc_ids_dispatch) 5799 5800 static const struct btf_kfunc_id_set scx_kfunc_set_dispatch = { 5801 .owner = THIS_MODULE, 5802 .set = &scx_kfunc_ids_dispatch, 5803 }; 5804 5805 __bpf_kfunc_start_defs(); 5806 5807 /** 5808 * scx_bpf_reenqueue_local - Re-enqueue tasks on a local DSQ 5809 * 5810 * Iterate over all of the tasks currently enqueued on the local DSQ of the 5811 * caller's CPU, and re-enqueue them in the BPF scheduler. Returns the number of 5812 * processed tasks. Can only be called from ops.cpu_release(). 5813 */ 5814 __bpf_kfunc u32 scx_bpf_reenqueue_local(void) 5815 { 5816 struct scx_sched *sch; 5817 LIST_HEAD(tasks); 5818 u32 nr_enqueued = 0; 5819 struct rq *rq; 5820 struct task_struct *p, *n; 5821 5822 guard(rcu)(); 5823 sch = rcu_dereference(scx_root); 5824 if (unlikely(!sch)) 5825 return 0; 5826 5827 if (!scx_kf_allowed(sch, SCX_KF_CPU_RELEASE)) 5828 return 0; 5829 5830 rq = cpu_rq(smp_processor_id()); 5831 lockdep_assert_rq_held(rq); 5832 5833 /* 5834 * The BPF scheduler may choose to dispatch tasks back to 5835 * @rq->scx.local_dsq. Move all candidate tasks off to a private list 5836 * first to avoid processing the same tasks repeatedly. 5837 */ 5838 list_for_each_entry_safe(p, n, &rq->scx.local_dsq.list, 5839 scx.dsq_list.node) { 5840 /* 5841 * If @p is being migrated, @p's current CPU may not agree with 5842 * its allowed CPUs and the migration_cpu_stop is about to 5843 * deactivate and re-activate @p anyway. Skip re-enqueueing. 5844 * 5845 * While racing sched property changes may also dequeue and 5846 * re-enqueue a migrating task while its current CPU and allowed 5847 * CPUs disagree, they use %ENQUEUE_RESTORE which is bypassed to 5848 * the current local DSQ for running tasks and thus are not 5849 * visible to the BPF scheduler. 5850 */ 5851 if (p->migration_pending) 5852 continue; 5853 5854 dispatch_dequeue(rq, p); 5855 list_add_tail(&p->scx.dsq_list.node, &tasks); 5856 } 5857 5858 list_for_each_entry_safe(p, n, &tasks, scx.dsq_list.node) { 5859 list_del_init(&p->scx.dsq_list.node); 5860 do_enqueue_task(rq, p, SCX_ENQ_REENQ, -1); 5861 nr_enqueued++; 5862 } 5863 5864 return nr_enqueued; 5865 } 5866 5867 __bpf_kfunc_end_defs(); 5868 5869 BTF_KFUNCS_START(scx_kfunc_ids_cpu_release) 5870 BTF_ID_FLAGS(func, scx_bpf_reenqueue_local) 5871 BTF_KFUNCS_END(scx_kfunc_ids_cpu_release) 5872 5873 static const struct btf_kfunc_id_set scx_kfunc_set_cpu_release = { 5874 .owner = THIS_MODULE, 5875 .set = &scx_kfunc_ids_cpu_release, 5876 }; 5877 5878 __bpf_kfunc_start_defs(); 5879 5880 /** 5881 * scx_bpf_create_dsq - Create a custom DSQ 5882 * @dsq_id: DSQ to create 5883 * @node: NUMA node to allocate from 5884 * 5885 * Create a custom DSQ identified by @dsq_id. Can be called from any sleepable 5886 * scx callback, and any BPF_PROG_TYPE_SYSCALL prog. 5887 */ 5888 __bpf_kfunc s32 scx_bpf_create_dsq(u64 dsq_id, s32 node) 5889 { 5890 struct scx_dispatch_q *dsq; 5891 struct scx_sched *sch; 5892 s32 ret; 5893 5894 if (unlikely(node >= (int)nr_node_ids || 5895 (node < 0 && node != NUMA_NO_NODE))) 5896 return -EINVAL; 5897 5898 if (unlikely(dsq_id & SCX_DSQ_FLAG_BUILTIN)) 5899 return -EINVAL; 5900 5901 dsq = kmalloc_node(sizeof(*dsq), GFP_KERNEL, node); 5902 if (!dsq) 5903 return -ENOMEM; 5904 5905 init_dsq(dsq, dsq_id); 5906 5907 rcu_read_lock(); 5908 5909 sch = rcu_dereference(scx_root); 5910 if (sch) 5911 ret = rhashtable_lookup_insert_fast(&sch->dsq_hash, &dsq->hash_node, 5912 dsq_hash_params); 5913 else 5914 ret = -ENODEV; 5915 5916 rcu_read_unlock(); 5917 if (ret) 5918 kfree(dsq); 5919 return ret; 5920 } 5921 5922 __bpf_kfunc_end_defs(); 5923 5924 BTF_KFUNCS_START(scx_kfunc_ids_unlocked) 5925 BTF_ID_FLAGS(func, scx_bpf_create_dsq, KF_SLEEPABLE) 5926 BTF_ID_FLAGS(func, scx_bpf_dsq_move_set_slice, KF_RCU) 5927 BTF_ID_FLAGS(func, scx_bpf_dsq_move_set_vtime, KF_RCU) 5928 BTF_ID_FLAGS(func, scx_bpf_dsq_move, KF_RCU) 5929 BTF_ID_FLAGS(func, scx_bpf_dsq_move_vtime, KF_RCU) 5930 BTF_KFUNCS_END(scx_kfunc_ids_unlocked) 5931 5932 static const struct btf_kfunc_id_set scx_kfunc_set_unlocked = { 5933 .owner = THIS_MODULE, 5934 .set = &scx_kfunc_ids_unlocked, 5935 }; 5936 5937 __bpf_kfunc_start_defs(); 5938 5939 static void scx_kick_cpu(struct scx_sched *sch, s32 cpu, u64 flags) 5940 { 5941 struct rq *this_rq; 5942 unsigned long irq_flags; 5943 5944 if (!ops_cpu_valid(sch, cpu, NULL)) 5945 return; 5946 5947 local_irq_save(irq_flags); 5948 5949 this_rq = this_rq(); 5950 5951 /* 5952 * While bypassing for PM ops, IRQ handling may not be online which can 5953 * lead to irq_work_queue() malfunction such as infinite busy wait for 5954 * IRQ status update. Suppress kicking. 5955 */ 5956 if (scx_rq_bypassing(this_rq)) 5957 goto out; 5958 5959 /* 5960 * Actual kicking is bounced to kick_cpus_irq_workfn() to avoid nesting 5961 * rq locks. We can probably be smarter and avoid bouncing if called 5962 * from ops which don't hold a rq lock. 5963 */ 5964 if (flags & SCX_KICK_IDLE) { 5965 struct rq *target_rq = cpu_rq(cpu); 5966 5967 if (unlikely(flags & (SCX_KICK_PREEMPT | SCX_KICK_WAIT))) 5968 scx_error(sch, "PREEMPT/WAIT cannot be used with SCX_KICK_IDLE"); 5969 5970 if (raw_spin_rq_trylock(target_rq)) { 5971 if (can_skip_idle_kick(target_rq)) { 5972 raw_spin_rq_unlock(target_rq); 5973 goto out; 5974 } 5975 raw_spin_rq_unlock(target_rq); 5976 } 5977 cpumask_set_cpu(cpu, this_rq->scx.cpus_to_kick_if_idle); 5978 } else { 5979 cpumask_set_cpu(cpu, this_rq->scx.cpus_to_kick); 5980 5981 if (flags & SCX_KICK_PREEMPT) 5982 cpumask_set_cpu(cpu, this_rq->scx.cpus_to_preempt); 5983 if (flags & SCX_KICK_WAIT) 5984 cpumask_set_cpu(cpu, this_rq->scx.cpus_to_wait); 5985 } 5986 5987 irq_work_queue(&this_rq->scx.kick_cpus_irq_work); 5988 out: 5989 local_irq_restore(irq_flags); 5990 } 5991 5992 /** 5993 * scx_bpf_kick_cpu - Trigger reschedule on a CPU 5994 * @cpu: cpu to kick 5995 * @flags: %SCX_KICK_* flags 5996 * 5997 * Kick @cpu into rescheduling. This can be used to wake up an idle CPU or 5998 * trigger rescheduling on a busy CPU. This can be called from any online 5999 * scx_ops operation and the actual kicking is performed asynchronously through 6000 * an irq work. 6001 */ 6002 __bpf_kfunc void scx_bpf_kick_cpu(s32 cpu, u64 flags) 6003 { 6004 struct scx_sched *sch; 6005 6006 guard(rcu)(); 6007 sch = rcu_dereference(scx_root); 6008 if (likely(sch)) 6009 scx_kick_cpu(sch, cpu, flags); 6010 } 6011 6012 /** 6013 * scx_bpf_dsq_nr_queued - Return the number of queued tasks 6014 * @dsq_id: id of the DSQ 6015 * 6016 * Return the number of tasks in the DSQ matching @dsq_id. If not found, 6017 * -%ENOENT is returned. 6018 */ 6019 __bpf_kfunc s32 scx_bpf_dsq_nr_queued(u64 dsq_id) 6020 { 6021 struct scx_sched *sch; 6022 struct scx_dispatch_q *dsq; 6023 s32 ret; 6024 6025 preempt_disable(); 6026 6027 sch = rcu_dereference_sched(scx_root); 6028 if (unlikely(!sch)) { 6029 ret = -ENODEV; 6030 goto out; 6031 } 6032 6033 if (dsq_id == SCX_DSQ_LOCAL) { 6034 ret = READ_ONCE(this_rq()->scx.local_dsq.nr); 6035 goto out; 6036 } else if ((dsq_id & SCX_DSQ_LOCAL_ON) == SCX_DSQ_LOCAL_ON) { 6037 s32 cpu = dsq_id & SCX_DSQ_LOCAL_CPU_MASK; 6038 6039 if (ops_cpu_valid(sch, cpu, NULL)) { 6040 ret = READ_ONCE(cpu_rq(cpu)->scx.local_dsq.nr); 6041 goto out; 6042 } 6043 } else { 6044 dsq = find_user_dsq(sch, dsq_id); 6045 if (dsq) { 6046 ret = READ_ONCE(dsq->nr); 6047 goto out; 6048 } 6049 } 6050 ret = -ENOENT; 6051 out: 6052 preempt_enable(); 6053 return ret; 6054 } 6055 6056 /** 6057 * scx_bpf_destroy_dsq - Destroy a custom DSQ 6058 * @dsq_id: DSQ to destroy 6059 * 6060 * Destroy the custom DSQ identified by @dsq_id. Only DSQs created with 6061 * scx_bpf_create_dsq() can be destroyed. The caller must ensure that the DSQ is 6062 * empty and no further tasks are dispatched to it. Ignored if called on a DSQ 6063 * which doesn't exist. Can be called from any online scx_ops operations. 6064 */ 6065 __bpf_kfunc void scx_bpf_destroy_dsq(u64 dsq_id) 6066 { 6067 struct scx_sched *sch; 6068 6069 rcu_read_lock(); 6070 sch = rcu_dereference(scx_root); 6071 if (sch) 6072 destroy_dsq(sch, dsq_id); 6073 rcu_read_unlock(); 6074 } 6075 6076 /** 6077 * bpf_iter_scx_dsq_new - Create a DSQ iterator 6078 * @it: iterator to initialize 6079 * @dsq_id: DSQ to iterate 6080 * @flags: %SCX_DSQ_ITER_* 6081 * 6082 * Initialize BPF iterator @it which can be used with bpf_for_each() to walk 6083 * tasks in the DSQ specified by @dsq_id. Iteration using @it only includes 6084 * tasks which are already queued when this function is invoked. 6085 */ 6086 __bpf_kfunc int bpf_iter_scx_dsq_new(struct bpf_iter_scx_dsq *it, u64 dsq_id, 6087 u64 flags) 6088 { 6089 struct bpf_iter_scx_dsq_kern *kit = (void *)it; 6090 struct scx_sched *sch; 6091 6092 BUILD_BUG_ON(sizeof(struct bpf_iter_scx_dsq_kern) > 6093 sizeof(struct bpf_iter_scx_dsq)); 6094 BUILD_BUG_ON(__alignof__(struct bpf_iter_scx_dsq_kern) != 6095 __alignof__(struct bpf_iter_scx_dsq)); 6096 6097 /* 6098 * next() and destroy() will be called regardless of the return value. 6099 * Always clear $kit->dsq. 6100 */ 6101 kit->dsq = NULL; 6102 6103 sch = rcu_dereference_check(scx_root, rcu_read_lock_bh_held()); 6104 if (unlikely(!sch)) 6105 return -ENODEV; 6106 6107 if (flags & ~__SCX_DSQ_ITER_USER_FLAGS) 6108 return -EINVAL; 6109 6110 kit->dsq = find_user_dsq(sch, dsq_id); 6111 if (!kit->dsq) 6112 return -ENOENT; 6113 6114 INIT_LIST_HEAD(&kit->cursor.node); 6115 kit->cursor.flags = SCX_DSQ_LNODE_ITER_CURSOR | flags; 6116 kit->cursor.priv = READ_ONCE(kit->dsq->seq); 6117 6118 return 0; 6119 } 6120 6121 /** 6122 * bpf_iter_scx_dsq_next - Progress a DSQ iterator 6123 * @it: iterator to progress 6124 * 6125 * Return the next task. See bpf_iter_scx_dsq_new(). 6126 */ 6127 __bpf_kfunc struct task_struct *bpf_iter_scx_dsq_next(struct bpf_iter_scx_dsq *it) 6128 { 6129 struct bpf_iter_scx_dsq_kern *kit = (void *)it; 6130 bool rev = kit->cursor.flags & SCX_DSQ_ITER_REV; 6131 struct task_struct *p; 6132 unsigned long flags; 6133 6134 if (!kit->dsq) 6135 return NULL; 6136 6137 raw_spin_lock_irqsave(&kit->dsq->lock, flags); 6138 6139 if (list_empty(&kit->cursor.node)) 6140 p = NULL; 6141 else 6142 p = container_of(&kit->cursor, struct task_struct, scx.dsq_list); 6143 6144 /* 6145 * Only tasks which were queued before the iteration started are 6146 * visible. This bounds BPF iterations and guarantees that vtime never 6147 * jumps in the other direction while iterating. 6148 */ 6149 do { 6150 p = nldsq_next_task(kit->dsq, p, rev); 6151 } while (p && unlikely(u32_before(kit->cursor.priv, p->scx.dsq_seq))); 6152 6153 if (p) { 6154 if (rev) 6155 list_move_tail(&kit->cursor.node, &p->scx.dsq_list.node); 6156 else 6157 list_move(&kit->cursor.node, &p->scx.dsq_list.node); 6158 } else { 6159 list_del_init(&kit->cursor.node); 6160 } 6161 6162 raw_spin_unlock_irqrestore(&kit->dsq->lock, flags); 6163 6164 return p; 6165 } 6166 6167 /** 6168 * bpf_iter_scx_dsq_destroy - Destroy a DSQ iterator 6169 * @it: iterator to destroy 6170 * 6171 * Undo scx_iter_scx_dsq_new(). 6172 */ 6173 __bpf_kfunc void bpf_iter_scx_dsq_destroy(struct bpf_iter_scx_dsq *it) 6174 { 6175 struct bpf_iter_scx_dsq_kern *kit = (void *)it; 6176 6177 if (!kit->dsq) 6178 return; 6179 6180 if (!list_empty(&kit->cursor.node)) { 6181 unsigned long flags; 6182 6183 raw_spin_lock_irqsave(&kit->dsq->lock, flags); 6184 list_del_init(&kit->cursor.node); 6185 raw_spin_unlock_irqrestore(&kit->dsq->lock, flags); 6186 } 6187 kit->dsq = NULL; 6188 } 6189 6190 __bpf_kfunc_end_defs(); 6191 6192 static s32 __bstr_format(struct scx_sched *sch, u64 *data_buf, char *line_buf, 6193 size_t line_size, char *fmt, unsigned long long *data, 6194 u32 data__sz) 6195 { 6196 struct bpf_bprintf_data bprintf_data = { .get_bin_args = true }; 6197 s32 ret; 6198 6199 if (data__sz % 8 || data__sz > MAX_BPRINTF_VARARGS * 8 || 6200 (data__sz && !data)) { 6201 scx_error(sch, "invalid data=%p and data__sz=%u", (void *)data, data__sz); 6202 return -EINVAL; 6203 } 6204 6205 ret = copy_from_kernel_nofault(data_buf, data, data__sz); 6206 if (ret < 0) { 6207 scx_error(sch, "failed to read data fields (%d)", ret); 6208 return ret; 6209 } 6210 6211 ret = bpf_bprintf_prepare(fmt, UINT_MAX, data_buf, data__sz / 8, 6212 &bprintf_data); 6213 if (ret < 0) { 6214 scx_error(sch, "format preparation failed (%d)", ret); 6215 return ret; 6216 } 6217 6218 ret = bstr_printf(line_buf, line_size, fmt, 6219 bprintf_data.bin_args); 6220 bpf_bprintf_cleanup(&bprintf_data); 6221 if (ret < 0) { 6222 scx_error(sch, "(\"%s\", %p, %u) failed to format", fmt, data, data__sz); 6223 return ret; 6224 } 6225 6226 return ret; 6227 } 6228 6229 static s32 bstr_format(struct scx_sched *sch, struct scx_bstr_buf *buf, 6230 char *fmt, unsigned long long *data, u32 data__sz) 6231 { 6232 return __bstr_format(sch, buf->data, buf->line, sizeof(buf->line), 6233 fmt, data, data__sz); 6234 } 6235 6236 __bpf_kfunc_start_defs(); 6237 6238 /** 6239 * scx_bpf_exit_bstr - Gracefully exit the BPF scheduler. 6240 * @exit_code: Exit value to pass to user space via struct scx_exit_info. 6241 * @fmt: error message format string 6242 * @data: format string parameters packaged using ___bpf_fill() macro 6243 * @data__sz: @data len, must end in '__sz' for the verifier 6244 * 6245 * Indicate that the BPF scheduler wants to exit gracefully, and initiate ops 6246 * disabling. 6247 */ 6248 __bpf_kfunc void scx_bpf_exit_bstr(s64 exit_code, char *fmt, 6249 unsigned long long *data, u32 data__sz) 6250 { 6251 struct scx_sched *sch; 6252 unsigned long flags; 6253 6254 raw_spin_lock_irqsave(&scx_exit_bstr_buf_lock, flags); 6255 sch = rcu_dereference_bh(scx_root); 6256 if (likely(sch) && 6257 bstr_format(sch, &scx_exit_bstr_buf, fmt, data, data__sz) >= 0) 6258 scx_exit(sch, SCX_EXIT_UNREG_BPF, exit_code, "%s", scx_exit_bstr_buf.line); 6259 raw_spin_unlock_irqrestore(&scx_exit_bstr_buf_lock, flags); 6260 } 6261 6262 /** 6263 * scx_bpf_error_bstr - Indicate fatal error 6264 * @fmt: error message format string 6265 * @data: format string parameters packaged using ___bpf_fill() macro 6266 * @data__sz: @data len, must end in '__sz' for the verifier 6267 * 6268 * Indicate that the BPF scheduler encountered a fatal error and initiate ops 6269 * disabling. 6270 */ 6271 __bpf_kfunc void scx_bpf_error_bstr(char *fmt, unsigned long long *data, 6272 u32 data__sz) 6273 { 6274 struct scx_sched *sch; 6275 unsigned long flags; 6276 6277 raw_spin_lock_irqsave(&scx_exit_bstr_buf_lock, flags); 6278 sch = rcu_dereference_bh(scx_root); 6279 if (likely(sch) && 6280 bstr_format(sch, &scx_exit_bstr_buf, fmt, data, data__sz) >= 0) 6281 scx_exit(sch, SCX_EXIT_ERROR_BPF, 0, "%s", scx_exit_bstr_buf.line); 6282 raw_spin_unlock_irqrestore(&scx_exit_bstr_buf_lock, flags); 6283 } 6284 6285 /** 6286 * scx_bpf_dump_bstr - Generate extra debug dump specific to the BPF scheduler 6287 * @fmt: format string 6288 * @data: format string parameters packaged using ___bpf_fill() macro 6289 * @data__sz: @data len, must end in '__sz' for the verifier 6290 * 6291 * To be called through scx_bpf_dump() helper from ops.dump(), dump_cpu() and 6292 * dump_task() to generate extra debug dump specific to the BPF scheduler. 6293 * 6294 * The extra dump may be multiple lines. A single line may be split over 6295 * multiple calls. The last line is automatically terminated. 6296 */ 6297 __bpf_kfunc void scx_bpf_dump_bstr(char *fmt, unsigned long long *data, 6298 u32 data__sz) 6299 { 6300 struct scx_sched *sch; 6301 struct scx_dump_data *dd = &scx_dump_data; 6302 struct scx_bstr_buf *buf = &dd->buf; 6303 s32 ret; 6304 6305 guard(rcu)(); 6306 6307 sch = rcu_dereference(scx_root); 6308 if (unlikely(!sch)) 6309 return; 6310 6311 if (raw_smp_processor_id() != dd->cpu) { 6312 scx_error(sch, "scx_bpf_dump() must only be called from ops.dump() and friends"); 6313 return; 6314 } 6315 6316 /* append the formatted string to the line buf */ 6317 ret = __bstr_format(sch, buf->data, buf->line + dd->cursor, 6318 sizeof(buf->line) - dd->cursor, fmt, data, data__sz); 6319 if (ret < 0) { 6320 dump_line(dd->s, "%s[!] (\"%s\", %p, %u) failed to format (%d)", 6321 dd->prefix, fmt, data, data__sz, ret); 6322 return; 6323 } 6324 6325 dd->cursor += ret; 6326 dd->cursor = min_t(s32, dd->cursor, sizeof(buf->line)); 6327 6328 if (!dd->cursor) 6329 return; 6330 6331 /* 6332 * If the line buf overflowed or ends in a newline, flush it into the 6333 * dump. This is to allow the caller to generate a single line over 6334 * multiple calls. As ops_dump_flush() can also handle multiple lines in 6335 * the line buf, the only case which can lead to an unexpected 6336 * truncation is when the caller keeps generating newlines in the middle 6337 * instead of the end consecutively. Don't do that. 6338 */ 6339 if (dd->cursor >= sizeof(buf->line) || buf->line[dd->cursor - 1] == '\n') 6340 ops_dump_flush(); 6341 } 6342 6343 /** 6344 * scx_bpf_cpuperf_cap - Query the maximum relative capacity of a CPU 6345 * @cpu: CPU of interest 6346 * 6347 * Return the maximum relative capacity of @cpu in relation to the most 6348 * performant CPU in the system. The return value is in the range [1, 6349 * %SCX_CPUPERF_ONE]. See scx_bpf_cpuperf_cur(). 6350 */ 6351 __bpf_kfunc u32 scx_bpf_cpuperf_cap(s32 cpu) 6352 { 6353 struct scx_sched *sch; 6354 6355 guard(rcu)(); 6356 6357 sch = rcu_dereference(scx_root); 6358 if (likely(sch) && ops_cpu_valid(sch, cpu, NULL)) 6359 return arch_scale_cpu_capacity(cpu); 6360 else 6361 return SCX_CPUPERF_ONE; 6362 } 6363 6364 /** 6365 * scx_bpf_cpuperf_cur - Query the current relative performance of a CPU 6366 * @cpu: CPU of interest 6367 * 6368 * Return the current relative performance of @cpu in relation to its maximum. 6369 * The return value is in the range [1, %SCX_CPUPERF_ONE]. 6370 * 6371 * The current performance level of a CPU in relation to the maximum performance 6372 * available in the system can be calculated as follows: 6373 * 6374 * scx_bpf_cpuperf_cap() * scx_bpf_cpuperf_cur() / %SCX_CPUPERF_ONE 6375 * 6376 * The result is in the range [1, %SCX_CPUPERF_ONE]. 6377 */ 6378 __bpf_kfunc u32 scx_bpf_cpuperf_cur(s32 cpu) 6379 { 6380 struct scx_sched *sch; 6381 6382 guard(rcu)(); 6383 6384 sch = rcu_dereference(scx_root); 6385 if (likely(sch) && ops_cpu_valid(sch, cpu, NULL)) 6386 return arch_scale_freq_capacity(cpu); 6387 else 6388 return SCX_CPUPERF_ONE; 6389 } 6390 6391 /** 6392 * scx_bpf_cpuperf_set - Set the relative performance target of a CPU 6393 * @cpu: CPU of interest 6394 * @perf: target performance level [0, %SCX_CPUPERF_ONE] 6395 * 6396 * Set the target performance level of @cpu to @perf. @perf is in linear 6397 * relative scale between 0 and %SCX_CPUPERF_ONE. This determines how the 6398 * schedutil cpufreq governor chooses the target frequency. 6399 * 6400 * The actual performance level chosen, CPU grouping, and the overhead and 6401 * latency of the operations are dependent on the hardware and cpufreq driver in 6402 * use. Consult hardware and cpufreq documentation for more information. The 6403 * current performance level can be monitored using scx_bpf_cpuperf_cur(). 6404 */ 6405 __bpf_kfunc void scx_bpf_cpuperf_set(s32 cpu, u32 perf) 6406 { 6407 struct scx_sched *sch; 6408 6409 guard(rcu)(); 6410 6411 sch = rcu_dereference(sch); 6412 if (unlikely(!sch)) 6413 return; 6414 6415 if (unlikely(perf > SCX_CPUPERF_ONE)) { 6416 scx_error(sch, "Invalid cpuperf target %u for CPU %d", perf, cpu); 6417 return; 6418 } 6419 6420 if (ops_cpu_valid(sch, cpu, NULL)) { 6421 struct rq *rq = cpu_rq(cpu), *locked_rq = scx_locked_rq(); 6422 struct rq_flags rf; 6423 6424 /* 6425 * When called with an rq lock held, restrict the operation 6426 * to the corresponding CPU to prevent ABBA deadlocks. 6427 */ 6428 if (locked_rq && rq != locked_rq) { 6429 scx_error(sch, "Invalid target CPU %d", cpu); 6430 return; 6431 } 6432 6433 /* 6434 * If no rq lock is held, allow to operate on any CPU by 6435 * acquiring the corresponding rq lock. 6436 */ 6437 if (!locked_rq) { 6438 rq_lock_irqsave(rq, &rf); 6439 update_rq_clock(rq); 6440 } 6441 6442 rq->scx.cpuperf_target = perf; 6443 cpufreq_update_util(rq, 0); 6444 6445 if (!locked_rq) 6446 rq_unlock_irqrestore(rq, &rf); 6447 } 6448 } 6449 6450 /** 6451 * scx_bpf_nr_node_ids - Return the number of possible node IDs 6452 * 6453 * All valid node IDs in the system are smaller than the returned value. 6454 */ 6455 __bpf_kfunc u32 scx_bpf_nr_node_ids(void) 6456 { 6457 return nr_node_ids; 6458 } 6459 6460 /** 6461 * scx_bpf_nr_cpu_ids - Return the number of possible CPU IDs 6462 * 6463 * All valid CPU IDs in the system are smaller than the returned value. 6464 */ 6465 __bpf_kfunc u32 scx_bpf_nr_cpu_ids(void) 6466 { 6467 return nr_cpu_ids; 6468 } 6469 6470 /** 6471 * scx_bpf_get_possible_cpumask - Get a referenced kptr to cpu_possible_mask 6472 */ 6473 __bpf_kfunc const struct cpumask *scx_bpf_get_possible_cpumask(void) 6474 { 6475 return cpu_possible_mask; 6476 } 6477 6478 /** 6479 * scx_bpf_get_online_cpumask - Get a referenced kptr to cpu_online_mask 6480 */ 6481 __bpf_kfunc const struct cpumask *scx_bpf_get_online_cpumask(void) 6482 { 6483 return cpu_online_mask; 6484 } 6485 6486 /** 6487 * scx_bpf_put_cpumask - Release a possible/online cpumask 6488 * @cpumask: cpumask to release 6489 */ 6490 __bpf_kfunc void scx_bpf_put_cpumask(const struct cpumask *cpumask) 6491 { 6492 /* 6493 * Empty function body because we aren't actually acquiring or releasing 6494 * a reference to a global cpumask, which is read-only in the caller and 6495 * is never released. The acquire / release semantics here are just used 6496 * to make the cpumask is a trusted pointer in the caller. 6497 */ 6498 } 6499 6500 /** 6501 * scx_bpf_task_running - Is task currently running? 6502 * @p: task of interest 6503 */ 6504 __bpf_kfunc bool scx_bpf_task_running(const struct task_struct *p) 6505 { 6506 return task_rq(p)->curr == p; 6507 } 6508 6509 /** 6510 * scx_bpf_task_cpu - CPU a task is currently associated with 6511 * @p: task of interest 6512 */ 6513 __bpf_kfunc s32 scx_bpf_task_cpu(const struct task_struct *p) 6514 { 6515 return task_cpu(p); 6516 } 6517 6518 /** 6519 * scx_bpf_cpu_rq - Fetch the rq of a CPU 6520 * @cpu: CPU of the rq 6521 */ 6522 __bpf_kfunc struct rq *scx_bpf_cpu_rq(s32 cpu) 6523 { 6524 struct scx_sched *sch; 6525 6526 guard(rcu)(); 6527 6528 sch = rcu_dereference(scx_root); 6529 if (unlikely(!sch)) 6530 return NULL; 6531 6532 if (!ops_cpu_valid(sch, cpu, NULL)) 6533 return NULL; 6534 6535 if (!sch->warned_deprecated_rq) { 6536 printk_deferred(KERN_WARNING "sched_ext: %s() is deprecated; " 6537 "use scx_bpf_locked_rq() when holding rq lock " 6538 "or scx_bpf_cpu_curr() to read remote curr safely.\n", __func__); 6539 sch->warned_deprecated_rq = true; 6540 } 6541 6542 return cpu_rq(cpu); 6543 } 6544 6545 /** 6546 * scx_bpf_locked_rq - Return the rq currently locked by SCX 6547 * 6548 * Returns the rq if a rq lock is currently held by SCX. 6549 * Otherwise emits an error and returns NULL. 6550 */ 6551 __bpf_kfunc struct rq *scx_bpf_locked_rq(void) 6552 { 6553 struct scx_sched *sch; 6554 struct rq *rq; 6555 6556 guard(preempt)(); 6557 6558 sch = rcu_dereference_sched(scx_root); 6559 if (unlikely(!sch)) 6560 return NULL; 6561 6562 rq = scx_locked_rq(); 6563 if (!rq) { 6564 scx_error(sch, "accessing rq without holding rq lock"); 6565 return NULL; 6566 } 6567 6568 return rq; 6569 } 6570 6571 /** 6572 * scx_bpf_cpu_curr - Return remote CPU's curr task 6573 * @cpu: CPU of interest 6574 * 6575 * Callers must hold RCU read lock (KF_RCU). 6576 */ 6577 __bpf_kfunc struct task_struct *scx_bpf_cpu_curr(s32 cpu) 6578 { 6579 struct scx_sched *sch; 6580 6581 guard(rcu)(); 6582 6583 sch = rcu_dereference(scx_root); 6584 if (unlikely(!sch)) 6585 return NULL; 6586 6587 if (!ops_cpu_valid(sch, cpu, NULL)) 6588 return NULL; 6589 6590 return rcu_dereference(cpu_rq(cpu)->curr); 6591 } 6592 6593 /** 6594 * scx_bpf_task_cgroup - Return the sched cgroup of a task 6595 * @p: task of interest 6596 * 6597 * @p->sched_task_group->css.cgroup represents the cgroup @p is associated with 6598 * from the scheduler's POV. SCX operations should use this function to 6599 * determine @p's current cgroup as, unlike following @p->cgroups, 6600 * @p->sched_task_group is protected by @p's rq lock and thus atomic w.r.t. all 6601 * rq-locked operations. Can be called on the parameter tasks of rq-locked 6602 * operations. The restriction guarantees that @p's rq is locked by the caller. 6603 */ 6604 #ifdef CONFIG_CGROUP_SCHED 6605 __bpf_kfunc struct cgroup *scx_bpf_task_cgroup(struct task_struct *p) 6606 { 6607 struct task_group *tg = p->sched_task_group; 6608 struct cgroup *cgrp = &cgrp_dfl_root.cgrp; 6609 struct scx_sched *sch; 6610 6611 guard(rcu)(); 6612 6613 sch = rcu_dereference(scx_root); 6614 if (unlikely(!sch)) 6615 goto out; 6616 6617 if (!scx_kf_allowed_on_arg_tasks(sch, __SCX_KF_RQ_LOCKED, p)) 6618 goto out; 6619 6620 cgrp = tg_cgrp(tg); 6621 6622 out: 6623 cgroup_get(cgrp); 6624 return cgrp; 6625 } 6626 #endif 6627 6628 /** 6629 * scx_bpf_now - Returns a high-performance monotonically non-decreasing 6630 * clock for the current CPU. The clock returned is in nanoseconds. 6631 * 6632 * It provides the following properties: 6633 * 6634 * 1) High performance: Many BPF schedulers call bpf_ktime_get_ns() frequently 6635 * to account for execution time and track tasks' runtime properties. 6636 * Unfortunately, in some hardware platforms, bpf_ktime_get_ns() -- which 6637 * eventually reads a hardware timestamp counter -- is neither performant nor 6638 * scalable. scx_bpf_now() aims to provide a high-performance clock by 6639 * using the rq clock in the scheduler core whenever possible. 6640 * 6641 * 2) High enough resolution for the BPF scheduler use cases: In most BPF 6642 * scheduler use cases, the required clock resolution is lower than the most 6643 * accurate hardware clock (e.g., rdtsc in x86). scx_bpf_now() basically 6644 * uses the rq clock in the scheduler core whenever it is valid. It considers 6645 * that the rq clock is valid from the time the rq clock is updated 6646 * (update_rq_clock) until the rq is unlocked (rq_unpin_lock). 6647 * 6648 * 3) Monotonically non-decreasing clock for the same CPU: scx_bpf_now() 6649 * guarantees the clock never goes backward when comparing them in the same 6650 * CPU. On the other hand, when comparing clocks in different CPUs, there 6651 * is no such guarantee -- the clock can go backward. It provides a 6652 * monotonically *non-decreasing* clock so that it would provide the same 6653 * clock values in two different scx_bpf_now() calls in the same CPU 6654 * during the same period of when the rq clock is valid. 6655 */ 6656 __bpf_kfunc u64 scx_bpf_now(void) 6657 { 6658 struct rq *rq; 6659 u64 clock; 6660 6661 preempt_disable(); 6662 6663 rq = this_rq(); 6664 if (smp_load_acquire(&rq->scx.flags) & SCX_RQ_CLK_VALID) { 6665 /* 6666 * If the rq clock is valid, use the cached rq clock. 6667 * 6668 * Note that scx_bpf_now() is re-entrant between a process 6669 * context and an interrupt context (e.g., timer interrupt). 6670 * However, we don't need to consider the race between them 6671 * because such race is not observable from a caller. 6672 */ 6673 clock = READ_ONCE(rq->scx.clock); 6674 } else { 6675 /* 6676 * Otherwise, return a fresh rq clock. 6677 * 6678 * The rq clock is updated outside of the rq lock. 6679 * In this case, keep the updated rq clock invalid so the next 6680 * kfunc call outside the rq lock gets a fresh rq clock. 6681 */ 6682 clock = sched_clock_cpu(cpu_of(rq)); 6683 } 6684 6685 preempt_enable(); 6686 6687 return clock; 6688 } 6689 6690 static void scx_read_events(struct scx_sched *sch, struct scx_event_stats *events) 6691 { 6692 struct scx_event_stats *e_cpu; 6693 int cpu; 6694 6695 /* Aggregate per-CPU event counters into @events. */ 6696 memset(events, 0, sizeof(*events)); 6697 for_each_possible_cpu(cpu) { 6698 e_cpu = &per_cpu_ptr(sch->pcpu, cpu)->event_stats; 6699 scx_agg_event(events, e_cpu, SCX_EV_SELECT_CPU_FALLBACK); 6700 scx_agg_event(events, e_cpu, SCX_EV_DISPATCH_LOCAL_DSQ_OFFLINE); 6701 scx_agg_event(events, e_cpu, SCX_EV_DISPATCH_KEEP_LAST); 6702 scx_agg_event(events, e_cpu, SCX_EV_ENQ_SKIP_EXITING); 6703 scx_agg_event(events, e_cpu, SCX_EV_ENQ_SKIP_MIGRATION_DISABLED); 6704 scx_agg_event(events, e_cpu, SCX_EV_REFILL_SLICE_DFL); 6705 scx_agg_event(events, e_cpu, SCX_EV_BYPASS_DURATION); 6706 scx_agg_event(events, e_cpu, SCX_EV_BYPASS_DISPATCH); 6707 scx_agg_event(events, e_cpu, SCX_EV_BYPASS_ACTIVATE); 6708 } 6709 } 6710 6711 /* 6712 * scx_bpf_events - Get a system-wide event counter to 6713 * @events: output buffer from a BPF program 6714 * @events__sz: @events len, must end in '__sz'' for the verifier 6715 */ 6716 __bpf_kfunc void scx_bpf_events(struct scx_event_stats *events, 6717 size_t events__sz) 6718 { 6719 struct scx_sched *sch; 6720 struct scx_event_stats e_sys; 6721 6722 rcu_read_lock(); 6723 sch = rcu_dereference(scx_root); 6724 if (sch) 6725 scx_read_events(sch, &e_sys); 6726 else 6727 memset(&e_sys, 0, sizeof(e_sys)); 6728 rcu_read_unlock(); 6729 6730 /* 6731 * We cannot entirely trust a BPF-provided size since a BPF program 6732 * might be compiled against a different vmlinux.h, of which 6733 * scx_event_stats would be larger (a newer vmlinux.h) or smaller 6734 * (an older vmlinux.h). Hence, we use the smaller size to avoid 6735 * memory corruption. 6736 */ 6737 events__sz = min(events__sz, sizeof(*events)); 6738 memcpy(events, &e_sys, events__sz); 6739 } 6740 6741 __bpf_kfunc_end_defs(); 6742 6743 BTF_KFUNCS_START(scx_kfunc_ids_any) 6744 BTF_ID_FLAGS(func, scx_bpf_kick_cpu) 6745 BTF_ID_FLAGS(func, scx_bpf_dsq_nr_queued) 6746 BTF_ID_FLAGS(func, scx_bpf_destroy_dsq) 6747 BTF_ID_FLAGS(func, bpf_iter_scx_dsq_new, KF_ITER_NEW | KF_RCU_PROTECTED) 6748 BTF_ID_FLAGS(func, bpf_iter_scx_dsq_next, KF_ITER_NEXT | KF_RET_NULL) 6749 BTF_ID_FLAGS(func, bpf_iter_scx_dsq_destroy, KF_ITER_DESTROY) 6750 BTF_ID_FLAGS(func, scx_bpf_exit_bstr, KF_TRUSTED_ARGS) 6751 BTF_ID_FLAGS(func, scx_bpf_error_bstr, KF_TRUSTED_ARGS) 6752 BTF_ID_FLAGS(func, scx_bpf_dump_bstr, KF_TRUSTED_ARGS) 6753 BTF_ID_FLAGS(func, scx_bpf_cpuperf_cap) 6754 BTF_ID_FLAGS(func, scx_bpf_cpuperf_cur) 6755 BTF_ID_FLAGS(func, scx_bpf_cpuperf_set) 6756 BTF_ID_FLAGS(func, scx_bpf_nr_node_ids) 6757 BTF_ID_FLAGS(func, scx_bpf_nr_cpu_ids) 6758 BTF_ID_FLAGS(func, scx_bpf_get_possible_cpumask, KF_ACQUIRE) 6759 BTF_ID_FLAGS(func, scx_bpf_get_online_cpumask, KF_ACQUIRE) 6760 BTF_ID_FLAGS(func, scx_bpf_put_cpumask, KF_RELEASE) 6761 BTF_ID_FLAGS(func, scx_bpf_task_running, KF_RCU) 6762 BTF_ID_FLAGS(func, scx_bpf_task_cpu, KF_RCU) 6763 BTF_ID_FLAGS(func, scx_bpf_cpu_rq) 6764 BTF_ID_FLAGS(func, scx_bpf_locked_rq, KF_RET_NULL) 6765 BTF_ID_FLAGS(func, scx_bpf_cpu_curr, KF_RET_NULL | KF_RCU_PROTECTED) 6766 #ifdef CONFIG_CGROUP_SCHED 6767 BTF_ID_FLAGS(func, scx_bpf_task_cgroup, KF_RCU | KF_ACQUIRE) 6768 #endif 6769 BTF_ID_FLAGS(func, scx_bpf_now) 6770 BTF_ID_FLAGS(func, scx_bpf_events, KF_TRUSTED_ARGS) 6771 BTF_KFUNCS_END(scx_kfunc_ids_any) 6772 6773 static const struct btf_kfunc_id_set scx_kfunc_set_any = { 6774 .owner = THIS_MODULE, 6775 .set = &scx_kfunc_ids_any, 6776 }; 6777 6778 static int __init scx_init(void) 6779 { 6780 int ret; 6781 6782 /* 6783 * kfunc registration can't be done from init_sched_ext_class() as 6784 * register_btf_kfunc_id_set() needs most of the system to be up. 6785 * 6786 * Some kfuncs are context-sensitive and can only be called from 6787 * specific SCX ops. They are grouped into BTF sets accordingly. 6788 * Unfortunately, BPF currently doesn't have a way of enforcing such 6789 * restrictions. Eventually, the verifier should be able to enforce 6790 * them. For now, register them the same and make each kfunc explicitly 6791 * check using scx_kf_allowed(). 6792 */ 6793 if ((ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_STRUCT_OPS, 6794 &scx_kfunc_set_enqueue_dispatch)) || 6795 (ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_STRUCT_OPS, 6796 &scx_kfunc_set_dispatch)) || 6797 (ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_STRUCT_OPS, 6798 &scx_kfunc_set_cpu_release)) || 6799 (ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_STRUCT_OPS, 6800 &scx_kfunc_set_unlocked)) || 6801 (ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_SYSCALL, 6802 &scx_kfunc_set_unlocked)) || 6803 (ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_STRUCT_OPS, 6804 &scx_kfunc_set_any)) || 6805 (ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_TRACING, 6806 &scx_kfunc_set_any)) || 6807 (ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_SYSCALL, 6808 &scx_kfunc_set_any))) { 6809 pr_err("sched_ext: Failed to register kfunc sets (%d)\n", ret); 6810 return ret; 6811 } 6812 6813 ret = scx_idle_init(); 6814 if (ret) { 6815 pr_err("sched_ext: Failed to initialize idle tracking (%d)\n", ret); 6816 return ret; 6817 } 6818 6819 ret = register_bpf_struct_ops(&bpf_sched_ext_ops, sched_ext_ops); 6820 if (ret) { 6821 pr_err("sched_ext: Failed to register struct_ops (%d)\n", ret); 6822 return ret; 6823 } 6824 6825 ret = register_pm_notifier(&scx_pm_notifier); 6826 if (ret) { 6827 pr_err("sched_ext: Failed to register PM notifier (%d)\n", ret); 6828 return ret; 6829 } 6830 6831 scx_kset = kset_create_and_add("sched_ext", &scx_uevent_ops, kernel_kobj); 6832 if (!scx_kset) { 6833 pr_err("sched_ext: Failed to create /sys/kernel/sched_ext\n"); 6834 return -ENOMEM; 6835 } 6836 6837 ret = sysfs_create_group(&scx_kset->kobj, &scx_global_attr_group); 6838 if (ret < 0) { 6839 pr_err("sched_ext: Failed to add global attributes\n"); 6840 return ret; 6841 } 6842 6843 return 0; 6844 } 6845 __initcall(scx_init); 6846