scx_flatcg.bpf.c 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957
  1. /* SPDX-License-Identifier: GPL-2.0 */
  2. /*
  3. * A demo sched_ext flattened cgroup hierarchy scheduler. It implements
  4. * hierarchical weight-based cgroup CPU control by flattening the cgroup
  5. * hierarchy into a single layer by compounding the active weight share at each
  6. * level. Consider the following hierarchy with weights in parentheses:
  7. *
  8. * R + A (100) + B (100)
  9. * | \ C (100)
  10. * \ D (200)
  11. *
  12. * Ignoring the root and threaded cgroups, only B, C and D can contain tasks.
  13. * Let's say all three have runnable tasks. The total share that each of these
  14. * three cgroups is entitled to can be calculated by compounding its share at
  15. * each level.
  16. *
  17. * For example, B is competing against C and in that competition its share is
  18. * 100/(100+100) == 1/2. At its parent level, A is competing against D and A's
  19. * share in that competition is 100/(200+100) == 1/3. B's eventual share in the
  20. * system can be calculated by multiplying the two shares, 1/2 * 1/3 == 1/6. C's
  21. * eventual shaer is the same at 1/6. D is only competing at the top level and
  22. * its share is 200/(100+200) == 2/3.
  23. *
  24. * So, instead of hierarchically scheduling level-by-level, we can consider it
  25. * as B, C and D competing each other with respective share of 1/6, 1/6 and 2/3
  26. * and keep updating the eventual shares as the cgroups' runnable states change.
  27. *
  28. * This flattening of hierarchy can bring a substantial performance gain when
  29. * the cgroup hierarchy is nested multiple levels. in a simple benchmark using
  30. * wrk[8] on apache serving a CGI script calculating sha1sum of a small file, it
  31. * outperforms CFS by ~3% with CPU controller disabled and by ~10% with two
  32. * apache instances competing with 2:1 weight ratio nested four level deep.
  33. *
  34. * However, the gain comes at the cost of not being able to properly handle
  35. * thundering herd of cgroups. For example, if many cgroups which are nested
  36. * behind a low priority parent cgroup wake up around the same time, they may be
  37. * able to consume more CPU cycles than they are entitled to. In many use cases,
  38. * this isn't a real concern especially given the performance gain. Also, there
  39. * are ways to mitigate the problem further by e.g. introducing an extra
  40. * scheduling layer on cgroup delegation boundaries.
  41. *
  42. * The scheduler first picks the cgroup to run and then schedule the tasks
  43. * within by using nested weighted vtime scheduling by default. The
  44. * cgroup-internal scheduling can be switched to FIFO with the -f option.
  45. */
  46. #include <scx/common.bpf.h>
  47. #include "scx_flatcg.h"
  48. /*
  49. * Maximum amount of retries to find a valid cgroup.
  50. */
  51. enum {
  52. FALLBACK_DSQ = 0,
  53. CGROUP_MAX_RETRIES = 1024,
  54. };
  55. char _license[] SEC("license") = "GPL";
  56. const volatile u32 nr_cpus = 32; /* !0 for veristat, set during init */
  57. const volatile u64 cgrp_slice_ns = SCX_SLICE_DFL;
  58. const volatile bool fifo_sched;
  59. u64 cvtime_now;
  60. UEI_DEFINE(uei);
  61. struct {
  62. __uint(type, BPF_MAP_TYPE_PERCPU_ARRAY);
  63. __type(key, u32);
  64. __type(value, u64);
  65. __uint(max_entries, FCG_NR_STATS);
  66. } stats SEC(".maps");
  67. static void stat_inc(enum fcg_stat_idx idx)
  68. {
  69. u32 idx_v = idx;
  70. u64 *cnt_p = bpf_map_lookup_elem(&stats, &idx_v);
  71. if (cnt_p)
  72. (*cnt_p)++;
  73. }
  74. struct fcg_cpu_ctx {
  75. u64 cur_cgid;
  76. u64 cur_at;
  77. };
  78. struct {
  79. __uint(type, BPF_MAP_TYPE_PERCPU_ARRAY);
  80. __type(key, u32);
  81. __type(value, struct fcg_cpu_ctx);
  82. __uint(max_entries, 1);
  83. } cpu_ctx SEC(".maps");
  84. struct {
  85. __uint(type, BPF_MAP_TYPE_CGRP_STORAGE);
  86. __uint(map_flags, BPF_F_NO_PREALLOC);
  87. __type(key, int);
  88. __type(value, struct fcg_cgrp_ctx);
  89. } cgrp_ctx SEC(".maps");
  90. struct cgv_node {
  91. struct bpf_rb_node rb_node;
  92. __u64 cvtime;
  93. __u64 cgid;
  94. };
  95. private(CGV_TREE) struct bpf_spin_lock cgv_tree_lock;
  96. private(CGV_TREE) struct bpf_rb_root cgv_tree __contains(cgv_node, rb_node);
  97. struct cgv_node_stash {
  98. struct cgv_node __kptr *node;
  99. };
  100. struct {
  101. __uint(type, BPF_MAP_TYPE_HASH);
  102. __uint(max_entries, 16384);
  103. __type(key, __u64);
  104. __type(value, struct cgv_node_stash);
  105. } cgv_node_stash SEC(".maps");
  106. struct fcg_task_ctx {
  107. u64 bypassed_at;
  108. };
  109. struct {
  110. __uint(type, BPF_MAP_TYPE_TASK_STORAGE);
  111. __uint(map_flags, BPF_F_NO_PREALLOC);
  112. __type(key, int);
  113. __type(value, struct fcg_task_ctx);
  114. } task_ctx SEC(".maps");
  115. /* gets inc'd on weight tree changes to expire the cached hweights */
  116. u64 hweight_gen = 1;
  117. static u64 div_round_up(u64 dividend, u64 divisor)
  118. {
  119. return (dividend + divisor - 1) / divisor;
  120. }
  121. static bool vtime_before(u64 a, u64 b)
  122. {
  123. return (s64)(a - b) < 0;
  124. }
  125. static bool cgv_node_less(struct bpf_rb_node *a, const struct bpf_rb_node *b)
  126. {
  127. struct cgv_node *cgc_a, *cgc_b;
  128. cgc_a = container_of(a, struct cgv_node, rb_node);
  129. cgc_b = container_of(b, struct cgv_node, rb_node);
  130. return cgc_a->cvtime < cgc_b->cvtime;
  131. }
  132. static struct fcg_cpu_ctx *find_cpu_ctx(void)
  133. {
  134. struct fcg_cpu_ctx *cpuc;
  135. u32 idx = 0;
  136. cpuc = bpf_map_lookup_elem(&cpu_ctx, &idx);
  137. if (!cpuc) {
  138. scx_bpf_error("cpu_ctx lookup failed");
  139. return NULL;
  140. }
  141. return cpuc;
  142. }
  143. static struct fcg_cgrp_ctx *find_cgrp_ctx(struct cgroup *cgrp)
  144. {
  145. struct fcg_cgrp_ctx *cgc;
  146. cgc = bpf_cgrp_storage_get(&cgrp_ctx, cgrp, 0, 0);
  147. if (!cgc) {
  148. scx_bpf_error("cgrp_ctx lookup failed for cgid %llu", cgrp->kn->id);
  149. return NULL;
  150. }
  151. return cgc;
  152. }
  153. static struct fcg_cgrp_ctx *find_ancestor_cgrp_ctx(struct cgroup *cgrp, int level)
  154. {
  155. struct fcg_cgrp_ctx *cgc;
  156. cgrp = bpf_cgroup_ancestor(cgrp, level);
  157. if (!cgrp) {
  158. scx_bpf_error("ancestor cgroup lookup failed");
  159. return NULL;
  160. }
  161. cgc = find_cgrp_ctx(cgrp);
  162. if (!cgc)
  163. scx_bpf_error("ancestor cgrp_ctx lookup failed");
  164. bpf_cgroup_release(cgrp);
  165. return cgc;
  166. }
  167. static void cgrp_refresh_hweight(struct cgroup *cgrp, struct fcg_cgrp_ctx *cgc)
  168. {
  169. int level;
  170. if (!cgc->nr_active) {
  171. stat_inc(FCG_STAT_HWT_SKIP);
  172. return;
  173. }
  174. if (cgc->hweight_gen == hweight_gen) {
  175. stat_inc(FCG_STAT_HWT_CACHE);
  176. return;
  177. }
  178. stat_inc(FCG_STAT_HWT_UPDATES);
  179. bpf_for(level, 0, cgrp->level + 1) {
  180. struct fcg_cgrp_ctx *cgc;
  181. bool is_active;
  182. cgc = find_ancestor_cgrp_ctx(cgrp, level);
  183. if (!cgc)
  184. break;
  185. if (!level) {
  186. cgc->hweight = FCG_HWEIGHT_ONE;
  187. cgc->hweight_gen = hweight_gen;
  188. } else {
  189. struct fcg_cgrp_ctx *pcgc;
  190. pcgc = find_ancestor_cgrp_ctx(cgrp, level - 1);
  191. if (!pcgc)
  192. break;
  193. /*
  194. * We can be opportunistic here and not grab the
  195. * cgv_tree_lock and deal with the occasional races.
  196. * However, hweight updates are already cached and
  197. * relatively low-frequency. Let's just do the
  198. * straightforward thing.
  199. */
  200. bpf_spin_lock(&cgv_tree_lock);
  201. is_active = cgc->nr_active;
  202. if (is_active) {
  203. cgc->hweight_gen = pcgc->hweight_gen;
  204. cgc->hweight =
  205. div_round_up(pcgc->hweight * cgc->weight,
  206. pcgc->child_weight_sum);
  207. }
  208. bpf_spin_unlock(&cgv_tree_lock);
  209. if (!is_active) {
  210. stat_inc(FCG_STAT_HWT_RACE);
  211. break;
  212. }
  213. }
  214. }
  215. }
  216. static void cgrp_cap_budget(struct cgv_node *cgv_node, struct fcg_cgrp_ctx *cgc)
  217. {
  218. u64 delta, cvtime, max_budget;
  219. /*
  220. * A node which is on the rbtree can't be pointed to from elsewhere yet
  221. * and thus can't be updated and repositioned. Instead, we collect the
  222. * vtime deltas separately and apply it asynchronously here.
  223. */
  224. delta = __sync_fetch_and_sub(&cgc->cvtime_delta, cgc->cvtime_delta);
  225. cvtime = cgv_node->cvtime + delta;
  226. /*
  227. * Allow a cgroup to carry the maximum budget proportional to its
  228. * hweight such that a full-hweight cgroup can immediately take up half
  229. * of the CPUs at the most while staying at the front of the rbtree.
  230. */
  231. max_budget = (cgrp_slice_ns * nr_cpus * cgc->hweight) /
  232. (2 * FCG_HWEIGHT_ONE);
  233. if (vtime_before(cvtime, cvtime_now - max_budget))
  234. cvtime = cvtime_now - max_budget;
  235. cgv_node->cvtime = cvtime;
  236. }
  237. static void cgrp_enqueued(struct cgroup *cgrp, struct fcg_cgrp_ctx *cgc)
  238. {
  239. struct cgv_node_stash *stash;
  240. struct cgv_node *cgv_node;
  241. u64 cgid = cgrp->kn->id;
  242. /* paired with cmpxchg in try_pick_next_cgroup() */
  243. if (__sync_val_compare_and_swap(&cgc->queued, 0, 1)) {
  244. stat_inc(FCG_STAT_ENQ_SKIP);
  245. return;
  246. }
  247. stash = bpf_map_lookup_elem(&cgv_node_stash, &cgid);
  248. if (!stash) {
  249. scx_bpf_error("cgv_node lookup failed for cgid %llu", cgid);
  250. return;
  251. }
  252. /* NULL if the node is already on the rbtree */
  253. cgv_node = bpf_kptr_xchg(&stash->node, NULL);
  254. if (!cgv_node) {
  255. stat_inc(FCG_STAT_ENQ_RACE);
  256. return;
  257. }
  258. bpf_spin_lock(&cgv_tree_lock);
  259. cgrp_cap_budget(cgv_node, cgc);
  260. bpf_rbtree_add(&cgv_tree, &cgv_node->rb_node, cgv_node_less);
  261. bpf_spin_unlock(&cgv_tree_lock);
  262. }
  263. static void set_bypassed_at(struct task_struct *p, struct fcg_task_ctx *taskc)
  264. {
  265. /*
  266. * Tell fcg_stopping() that this bypassed the regular scheduling path
  267. * and should be force charged to the cgroup. 0 is used to indicate that
  268. * the task isn't bypassing, so if the current runtime is 0, go back by
  269. * one nanosecond.
  270. */
  271. taskc->bypassed_at = p->se.sum_exec_runtime ?: (u64)-1;
  272. }
  273. s32 BPF_STRUCT_OPS(fcg_select_cpu, struct task_struct *p, s32 prev_cpu, u64 wake_flags)
  274. {
  275. struct fcg_task_ctx *taskc;
  276. bool is_idle = false;
  277. s32 cpu;
  278. cpu = scx_bpf_select_cpu_dfl(p, prev_cpu, wake_flags, &is_idle);
  279. taskc = bpf_task_storage_get(&task_ctx, p, 0, 0);
  280. if (!taskc) {
  281. scx_bpf_error("task_ctx lookup failed");
  282. return cpu;
  283. }
  284. /*
  285. * If select_cpu_dfl() is recommending local enqueue, the target CPU is
  286. * idle. Follow it and charge the cgroup later in fcg_stopping() after
  287. * the fact.
  288. */
  289. if (is_idle) {
  290. set_bypassed_at(p, taskc);
  291. stat_inc(FCG_STAT_LOCAL);
  292. scx_bpf_dispatch(p, SCX_DSQ_LOCAL, SCX_SLICE_DFL, 0);
  293. }
  294. return cpu;
  295. }
  296. void BPF_STRUCT_OPS(fcg_enqueue, struct task_struct *p, u64 enq_flags)
  297. {
  298. struct fcg_task_ctx *taskc;
  299. struct cgroup *cgrp;
  300. struct fcg_cgrp_ctx *cgc;
  301. taskc = bpf_task_storage_get(&task_ctx, p, 0, 0);
  302. if (!taskc) {
  303. scx_bpf_error("task_ctx lookup failed");
  304. return;
  305. }
  306. /*
  307. * Use the direct dispatching and force charging to deal with tasks with
  308. * custom affinities so that we don't have to worry about per-cgroup
  309. * dq's containing tasks that can't be executed from some CPUs.
  310. */
  311. if (p->nr_cpus_allowed != nr_cpus) {
  312. set_bypassed_at(p, taskc);
  313. /*
  314. * The global dq is deprioritized as we don't want to let tasks
  315. * to boost themselves by constraining its cpumask. The
  316. * deprioritization is rather severe, so let's not apply that to
  317. * per-cpu kernel threads. This is ham-fisted. We probably wanna
  318. * implement per-cgroup fallback dq's instead so that we have
  319. * more control over when tasks with custom cpumask get issued.
  320. */
  321. if (p->nr_cpus_allowed == 1 && (p->flags & PF_KTHREAD)) {
  322. stat_inc(FCG_STAT_LOCAL);
  323. scx_bpf_dispatch(p, SCX_DSQ_LOCAL, SCX_SLICE_DFL, enq_flags);
  324. } else {
  325. stat_inc(FCG_STAT_GLOBAL);
  326. scx_bpf_dispatch(p, FALLBACK_DSQ, SCX_SLICE_DFL, enq_flags);
  327. }
  328. return;
  329. }
  330. cgrp = __COMPAT_scx_bpf_task_cgroup(p);
  331. cgc = find_cgrp_ctx(cgrp);
  332. if (!cgc)
  333. goto out_release;
  334. if (fifo_sched) {
  335. scx_bpf_dispatch(p, cgrp->kn->id, SCX_SLICE_DFL, enq_flags);
  336. } else {
  337. u64 tvtime = p->scx.dsq_vtime;
  338. /*
  339. * Limit the amount of budget that an idling task can accumulate
  340. * to one slice.
  341. */
  342. if (vtime_before(tvtime, cgc->tvtime_now - SCX_SLICE_DFL))
  343. tvtime = cgc->tvtime_now - SCX_SLICE_DFL;
  344. scx_bpf_dispatch_vtime(p, cgrp->kn->id, SCX_SLICE_DFL,
  345. tvtime, enq_flags);
  346. }
  347. cgrp_enqueued(cgrp, cgc);
  348. out_release:
  349. bpf_cgroup_release(cgrp);
  350. }
  351. /*
  352. * Walk the cgroup tree to update the active weight sums as tasks wake up and
  353. * sleep. The weight sums are used as the base when calculating the proportion a
  354. * given cgroup or task is entitled to at each level.
  355. */
  356. static void update_active_weight_sums(struct cgroup *cgrp, bool runnable)
  357. {
  358. struct fcg_cgrp_ctx *cgc;
  359. bool updated = false;
  360. int idx;
  361. cgc = find_cgrp_ctx(cgrp);
  362. if (!cgc)
  363. return;
  364. /*
  365. * In most cases, a hot cgroup would have multiple threads going to
  366. * sleep and waking up while the whole cgroup stays active. In leaf
  367. * cgroups, ->nr_runnable which is updated with __sync operations gates
  368. * ->nr_active updates, so that we don't have to grab the cgv_tree_lock
  369. * repeatedly for a busy cgroup which is staying active.
  370. */
  371. if (runnable) {
  372. if (__sync_fetch_and_add(&cgc->nr_runnable, 1))
  373. return;
  374. stat_inc(FCG_STAT_ACT);
  375. } else {
  376. if (__sync_sub_and_fetch(&cgc->nr_runnable, 1))
  377. return;
  378. stat_inc(FCG_STAT_DEACT);
  379. }
  380. /*
  381. * If @cgrp is becoming runnable, its hweight should be refreshed after
  382. * it's added to the weight tree so that enqueue has the up-to-date
  383. * value. If @cgrp is becoming quiescent, the hweight should be
  384. * refreshed before it's removed from the weight tree so that the usage
  385. * charging which happens afterwards has access to the latest value.
  386. */
  387. if (!runnable)
  388. cgrp_refresh_hweight(cgrp, cgc);
  389. /* propagate upwards */
  390. bpf_for(idx, 0, cgrp->level) {
  391. int level = cgrp->level - idx;
  392. struct fcg_cgrp_ctx *cgc, *pcgc = NULL;
  393. bool propagate = false;
  394. cgc = find_ancestor_cgrp_ctx(cgrp, level);
  395. if (!cgc)
  396. break;
  397. if (level) {
  398. pcgc = find_ancestor_cgrp_ctx(cgrp, level - 1);
  399. if (!pcgc)
  400. break;
  401. }
  402. /*
  403. * We need the propagation protected by a lock to synchronize
  404. * against weight changes. There's no reason to drop the lock at
  405. * each level but bpf_spin_lock() doesn't want any function
  406. * calls while locked.
  407. */
  408. bpf_spin_lock(&cgv_tree_lock);
  409. if (runnable) {
  410. if (!cgc->nr_active++) {
  411. updated = true;
  412. if (pcgc) {
  413. propagate = true;
  414. pcgc->child_weight_sum += cgc->weight;
  415. }
  416. }
  417. } else {
  418. if (!--cgc->nr_active) {
  419. updated = true;
  420. if (pcgc) {
  421. propagate = true;
  422. pcgc->child_weight_sum -= cgc->weight;
  423. }
  424. }
  425. }
  426. bpf_spin_unlock(&cgv_tree_lock);
  427. if (!propagate)
  428. break;
  429. }
  430. if (updated)
  431. __sync_fetch_and_add(&hweight_gen, 1);
  432. if (runnable)
  433. cgrp_refresh_hweight(cgrp, cgc);
  434. }
  435. void BPF_STRUCT_OPS(fcg_runnable, struct task_struct *p, u64 enq_flags)
  436. {
  437. struct cgroup *cgrp;
  438. cgrp = __COMPAT_scx_bpf_task_cgroup(p);
  439. update_active_weight_sums(cgrp, true);
  440. bpf_cgroup_release(cgrp);
  441. }
  442. void BPF_STRUCT_OPS(fcg_running, struct task_struct *p)
  443. {
  444. struct cgroup *cgrp;
  445. struct fcg_cgrp_ctx *cgc;
  446. if (fifo_sched)
  447. return;
  448. cgrp = __COMPAT_scx_bpf_task_cgroup(p);
  449. cgc = find_cgrp_ctx(cgrp);
  450. if (cgc) {
  451. /*
  452. * @cgc->tvtime_now always progresses forward as tasks start
  453. * executing. The test and update can be performed concurrently
  454. * from multiple CPUs and thus racy. Any error should be
  455. * contained and temporary. Let's just live with it.
  456. */
  457. if (vtime_before(cgc->tvtime_now, p->scx.dsq_vtime))
  458. cgc->tvtime_now = p->scx.dsq_vtime;
  459. }
  460. bpf_cgroup_release(cgrp);
  461. }
  462. void BPF_STRUCT_OPS(fcg_stopping, struct task_struct *p, bool runnable)
  463. {
  464. struct fcg_task_ctx *taskc;
  465. struct cgroup *cgrp;
  466. struct fcg_cgrp_ctx *cgc;
  467. /*
  468. * Scale the execution time by the inverse of the weight and charge.
  469. *
  470. * Note that the default yield implementation yields by setting
  471. * @p->scx.slice to zero and the following would treat the yielding task
  472. * as if it has consumed all its slice. If this penalizes yielding tasks
  473. * too much, determine the execution time by taking explicit timestamps
  474. * instead of depending on @p->scx.slice.
  475. */
  476. if (!fifo_sched)
  477. p->scx.dsq_vtime +=
  478. (SCX_SLICE_DFL - p->scx.slice) * 100 / p->scx.weight;
  479. taskc = bpf_task_storage_get(&task_ctx, p, 0, 0);
  480. if (!taskc) {
  481. scx_bpf_error("task_ctx lookup failed");
  482. return;
  483. }
  484. if (!taskc->bypassed_at)
  485. return;
  486. cgrp = __COMPAT_scx_bpf_task_cgroup(p);
  487. cgc = find_cgrp_ctx(cgrp);
  488. if (cgc) {
  489. __sync_fetch_and_add(&cgc->cvtime_delta,
  490. p->se.sum_exec_runtime - taskc->bypassed_at);
  491. taskc->bypassed_at = 0;
  492. }
  493. bpf_cgroup_release(cgrp);
  494. }
  495. void BPF_STRUCT_OPS(fcg_quiescent, struct task_struct *p, u64 deq_flags)
  496. {
  497. struct cgroup *cgrp;
  498. cgrp = __COMPAT_scx_bpf_task_cgroup(p);
  499. update_active_weight_sums(cgrp, false);
  500. bpf_cgroup_release(cgrp);
  501. }
  502. void BPF_STRUCT_OPS(fcg_cgroup_set_weight, struct cgroup *cgrp, u32 weight)
  503. {
  504. struct fcg_cgrp_ctx *cgc, *pcgc = NULL;
  505. cgc = find_cgrp_ctx(cgrp);
  506. if (!cgc)
  507. return;
  508. if (cgrp->level) {
  509. pcgc = find_ancestor_cgrp_ctx(cgrp, cgrp->level - 1);
  510. if (!pcgc)
  511. return;
  512. }
  513. bpf_spin_lock(&cgv_tree_lock);
  514. if (pcgc && cgc->nr_active)
  515. pcgc->child_weight_sum += (s64)weight - cgc->weight;
  516. cgc->weight = weight;
  517. bpf_spin_unlock(&cgv_tree_lock);
  518. }
  519. static bool try_pick_next_cgroup(u64 *cgidp)
  520. {
  521. struct bpf_rb_node *rb_node;
  522. struct cgv_node_stash *stash;
  523. struct cgv_node *cgv_node;
  524. struct fcg_cgrp_ctx *cgc;
  525. struct cgroup *cgrp;
  526. u64 cgid;
  527. /* pop the front cgroup and wind cvtime_now accordingly */
  528. bpf_spin_lock(&cgv_tree_lock);
  529. rb_node = bpf_rbtree_first(&cgv_tree);
  530. if (!rb_node) {
  531. bpf_spin_unlock(&cgv_tree_lock);
  532. stat_inc(FCG_STAT_PNC_NO_CGRP);
  533. *cgidp = 0;
  534. return true;
  535. }
  536. rb_node = bpf_rbtree_remove(&cgv_tree, rb_node);
  537. bpf_spin_unlock(&cgv_tree_lock);
  538. if (!rb_node) {
  539. /*
  540. * This should never happen. bpf_rbtree_first() was called
  541. * above while the tree lock was held, so the node should
  542. * always be present.
  543. */
  544. scx_bpf_error("node could not be removed");
  545. return true;
  546. }
  547. cgv_node = container_of(rb_node, struct cgv_node, rb_node);
  548. cgid = cgv_node->cgid;
  549. if (vtime_before(cvtime_now, cgv_node->cvtime))
  550. cvtime_now = cgv_node->cvtime;
  551. /*
  552. * If lookup fails, the cgroup's gone. Free and move on. See
  553. * fcg_cgroup_exit().
  554. */
  555. cgrp = bpf_cgroup_from_id(cgid);
  556. if (!cgrp) {
  557. stat_inc(FCG_STAT_PNC_GONE);
  558. goto out_free;
  559. }
  560. cgc = bpf_cgrp_storage_get(&cgrp_ctx, cgrp, 0, 0);
  561. if (!cgc) {
  562. bpf_cgroup_release(cgrp);
  563. stat_inc(FCG_STAT_PNC_GONE);
  564. goto out_free;
  565. }
  566. if (!scx_bpf_consume(cgid)) {
  567. bpf_cgroup_release(cgrp);
  568. stat_inc(FCG_STAT_PNC_EMPTY);
  569. goto out_stash;
  570. }
  571. /*
  572. * Successfully consumed from the cgroup. This will be our current
  573. * cgroup for the new slice. Refresh its hweight.
  574. */
  575. cgrp_refresh_hweight(cgrp, cgc);
  576. bpf_cgroup_release(cgrp);
  577. /*
  578. * As the cgroup may have more tasks, add it back to the rbtree. Note
  579. * that here we charge the full slice upfront and then exact later
  580. * according to the actual consumption. This prevents lowpri thundering
  581. * herd from saturating the machine.
  582. */
  583. bpf_spin_lock(&cgv_tree_lock);
  584. cgv_node->cvtime += cgrp_slice_ns * FCG_HWEIGHT_ONE / (cgc->hweight ?: 1);
  585. cgrp_cap_budget(cgv_node, cgc);
  586. bpf_rbtree_add(&cgv_tree, &cgv_node->rb_node, cgv_node_less);
  587. bpf_spin_unlock(&cgv_tree_lock);
  588. *cgidp = cgid;
  589. stat_inc(FCG_STAT_PNC_NEXT);
  590. return true;
  591. out_stash:
  592. stash = bpf_map_lookup_elem(&cgv_node_stash, &cgid);
  593. if (!stash) {
  594. stat_inc(FCG_STAT_PNC_GONE);
  595. goto out_free;
  596. }
  597. /*
  598. * Paired with cmpxchg in cgrp_enqueued(). If they see the following
  599. * transition, they'll enqueue the cgroup. If they are earlier, we'll
  600. * see their task in the dq below and requeue the cgroup.
  601. */
  602. __sync_val_compare_and_swap(&cgc->queued, 1, 0);
  603. if (scx_bpf_dsq_nr_queued(cgid)) {
  604. bpf_spin_lock(&cgv_tree_lock);
  605. bpf_rbtree_add(&cgv_tree, &cgv_node->rb_node, cgv_node_less);
  606. bpf_spin_unlock(&cgv_tree_lock);
  607. stat_inc(FCG_STAT_PNC_RACE);
  608. } else {
  609. cgv_node = bpf_kptr_xchg(&stash->node, cgv_node);
  610. if (cgv_node) {
  611. scx_bpf_error("unexpected !NULL cgv_node stash");
  612. goto out_free;
  613. }
  614. }
  615. return false;
  616. out_free:
  617. bpf_obj_drop(cgv_node);
  618. return false;
  619. }
  620. void BPF_STRUCT_OPS(fcg_dispatch, s32 cpu, struct task_struct *prev)
  621. {
  622. struct fcg_cpu_ctx *cpuc;
  623. struct fcg_cgrp_ctx *cgc;
  624. struct cgroup *cgrp;
  625. u64 now = bpf_ktime_get_ns();
  626. bool picked_next = false;
  627. cpuc = find_cpu_ctx();
  628. if (!cpuc)
  629. return;
  630. if (!cpuc->cur_cgid)
  631. goto pick_next_cgroup;
  632. if (vtime_before(now, cpuc->cur_at + cgrp_slice_ns)) {
  633. if (scx_bpf_consume(cpuc->cur_cgid)) {
  634. stat_inc(FCG_STAT_CNS_KEEP);
  635. return;
  636. }
  637. stat_inc(FCG_STAT_CNS_EMPTY);
  638. } else {
  639. stat_inc(FCG_STAT_CNS_EXPIRE);
  640. }
  641. /*
  642. * The current cgroup is expiring. It was already charged a full slice.
  643. * Calculate the actual usage and accumulate the delta.
  644. */
  645. cgrp = bpf_cgroup_from_id(cpuc->cur_cgid);
  646. if (!cgrp) {
  647. stat_inc(FCG_STAT_CNS_GONE);
  648. goto pick_next_cgroup;
  649. }
  650. cgc = bpf_cgrp_storage_get(&cgrp_ctx, cgrp, 0, 0);
  651. if (cgc) {
  652. /*
  653. * We want to update the vtime delta and then look for the next
  654. * cgroup to execute but the latter needs to be done in a loop
  655. * and we can't keep the lock held. Oh well...
  656. */
  657. bpf_spin_lock(&cgv_tree_lock);
  658. __sync_fetch_and_add(&cgc->cvtime_delta,
  659. (cpuc->cur_at + cgrp_slice_ns - now) *
  660. FCG_HWEIGHT_ONE / (cgc->hweight ?: 1));
  661. bpf_spin_unlock(&cgv_tree_lock);
  662. } else {
  663. stat_inc(FCG_STAT_CNS_GONE);
  664. }
  665. bpf_cgroup_release(cgrp);
  666. pick_next_cgroup:
  667. cpuc->cur_at = now;
  668. if (scx_bpf_consume(FALLBACK_DSQ)) {
  669. cpuc->cur_cgid = 0;
  670. return;
  671. }
  672. bpf_repeat(CGROUP_MAX_RETRIES) {
  673. if (try_pick_next_cgroup(&cpuc->cur_cgid)) {
  674. picked_next = true;
  675. break;
  676. }
  677. }
  678. /*
  679. * This only happens if try_pick_next_cgroup() races against enqueue
  680. * path for more than CGROUP_MAX_RETRIES times, which is extremely
  681. * unlikely and likely indicates an underlying bug. There shouldn't be
  682. * any stall risk as the race is against enqueue.
  683. */
  684. if (!picked_next)
  685. stat_inc(FCG_STAT_PNC_FAIL);
  686. }
  687. s32 BPF_STRUCT_OPS(fcg_init_task, struct task_struct *p,
  688. struct scx_init_task_args *args)
  689. {
  690. struct fcg_task_ctx *taskc;
  691. struct fcg_cgrp_ctx *cgc;
  692. /*
  693. * @p is new. Let's ensure that its task_ctx is available. We can sleep
  694. * in this function and the following will automatically use GFP_KERNEL.
  695. */
  696. taskc = bpf_task_storage_get(&task_ctx, p, 0,
  697. BPF_LOCAL_STORAGE_GET_F_CREATE);
  698. if (!taskc)
  699. return -ENOMEM;
  700. taskc->bypassed_at = 0;
  701. if (!(cgc = find_cgrp_ctx(args->cgroup)))
  702. return -ENOENT;
  703. p->scx.dsq_vtime = cgc->tvtime_now;
  704. return 0;
  705. }
  706. int BPF_STRUCT_OPS_SLEEPABLE(fcg_cgroup_init, struct cgroup *cgrp,
  707. struct scx_cgroup_init_args *args)
  708. {
  709. struct fcg_cgrp_ctx *cgc;
  710. struct cgv_node *cgv_node;
  711. struct cgv_node_stash empty_stash = {}, *stash;
  712. u64 cgid = cgrp->kn->id;
  713. int ret;
  714. /*
  715. * Technically incorrect as cgroup ID is full 64bit while dsq ID is
  716. * 63bit. Should not be a problem in practice and easy to spot in the
  717. * unlikely case that it breaks.
  718. */
  719. ret = scx_bpf_create_dsq(cgid, -1);
  720. if (ret)
  721. return ret;
  722. cgc = bpf_cgrp_storage_get(&cgrp_ctx, cgrp, 0,
  723. BPF_LOCAL_STORAGE_GET_F_CREATE);
  724. if (!cgc) {
  725. ret = -ENOMEM;
  726. goto err_destroy_dsq;
  727. }
  728. cgc->weight = args->weight;
  729. cgc->hweight = FCG_HWEIGHT_ONE;
  730. ret = bpf_map_update_elem(&cgv_node_stash, &cgid, &empty_stash,
  731. BPF_NOEXIST);
  732. if (ret) {
  733. if (ret != -ENOMEM)
  734. scx_bpf_error("unexpected stash creation error (%d)",
  735. ret);
  736. goto err_destroy_dsq;
  737. }
  738. stash = bpf_map_lookup_elem(&cgv_node_stash, &cgid);
  739. if (!stash) {
  740. scx_bpf_error("unexpected cgv_node stash lookup failure");
  741. ret = -ENOENT;
  742. goto err_destroy_dsq;
  743. }
  744. cgv_node = bpf_obj_new(struct cgv_node);
  745. if (!cgv_node) {
  746. ret = -ENOMEM;
  747. goto err_del_cgv_node;
  748. }
  749. cgv_node->cgid = cgid;
  750. cgv_node->cvtime = cvtime_now;
  751. cgv_node = bpf_kptr_xchg(&stash->node, cgv_node);
  752. if (cgv_node) {
  753. scx_bpf_error("unexpected !NULL cgv_node stash");
  754. ret = -EBUSY;
  755. goto err_drop;
  756. }
  757. return 0;
  758. err_drop:
  759. bpf_obj_drop(cgv_node);
  760. err_del_cgv_node:
  761. bpf_map_delete_elem(&cgv_node_stash, &cgid);
  762. err_destroy_dsq:
  763. scx_bpf_destroy_dsq(cgid);
  764. return ret;
  765. }
  766. void BPF_STRUCT_OPS(fcg_cgroup_exit, struct cgroup *cgrp)
  767. {
  768. u64 cgid = cgrp->kn->id;
  769. /*
  770. * For now, there's no way find and remove the cgv_node if it's on the
  771. * cgv_tree. Let's drain them in the dispatch path as they get popped
  772. * off the front of the tree.
  773. */
  774. bpf_map_delete_elem(&cgv_node_stash, &cgid);
  775. scx_bpf_destroy_dsq(cgid);
  776. }
  777. void BPF_STRUCT_OPS(fcg_cgroup_move, struct task_struct *p,
  778. struct cgroup *from, struct cgroup *to)
  779. {
  780. struct fcg_cgrp_ctx *from_cgc, *to_cgc;
  781. s64 vtime_delta;
  782. /* find_cgrp_ctx() triggers scx_ops_error() on lookup failures */
  783. if (!(from_cgc = find_cgrp_ctx(from)) || !(to_cgc = find_cgrp_ctx(to)))
  784. return;
  785. vtime_delta = p->scx.dsq_vtime - from_cgc->tvtime_now;
  786. p->scx.dsq_vtime = to_cgc->tvtime_now + vtime_delta;
  787. }
  788. s32 BPF_STRUCT_OPS_SLEEPABLE(fcg_init)
  789. {
  790. return scx_bpf_create_dsq(FALLBACK_DSQ, -1);
  791. }
  792. void BPF_STRUCT_OPS(fcg_exit, struct scx_exit_info *ei)
  793. {
  794. UEI_RECORD(uei, ei);
  795. }
  796. SCX_OPS_DEFINE(flatcg_ops,
  797. .select_cpu = (void *)fcg_select_cpu,
  798. .enqueue = (void *)fcg_enqueue,
  799. .dispatch = (void *)fcg_dispatch,
  800. .runnable = (void *)fcg_runnable,
  801. .running = (void *)fcg_running,
  802. .stopping = (void *)fcg_stopping,
  803. .quiescent = (void *)fcg_quiescent,
  804. .init_task = (void *)fcg_init_task,
  805. .cgroup_set_weight = (void *)fcg_cgroup_set_weight,
  806. .cgroup_init = (void *)fcg_cgroup_init,
  807. .cgroup_exit = (void *)fcg_cgroup_exit,
  808. .cgroup_move = (void *)fcg_cgroup_move,
  809. .init = (void *)fcg_init,
  810. .exit = (void *)fcg_exit,
  811. .flags = SCX_OPS_HAS_CGROUP_WEIGHT | SCX_OPS_ENQ_EXITING,
  812. .name = "flatcg");