scx_central.bpf.c 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. /* SPDX-License-Identifier: GPL-2.0 */
  2. /*
  3. * A central FIFO sched_ext scheduler which demonstrates the following:
  4. *
  5. * a. Making all scheduling decisions from one CPU:
  6. *
  7. * The central CPU is the only one making scheduling decisions. All other
  8. * CPUs kick the central CPU when they run out of tasks to run.
  9. *
  10. * There is one global BPF queue and the central CPU schedules all CPUs by
  11. * dispatching from the global queue to each CPU's local dsq from dispatch().
  12. * This isn't the most straightforward. e.g. It'd be easier to bounce
  13. * through per-CPU BPF queues. The current design is chosen to maximally
  14. * utilize and verify various SCX mechanisms such as LOCAL_ON dispatching.
  15. *
  16. * b. Tickless operation
  17. *
  18. * All tasks are dispatched with the infinite slice which allows stopping the
  19. * ticks on CONFIG_NO_HZ_FULL kernels running with the proper nohz_full
  20. * parameter. The tickless operation can be observed through
  21. * /proc/interrupts.
  22. *
  23. * Periodic switching is enforced by a periodic timer checking all CPUs and
  24. * preempting them as necessary. Unfortunately, BPF timer currently doesn't
  25. * have a way to pin to a specific CPU, so the periodic timer isn't pinned to
  26. * the central CPU.
  27. *
  28. * c. Preemption
  29. *
  30. * Kthreads are unconditionally queued to the head of a matching local dsq
  31. * and dispatched with SCX_DSQ_PREEMPT. This ensures that a kthread is always
  32. * prioritized over user threads, which is required for ensuring forward
  33. * progress as e.g. the periodic timer may run on a ksoftirqd and if the
  34. * ksoftirqd gets starved by a user thread, there may not be anything else to
  35. * vacate that user thread.
  36. *
  37. * SCX_KICK_PREEMPT is used to trigger scheduling and CPUs to move to the
  38. * next tasks.
  39. *
  40. * This scheduler is designed to maximize usage of various SCX mechanisms. A
  41. * more practical implementation would likely put the scheduling loop outside
  42. * the central CPU's dispatch() path and add some form of priority mechanism.
  43. *
  44. * Copyright (c) 2022 Meta Platforms, Inc. and affiliates.
  45. * Copyright (c) 2022 Tejun Heo <tj@kernel.org>
  46. * Copyright (c) 2022 David Vernet <dvernet@meta.com>
  47. */
  48. #include <scx/common.bpf.h>
  49. char _license[] SEC("license") = "GPL";
  50. enum {
  51. FALLBACK_DSQ_ID = 0,
  52. MS_TO_NS = 1000LLU * 1000,
  53. TIMER_INTERVAL_NS = 1 * MS_TO_NS,
  54. };
  55. const volatile s32 central_cpu;
  56. const volatile u32 nr_cpu_ids = 1; /* !0 for veristat, set during init */
  57. const volatile u64 slice_ns;
  58. bool timer_pinned = true;
  59. u64 nr_total, nr_locals, nr_queued, nr_lost_pids;
  60. u64 nr_timers, nr_dispatches, nr_mismatches, nr_retries;
  61. u64 nr_overflows;
  62. UEI_DEFINE(uei);
  63. struct {
  64. __uint(type, BPF_MAP_TYPE_QUEUE);
  65. __uint(max_entries, 4096);
  66. __type(value, s32);
  67. } central_q SEC(".maps");
  68. /* can't use percpu map due to bad lookups */
  69. bool RESIZABLE_ARRAY(data, cpu_gimme_task);
  70. u64 RESIZABLE_ARRAY(data, cpu_started_at);
  71. struct central_timer {
  72. struct bpf_timer timer;
  73. };
  74. struct {
  75. __uint(type, BPF_MAP_TYPE_ARRAY);
  76. __uint(max_entries, 1);
  77. __type(key, u32);
  78. __type(value, struct central_timer);
  79. } central_timer SEC(".maps");
  80. s32 BPF_STRUCT_OPS(central_select_cpu, struct task_struct *p,
  81. s32 prev_cpu, u64 wake_flags)
  82. {
  83. /*
  84. * Steer wakeups to the central CPU as much as possible to avoid
  85. * disturbing other CPUs. It's safe to blindly return the central cpu as
  86. * select_cpu() is a hint and if @p can't be on it, the kernel will
  87. * automatically pick a fallback CPU.
  88. */
  89. return central_cpu;
  90. }
  91. void BPF_STRUCT_OPS(central_enqueue, struct task_struct *p, u64 enq_flags)
  92. {
  93. s32 pid = p->pid;
  94. __sync_fetch_and_add(&nr_total, 1);
  95. /*
  96. * Push per-cpu kthreads at the head of local dsq's and preempt the
  97. * corresponding CPU. This ensures that e.g. ksoftirqd isn't blocked
  98. * behind other threads which is necessary for forward progress
  99. * guarantee as we depend on the BPF timer which may run from ksoftirqd.
  100. */
  101. if ((p->flags & PF_KTHREAD) && p->nr_cpus_allowed == 1) {
  102. __sync_fetch_and_add(&nr_locals, 1);
  103. scx_bpf_dsq_insert(p, SCX_DSQ_LOCAL, SCX_SLICE_INF,
  104. enq_flags | SCX_ENQ_PREEMPT);
  105. return;
  106. }
  107. if (bpf_map_push_elem(&central_q, &pid, 0)) {
  108. __sync_fetch_and_add(&nr_overflows, 1);
  109. scx_bpf_dsq_insert(p, FALLBACK_DSQ_ID, SCX_SLICE_INF, enq_flags);
  110. return;
  111. }
  112. __sync_fetch_and_add(&nr_queued, 1);
  113. if (!scx_bpf_task_running(p))
  114. scx_bpf_kick_cpu(central_cpu, SCX_KICK_PREEMPT);
  115. }
  116. static bool dispatch_to_cpu(s32 cpu)
  117. {
  118. struct task_struct *p;
  119. s32 pid;
  120. bpf_repeat(BPF_MAX_LOOPS) {
  121. if (bpf_map_pop_elem(&central_q, &pid))
  122. break;
  123. __sync_fetch_and_sub(&nr_queued, 1);
  124. p = bpf_task_from_pid(pid);
  125. if (!p) {
  126. __sync_fetch_and_add(&nr_lost_pids, 1);
  127. continue;
  128. }
  129. /*
  130. * If we can't run the task at the top, do the dumb thing and
  131. * bounce it to the fallback dsq.
  132. */
  133. if (!bpf_cpumask_test_cpu(cpu, p->cpus_ptr)) {
  134. __sync_fetch_and_add(&nr_mismatches, 1);
  135. scx_bpf_dsq_insert(p, FALLBACK_DSQ_ID, SCX_SLICE_INF, 0);
  136. bpf_task_release(p);
  137. /*
  138. * We might run out of dispatch buffer slots if we continue dispatching
  139. * to the fallback DSQ, without dispatching to the local DSQ of the
  140. * target CPU. In such a case, break the loop now as will fail the
  141. * next dispatch operation.
  142. */
  143. if (!scx_bpf_dispatch_nr_slots())
  144. break;
  145. continue;
  146. }
  147. /* dispatch to local and mark that @cpu doesn't need more */
  148. scx_bpf_dsq_insert(p, SCX_DSQ_LOCAL_ON | cpu, SCX_SLICE_INF, 0);
  149. if (cpu != central_cpu)
  150. scx_bpf_kick_cpu(cpu, SCX_KICK_IDLE);
  151. bpf_task_release(p);
  152. return true;
  153. }
  154. return false;
  155. }
  156. void BPF_STRUCT_OPS(central_dispatch, s32 cpu, struct task_struct *prev)
  157. {
  158. if (cpu == central_cpu) {
  159. /* dispatch for all other CPUs first */
  160. __sync_fetch_and_add(&nr_dispatches, 1);
  161. bpf_for(cpu, 0, nr_cpu_ids) {
  162. bool *gimme;
  163. if (!scx_bpf_dispatch_nr_slots())
  164. break;
  165. /* central's gimme is never set */
  166. gimme = ARRAY_ELEM_PTR(cpu_gimme_task, cpu, nr_cpu_ids);
  167. if (!gimme || !*gimme)
  168. continue;
  169. if (dispatch_to_cpu(cpu))
  170. *gimme = false;
  171. }
  172. /*
  173. * Retry if we ran out of dispatch buffer slots as we might have
  174. * skipped some CPUs and also need to dispatch for self. The ext
  175. * core automatically retries if the local dsq is empty but we
  176. * can't rely on that as we're dispatching for other CPUs too.
  177. * Kick self explicitly to retry.
  178. */
  179. if (!scx_bpf_dispatch_nr_slots()) {
  180. __sync_fetch_and_add(&nr_retries, 1);
  181. scx_bpf_kick_cpu(central_cpu, SCX_KICK_PREEMPT);
  182. return;
  183. }
  184. /* look for a task to run on the central CPU */
  185. if (scx_bpf_dsq_move_to_local(FALLBACK_DSQ_ID))
  186. return;
  187. dispatch_to_cpu(central_cpu);
  188. } else {
  189. bool *gimme;
  190. if (scx_bpf_dsq_move_to_local(FALLBACK_DSQ_ID))
  191. return;
  192. gimme = ARRAY_ELEM_PTR(cpu_gimme_task, cpu, nr_cpu_ids);
  193. if (gimme)
  194. *gimme = true;
  195. /*
  196. * Force dispatch on the scheduling CPU so that it finds a task
  197. * to run for us.
  198. */
  199. scx_bpf_kick_cpu(central_cpu, SCX_KICK_PREEMPT);
  200. }
  201. }
  202. void BPF_STRUCT_OPS(central_running, struct task_struct *p)
  203. {
  204. s32 cpu = scx_bpf_task_cpu(p);
  205. u64 *started_at = ARRAY_ELEM_PTR(cpu_started_at, cpu, nr_cpu_ids);
  206. if (started_at)
  207. *started_at = scx_bpf_now() ?: 1; /* 0 indicates idle */
  208. }
  209. void BPF_STRUCT_OPS(central_stopping, struct task_struct *p, bool runnable)
  210. {
  211. s32 cpu = scx_bpf_task_cpu(p);
  212. u64 *started_at = ARRAY_ELEM_PTR(cpu_started_at, cpu, nr_cpu_ids);
  213. if (started_at)
  214. *started_at = 0;
  215. }
  216. static int central_timerfn(void *map, int *key, struct bpf_timer *timer)
  217. {
  218. u64 now = scx_bpf_now();
  219. u64 nr_to_kick = nr_queued;
  220. s32 i, curr_cpu;
  221. curr_cpu = bpf_get_smp_processor_id();
  222. if (timer_pinned && (curr_cpu != central_cpu)) {
  223. scx_bpf_error("Central timer ran on CPU %d, not central CPU %d",
  224. curr_cpu, central_cpu);
  225. return 0;
  226. }
  227. bpf_for(i, 0, nr_cpu_ids) {
  228. s32 cpu = (nr_timers + i) % nr_cpu_ids;
  229. u64 *started_at;
  230. if (cpu == central_cpu)
  231. continue;
  232. /* kick iff the current one exhausted its slice */
  233. started_at = ARRAY_ELEM_PTR(cpu_started_at, cpu, nr_cpu_ids);
  234. if (started_at && *started_at &&
  235. time_before(now, *started_at + slice_ns))
  236. continue;
  237. /* and there's something pending */
  238. if (scx_bpf_dsq_nr_queued(FALLBACK_DSQ_ID) ||
  239. scx_bpf_dsq_nr_queued(SCX_DSQ_LOCAL_ON | cpu))
  240. ;
  241. else if (nr_to_kick)
  242. nr_to_kick--;
  243. else
  244. continue;
  245. scx_bpf_kick_cpu(cpu, SCX_KICK_PREEMPT);
  246. }
  247. bpf_timer_start(timer, TIMER_INTERVAL_NS, BPF_F_TIMER_CPU_PIN);
  248. __sync_fetch_and_add(&nr_timers, 1);
  249. return 0;
  250. }
  251. int BPF_STRUCT_OPS_SLEEPABLE(central_init)
  252. {
  253. u32 key = 0;
  254. struct bpf_timer *timer;
  255. int ret;
  256. ret = scx_bpf_create_dsq(FALLBACK_DSQ_ID, -1);
  257. if (ret) {
  258. scx_bpf_error("scx_bpf_create_dsq failed (%d)", ret);
  259. return ret;
  260. }
  261. timer = bpf_map_lookup_elem(&central_timer, &key);
  262. if (!timer)
  263. return -ESRCH;
  264. if (bpf_get_smp_processor_id() != central_cpu) {
  265. scx_bpf_error("init from non-central CPU");
  266. return -EINVAL;
  267. }
  268. bpf_timer_init(timer, &central_timer, CLOCK_MONOTONIC);
  269. bpf_timer_set_callback(timer, central_timerfn);
  270. ret = bpf_timer_start(timer, TIMER_INTERVAL_NS, BPF_F_TIMER_CPU_PIN);
  271. /*
  272. * BPF_F_TIMER_CPU_PIN is pretty new (>=6.7). If we're running in a
  273. * kernel which doesn't have it, bpf_timer_start() will return -EINVAL.
  274. * Retry without the PIN. This would be the perfect use case for
  275. * bpf_core_enum_value_exists() but the enum type doesn't have a name
  276. * and can't be used with bpf_core_enum_value_exists(). Oh well...
  277. */
  278. if (ret == -EINVAL) {
  279. timer_pinned = false;
  280. ret = bpf_timer_start(timer, TIMER_INTERVAL_NS, 0);
  281. }
  282. if (ret)
  283. scx_bpf_error("bpf_timer_start failed (%d)", ret);
  284. return ret;
  285. }
  286. void BPF_STRUCT_OPS(central_exit, struct scx_exit_info *ei)
  287. {
  288. UEI_RECORD(uei, ei);
  289. }
  290. SCX_OPS_DEFINE(central_ops,
  291. /*
  292. * We are offloading all scheduling decisions to the central CPU
  293. * and thus being the last task on a given CPU doesn't mean
  294. * anything special. Enqueue the last tasks like any other tasks.
  295. */
  296. .flags = SCX_OPS_ENQ_LAST,
  297. .select_cpu = (void *)central_select_cpu,
  298. .enqueue = (void *)central_enqueue,
  299. .dispatch = (void *)central_dispatch,
  300. .running = (void *)central_running,
  301. .stopping = (void *)central_stopping,
  302. .init = (void *)central_init,
  303. .exit = (void *)central_exit,
  304. .name = "central");