scx_userland.bpf.c 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. /* SPDX-License-Identifier: GPL-2.0 */
  2. /*
  3. * A minimal userland scheduler.
  4. *
  5. * In terms of scheduling, this provides two different types of behaviors:
  6. * 1. A global FIFO scheduling order for _any_ tasks that have CPU affinity.
  7. * All such tasks are direct-dispatched from the kernel, and are never
  8. * enqueued in user space.
  9. * 2. A primitive vruntime scheduler that is implemented in user space, for all
  10. * other tasks.
  11. *
  12. * Some parts of this example user space scheduler could be implemented more
  13. * efficiently using more complex and sophisticated data structures. For
  14. * example, rather than using BPF_MAP_TYPE_QUEUE's,
  15. * BPF_MAP_TYPE_{USER_}RINGBUF's could be used for exchanging messages between
  16. * user space and kernel space. Similarly, we use a simple vruntime-sorted list
  17. * in user space, but an rbtree could be used instead.
  18. *
  19. * Copyright (c) 2022 Meta Platforms, Inc. and affiliates.
  20. * Copyright (c) 2022 Tejun Heo <tj@kernel.org>
  21. * Copyright (c) 2022 David Vernet <dvernet@meta.com>
  22. */
  23. #include <scx/common.bpf.h>
  24. #include "scx_userland.h"
  25. /*
  26. * Maximum amount of tasks enqueued/dispatched between kernel and user-space.
  27. */
  28. #define MAX_ENQUEUED_TASKS 4096
  29. char _license[] SEC("license") = "GPL";
  30. const volatile s32 usersched_pid;
  31. /* !0 for veristat, set during init */
  32. const volatile u32 num_possible_cpus = 64;
  33. /* Stats that are printed by user space. */
  34. u64 nr_failed_enqueues, nr_kernel_enqueues, nr_user_enqueues;
  35. /*
  36. * Number of tasks that are queued for scheduling.
  37. *
  38. * This number is incremented by the BPF component when a task is queued to the
  39. * user-space scheduler and it must be decremented by the user-space scheduler
  40. * when a task is consumed.
  41. */
  42. volatile u64 nr_queued;
  43. /*
  44. * Number of tasks that are waiting for scheduling.
  45. *
  46. * This number must be updated by the user-space scheduler to keep track if
  47. * there is still some scheduling work to do.
  48. */
  49. volatile u64 nr_scheduled;
  50. UEI_DEFINE(uei);
  51. /*
  52. * The map containing tasks that are enqueued in user space from the kernel.
  53. *
  54. * This map is drained by the user space scheduler.
  55. */
  56. struct {
  57. __uint(type, BPF_MAP_TYPE_QUEUE);
  58. __uint(max_entries, MAX_ENQUEUED_TASKS);
  59. __type(value, struct scx_userland_enqueued_task);
  60. } enqueued SEC(".maps");
  61. /*
  62. * The map containing tasks that are dispatched to the kernel from user space.
  63. *
  64. * Drained by the kernel in userland_dispatch().
  65. */
  66. struct {
  67. __uint(type, BPF_MAP_TYPE_QUEUE);
  68. __uint(max_entries, MAX_ENQUEUED_TASKS);
  69. __type(value, s32);
  70. } dispatched SEC(".maps");
  71. /* Per-task scheduling context */
  72. struct task_ctx {
  73. bool force_local; /* Dispatch directly to local DSQ */
  74. };
  75. /* Map that contains task-local storage. */
  76. struct {
  77. __uint(type, BPF_MAP_TYPE_TASK_STORAGE);
  78. __uint(map_flags, BPF_F_NO_PREALLOC);
  79. __type(key, int);
  80. __type(value, struct task_ctx);
  81. } task_ctx_stor SEC(".maps");
  82. /*
  83. * Flag used to wake-up the user-space scheduler.
  84. */
  85. static volatile u32 usersched_needed;
  86. /*
  87. * Set user-space scheduler wake-up flag (equivalent to an atomic release
  88. * operation).
  89. */
  90. static void set_usersched_needed(void)
  91. {
  92. __sync_fetch_and_or(&usersched_needed, 1);
  93. }
  94. /*
  95. * Check and clear user-space scheduler wake-up flag (equivalent to an atomic
  96. * acquire operation).
  97. */
  98. static bool test_and_clear_usersched_needed(void)
  99. {
  100. return __sync_fetch_and_and(&usersched_needed, 0) == 1;
  101. }
  102. static bool is_usersched_task(const struct task_struct *p)
  103. {
  104. return p->pid == usersched_pid;
  105. }
  106. static bool keep_in_kernel(const struct task_struct *p)
  107. {
  108. return p->nr_cpus_allowed < num_possible_cpus;
  109. }
  110. static struct task_struct *usersched_task(void)
  111. {
  112. struct task_struct *p;
  113. p = bpf_task_from_pid(usersched_pid);
  114. /*
  115. * Should never happen -- the usersched task should always be managed
  116. * by sched_ext.
  117. */
  118. if (!p)
  119. scx_bpf_error("Failed to find usersched task %d", usersched_pid);
  120. return p;
  121. }
  122. s32 BPF_STRUCT_OPS(userland_select_cpu, struct task_struct *p,
  123. s32 prev_cpu, u64 wake_flags)
  124. {
  125. if (keep_in_kernel(p)) {
  126. s32 cpu;
  127. struct task_ctx *tctx;
  128. tctx = bpf_task_storage_get(&task_ctx_stor, p, 0, 0);
  129. if (!tctx) {
  130. scx_bpf_error("Failed to look up task-local storage for %s", p->comm);
  131. return -ESRCH;
  132. }
  133. if (p->nr_cpus_allowed == 1 ||
  134. scx_bpf_test_and_clear_cpu_idle(prev_cpu)) {
  135. tctx->force_local = true;
  136. return prev_cpu;
  137. }
  138. cpu = scx_bpf_pick_idle_cpu(p->cpus_ptr, 0);
  139. if (cpu >= 0) {
  140. tctx->force_local = true;
  141. return cpu;
  142. }
  143. }
  144. return prev_cpu;
  145. }
  146. static void dispatch_user_scheduler(void)
  147. {
  148. struct task_struct *p;
  149. p = usersched_task();
  150. if (p) {
  151. scx_bpf_dsq_insert(p, SCX_DSQ_GLOBAL, SCX_SLICE_DFL, 0);
  152. bpf_task_release(p);
  153. }
  154. }
  155. static void enqueue_task_in_user_space(struct task_struct *p, u64 enq_flags)
  156. {
  157. struct scx_userland_enqueued_task task = {};
  158. task.pid = p->pid;
  159. task.sum_exec_runtime = p->se.sum_exec_runtime;
  160. task.weight = p->scx.weight;
  161. if (bpf_map_push_elem(&enqueued, &task, 0)) {
  162. /*
  163. * If we fail to enqueue the task in user space, put it
  164. * directly on the global DSQ.
  165. */
  166. __sync_fetch_and_add(&nr_failed_enqueues, 1);
  167. scx_bpf_dsq_insert(p, SCX_DSQ_GLOBAL, SCX_SLICE_DFL, enq_flags);
  168. } else {
  169. __sync_fetch_and_add(&nr_user_enqueues, 1);
  170. set_usersched_needed();
  171. }
  172. }
  173. void BPF_STRUCT_OPS(userland_enqueue, struct task_struct *p, u64 enq_flags)
  174. {
  175. if (keep_in_kernel(p)) {
  176. u64 dsq_id = SCX_DSQ_GLOBAL;
  177. struct task_ctx *tctx;
  178. tctx = bpf_task_storage_get(&task_ctx_stor, p, 0, 0);
  179. if (!tctx) {
  180. scx_bpf_error("Failed to lookup task ctx for %s", p->comm);
  181. return;
  182. }
  183. if (tctx->force_local)
  184. dsq_id = SCX_DSQ_LOCAL;
  185. tctx->force_local = false;
  186. scx_bpf_dsq_insert(p, dsq_id, SCX_SLICE_DFL, enq_flags);
  187. __sync_fetch_and_add(&nr_kernel_enqueues, 1);
  188. return;
  189. } else if (!is_usersched_task(p)) {
  190. enqueue_task_in_user_space(p, enq_flags);
  191. }
  192. }
  193. void BPF_STRUCT_OPS(userland_dispatch, s32 cpu, struct task_struct *prev)
  194. {
  195. if (test_and_clear_usersched_needed())
  196. dispatch_user_scheduler();
  197. bpf_repeat(MAX_ENQUEUED_TASKS) {
  198. s32 pid;
  199. struct task_struct *p;
  200. if (bpf_map_pop_elem(&dispatched, &pid))
  201. break;
  202. /*
  203. * The task could have exited by the time we get around to
  204. * dispatching it. Treat this as a normal occurrence, and simply
  205. * move onto the next iteration.
  206. */
  207. p = bpf_task_from_pid(pid);
  208. if (!p)
  209. continue;
  210. scx_bpf_dsq_insert(p, SCX_DSQ_GLOBAL, SCX_SLICE_DFL, 0);
  211. bpf_task_release(p);
  212. }
  213. }
  214. /*
  215. * A CPU is about to change its idle state. If the CPU is going idle, ensure
  216. * that the user-space scheduler has a chance to run if there is any remaining
  217. * work to do.
  218. */
  219. void BPF_STRUCT_OPS(userland_update_idle, s32 cpu, bool idle)
  220. {
  221. /*
  222. * Don't do anything if we exit from and idle state, a CPU owner will
  223. * be assigned in .running().
  224. */
  225. if (!idle)
  226. return;
  227. /*
  228. * A CPU is now available, notify the user-space scheduler that tasks
  229. * can be dispatched, if there is at least one task waiting to be
  230. * scheduled, either queued (accounted in nr_queued) or scheduled
  231. * (accounted in nr_scheduled).
  232. *
  233. * NOTE: nr_queued is incremented by the BPF component, more exactly in
  234. * enqueue(), when a task is sent to the user-space scheduler, then
  235. * the scheduler drains the queued tasks (updating nr_queued) and adds
  236. * them to its internal data structures / state; at this point tasks
  237. * become "scheduled" and the user-space scheduler will take care of
  238. * updating nr_scheduled accordingly; lastly tasks will be dispatched
  239. * and the user-space scheduler will update nr_scheduled again.
  240. *
  241. * Checking both counters allows to determine if there is still some
  242. * pending work to do for the scheduler: new tasks have been queued
  243. * since last check, or there are still tasks "queued" or "scheduled"
  244. * since the previous user-space scheduler run. If the counters are
  245. * both zero it is pointless to wake-up the scheduler (even if a CPU
  246. * becomes idle), because there is nothing to do.
  247. *
  248. * Keep in mind that update_idle() doesn't run concurrently with the
  249. * user-space scheduler (that is single-threaded): this function is
  250. * naturally serialized with the user-space scheduler code, therefore
  251. * this check here is also safe from a concurrency perspective.
  252. */
  253. if (nr_queued || nr_scheduled) {
  254. /*
  255. * Kick the CPU to make it immediately ready to accept
  256. * dispatched tasks.
  257. */
  258. set_usersched_needed();
  259. scx_bpf_kick_cpu(cpu, 0);
  260. }
  261. }
  262. s32 BPF_STRUCT_OPS(userland_init_task, struct task_struct *p,
  263. struct scx_init_task_args *args)
  264. {
  265. if (bpf_task_storage_get(&task_ctx_stor, p, 0,
  266. BPF_LOCAL_STORAGE_GET_F_CREATE))
  267. return 0;
  268. else
  269. return -ENOMEM;
  270. }
  271. s32 BPF_STRUCT_OPS(userland_init)
  272. {
  273. if (num_possible_cpus == 0) {
  274. scx_bpf_error("User scheduler # CPUs uninitialized (%d)",
  275. num_possible_cpus);
  276. return -EINVAL;
  277. }
  278. if (usersched_pid <= 0) {
  279. scx_bpf_error("User scheduler pid uninitialized (%d)",
  280. usersched_pid);
  281. return -EINVAL;
  282. }
  283. return 0;
  284. }
  285. void BPF_STRUCT_OPS(userland_exit, struct scx_exit_info *ei)
  286. {
  287. UEI_RECORD(uei, ei);
  288. }
  289. SCX_OPS_DEFINE(userland_ops,
  290. .select_cpu = (void *)userland_select_cpu,
  291. .enqueue = (void *)userland_enqueue,
  292. .dispatch = (void *)userland_dispatch,
  293. .update_idle = (void *)userland_update_idle,
  294. .init_task = (void *)userland_init_task,
  295. .init = (void *)userland_init,
  296. .exit = (void *)userland_exit,
  297. .flags = SCX_OPS_ENQ_LAST |
  298. SCX_OPS_KEEP_BUILTIN_IDLE,
  299. .name = "userland");