Debian Codegraph @

tools/sched_ext/scx_sdt.bpf.c

raw
1 /* SPDX-License-Identifier: GPL-2.0 */
2 /*
3 * Arena-based task data scheduler. This is a variation of scx_simple
4 * that uses a combined allocator and indexing structure to organize
5 * task data. Task context allocation is done when a task enters the
6 * scheduler, while freeing is done when it exits. Task contexts are
7 * retrieved from task-local storage, pointing to the allocated memory.
8 *
9 * The main purpose of this scheduler is to demostrate arena memory
10 * management.
11 *
12 * Copyright (c) 2024-2025 Meta Platforms, Inc. and affiliates.
13 * Copyright (c) 2024-2025 Emil Tsalapatis <[email protected]>
14 * Copyright (c) 2024-2025 Tejun Heo <[email protected]>
15 *
16 */
17 #include <scx/common.bpf.h>
18 #include <scx/bpf_arena_common.bpf.h>
19
20 #include "scx_sdt.h"
21
22 char _license[] SEC("license") = "GPL";
23
24 UEI_DEFINE(uei);
25
26 struct {
27 __uint(type, BPF_MAP_TYPE_ARENA);
28 __uint(map_flags, BPF_F_MMAPABLE);
29 #if defined(__TARGET_ARCH_arm64) || defined(__aarch64__)
30 __uint(max_entries, 1 << 16); /* number of pages */
31 __ulong(map_extra, (1ull << 32)); /* start of mmap() region */
32 #else
33 __uint(max_entries, 1 << 20); /* number of pages */
34 __ulong(map_extra, (1ull << 44)); /* start of mmap() region */
35 #endif
36 } arena __weak SEC(".maps");
37
38 #define SHARED_DSQ 0
39
40 #define DEFINE_SDT_STAT(metric) \
41 static inline void \
42 stat_inc_##metric(struct scx_stats __arena *stats) \
43 { \
44 cast_kern(stats); \
45 stats->metric += 1; \
46 } \
47 __u64 stat_##metric; \
48
49 DEFINE_SDT_STAT(enqueue);
50 DEFINE_SDT_STAT(init);
51 DEFINE_SDT_STAT(exit);
52 DEFINE_SDT_STAT(select_idle_cpu);
53 DEFINE_SDT_STAT(select_busy_cpu);
54
55 /*
56 * Necessary for cond_break/can_loop's semantics. According to kernel commit
57 * 011832b, the loop counter variable must be seen as imprecise and bounded
58 * by the verifier. Initializing it from a constant (e.g., i = 0;), then,
59 * makes it precise and prevents may_goto from helping with converging the
60 * loop. For these loops we must initialize the loop counter from a variable
61 * whose value the verifier cannot reason about when checking the program, so
62 * that the loop counter's value is imprecise.
63 */
64 static __u64 zero = 0;
65
66 /*
67 * XXX Hack to get the verifier to find the arena for sdt_exit_task.
68 * As of 6.12-rc5, The verifier associates arenas with programs by
69 * checking LD.IMM instruction operands for an arena and populating
70 * the program state with the first instance it finds. This requires
71 * accessing our global arena variable, but scx methods do not necessarily
72 * do so while still using pointers from that arena. Insert a bpf_printk
73 * statement that triggers at most once to generate an LD.IMM instruction
74 * to access the arena and help the verifier.
75 */
76 static volatile bool scx_arena_verify_once;
77
78 __hidden void scx_arena_subprog_init(void)
79 {
80 if (scx_arena_verify_once)
81 return;
82
83 bpf_printk("%s: arena pointer %p", __func__, &arena);
84 scx_arena_verify_once = true;
85 }
86
87
88 private(LOCK) struct bpf_spin_lock alloc_lock;
89 private(POOL_LOCK) struct bpf_spin_lock alloc_pool_lock;
90
91 /* allocation pools */
92 struct sdt_pool desc_pool;
93 struct sdt_pool chunk_pool;
94
95 /* Protected by alloc_lock. */
96 struct scx_alloc_stats alloc_stats;
97
98
99 /* Allocate element from the pool. Must be called with a then pool lock held. */
100 static
101 void __arena *scx_alloc_from_pool(struct sdt_pool *pool)
102 {
103 __u64 elem_size, max_elems;
104 void __arena *slab;
105 void __arena *ptr;
106
107 elem_size = pool->elem_size;
108 max_elems = pool->max_elems;
109
110 /* If the chunk is spent, get a new one. */
111 if (pool->idx >= max_elems) {
112 slab = bpf_arena_alloc_pages(&arena, NULL,
113 div_round_up(max_elems * elem_size, PAGE_SIZE), NUMA_NO_NODE, 0);
114 if (!slab)
115 return NULL;
116
117 pool->slab = slab;
118 pool->idx = 0;
119 }
120
121 ptr = (void __arena *)((__u64) pool->slab + elem_size * pool->idx);
122 pool->idx += 1;
123
124 return ptr;
125 }
126
127 /* Alloc desc and associated chunk. Called with the allocator spinlock held. */
128 static sdt_desc_t *scx_alloc_chunk(void)
129 {
130 struct sdt_chunk __arena *chunk;
131 sdt_desc_t *desc;
132 sdt_desc_t *out;
133
134 chunk = scx_alloc_from_pool(&chunk_pool);
135 if (!chunk)
136 return NULL;
137
138 desc = scx_alloc_from_pool(&desc_pool);
139 if (!desc) {
140 /*
141 * Effectively frees the previous chunk allocation.
142 * Index cannot be 0, so decrementing is always
143 * valid.
144 */
145 chunk_pool.idx -= 1;
146 return NULL;
147 }
148
149 out = desc;
150
151 desc->nr_free = SDT_TASK_ENTS_PER_CHUNK;
152 desc->chunk = chunk;
153
154 alloc_stats.chunk_allocs += 1;
155
156 return out;
157 }
158
159 static int pool_set_size(struct sdt_pool *pool, __u64 data_size, __u64 nr_pages)
160 {
161 if (unlikely(data_size % 8))
162 return -EINVAL;
163
164 if (unlikely(nr_pages == 0))
165 return -EINVAL;
166
167 pool->elem_size = data_size;
168 pool->max_elems = (PAGE_SIZE * nr_pages) / pool->elem_size;
169 /* Populate the pool slab on the first allocation. */
170 pool->idx = pool->max_elems;
171
172 return 0;
173 }
174
175 /* Initialize both the base pool allocators and the root chunk of the index. */
176 __hidden int
177 scx_alloc_init(struct scx_allocator *alloc, __u64 data_size)
178 {
179 size_t min_chunk_size;
180 int ret;
181
182 _Static_assert(sizeof(struct sdt_chunk) <= PAGE_SIZE,
183 "chunk size must fit into a page");
184
185 ret = pool_set_size(&chunk_pool, sizeof(struct sdt_chunk), 1);
186 if (ret != 0)
187 return ret;
188
189 ret = pool_set_size(&desc_pool, sizeof(struct sdt_desc), 1);
190 if (ret != 0)
191 return ret;
192
193 /* Wrap data into a descriptor and word align. */
194 data_size += sizeof(struct sdt_data);
195 data_size = round_up(data_size, 8);
196
197 /*
198 * Ensure we allocate large enough chunks from the arena to avoid excessive
199 * internal fragmentation when turning chunks it into structs.
200 */
201 min_chunk_size = div_round_up(SDT_TASK_MIN_ELEM_PER_ALLOC * data_size, PAGE_SIZE);
202 ret = pool_set_size(&alloc->pool, data_size, min_chunk_size);
203 if (ret != 0)
204 return ret;
205
206 bpf_spin_lock(&alloc_lock);
207 alloc->root = scx_alloc_chunk();
208 bpf_spin_unlock(&alloc_lock);
209 if (!alloc->root)
210 return -ENOMEM;
211
212 return 0;
213 }
214
215 static
216 int set_idx_state(sdt_desc_t *desc, __u64 pos, bool state)
217 {
218 __u64 __arena *allocated = desc->allocated;
219 __u64 bit;
220
221 if (unlikely(pos >= SDT_TASK_ENTS_PER_CHUNK))
222 return -EINVAL;
223
224 bit = (__u64)1 << (pos % 64);
225
226 if (state)
227 allocated[pos / 64] |= bit;
228 else
229 allocated[pos / 64] &= ~bit;
230
231 return 0;
232 }
233
234 static __noinline
235 int mark_nodes_avail(sdt_desc_t *lv_desc[SDT_TASK_LEVELS], __u64 lv_pos[SDT_TASK_LEVELS])
236 {
237 sdt_desc_t *desc;
238 __u64 u, level;
239 int ret;
240
241 for (u = zero; u < SDT_TASK_LEVELS && can_loop; u++) {
242 level = SDT_TASK_LEVELS - 1 - u;
243
244 /* Only propagate upwards if we are the parent's only free chunk. */
245 desc = lv_desc[level];
246
247 ret = set_idx_state(desc, lv_pos[level], false);
248 if (unlikely(ret != 0))
249 return ret;
250
251 desc->nr_free += 1;
252 if (desc->nr_free > 1)
253 return 0;
254 }
255
256 return 0;
257 }
258
259 /*
260 * Free the allocated struct with the given index. Called with the
261 * allocator lock taken.
262 */
263 __hidden
264 int scx_alloc_free_idx(struct scx_allocator *alloc, __u64 idx)
265 {
266 const __u64 mask = (1 << SDT_TASK_ENTS_PER_PAGE_SHIFT) - 1;
267 sdt_desc_t *lv_desc[SDT_TASK_LEVELS];
268 sdt_desc_t * __arena *desc_children;
269 struct sdt_chunk __arena *chunk;
270 sdt_desc_t *desc;
271 struct sdt_data __arena *data;
272 __u64 level, shift, pos;
273 __u64 lv_pos[SDT_TASK_LEVELS];
274 int ret;
275 int i;
276
277 if (!alloc)
278 return 0;
279
280 desc = alloc->root;
281 if (unlikely(!desc))
282 return -EINVAL;
283
284 /* To appease the verifier. */
285 for (level = zero; level < SDT_TASK_LEVELS && can_loop; level++) {
286 lv_desc[level] = NULL;
287 lv_pos[level] = 0;
288 }
289
290 /* Find the leaf node containing the index. */
291 for (level = zero; level < SDT_TASK_LEVELS && can_loop; level++) {
292 shift = (SDT_TASK_LEVELS - 1 - level) * SDT_TASK_ENTS_PER_PAGE_SHIFT;
293 pos = (idx >> shift) & mask;
294
295 lv_desc[level] = desc;
296 lv_pos[level] = pos;
297
298 if (level == SDT_TASK_LEVELS - 1)
299 break;
300
301 chunk = desc->chunk;
302
303 desc_children = (sdt_desc_t * __arena *)chunk->descs;
304 desc = desc_children[pos];
305
306 if (unlikely(!desc))
307 return -EINVAL;
308 }
309
310 chunk = desc->chunk;
311
312 pos = idx & mask;
313 data = chunk->data[pos];
314 if (likely(data)) {
315 *data = (struct sdt_data) {
316 .tid.genn = data->tid.genn + 1,
317 };
318
319 /* Zero out one word at a time. */
320 for (i = zero; i < (alloc->pool.elem_size - sizeof(struct sdt_data)) / 8
321 && can_loop; i++) {
322 data->payload[i] = 0;
323 }
324 }
325
326 ret = mark_nodes_avail(lv_desc, lv_pos);
327 if (unlikely(ret != 0))
328 return ret;
329
330 alloc_stats.active_allocs -= 1;
331 alloc_stats.free_ops += 1;
332
333 return 0;
334 }
335
336 static inline
337 int ffs(__u64 word)
338 {
339 unsigned int num = 0;
340
341 if ((word & 0xffffffff) == 0) {
342 num += 32;
343 word >>= 32;
344 }
345
346 if ((word & 0xffff) == 0) {
347 num += 16;
348 word >>= 16;
349 }
350
351 if ((word & 0xff) == 0) {
352 num += 8;
353 word >>= 8;
354 }
355
356 if ((word & 0xf) == 0) {
357 num += 4;
358 word >>= 4;
359 }
360
361 if ((word & 0x3) == 0) {
362 num += 2;
363 word >>= 2;
364 }
365
366 if ((word & 0x1) == 0) {
367 num += 1;
368 word >>= 1;
369 }
370
371 return num;
372 }
373
374
375 /* find the first empty slot */
376 __hidden
377 __u64 chunk_find_empty(sdt_desc_t __arg_arena *desc)
378 {
379 __u64 freeslots;
380 __u64 i;
381
382 for (i = 0; i < SDT_TASK_CHUNK_BITMAP_U64S; i++) {
383 freeslots = ~desc->allocated[i];
384 if (freeslots == (__u64)0)
385 continue;
386
387 return (i * 64) + ffs(freeslots);
388 }
389
390 return SDT_TASK_ENTS_PER_CHUNK;
391 }
392
393 /*
394 * Find and return an available idx on the allocator.
395 * Called with the task spinlock held.
396 */
397 static sdt_desc_t * desc_find_empty(sdt_desc_t *desc, __u64 *idxp)
398 {
399 sdt_desc_t *lv_desc[SDT_TASK_LEVELS];
400 sdt_desc_t * __arena *desc_children;
401 struct sdt_chunk __arena *chunk;
402 sdt_desc_t *tmp;
403 __u64 lv_pos[SDT_TASK_LEVELS];
404 __u64 u, pos, level;
405 __u64 idx = 0;
406 int ret;
407
408 for (level = zero; level < SDT_TASK_LEVELS && can_loop; level++) {
409 pos = chunk_find_empty(desc);
410
411 /* If we error out, something has gone very wrong. */
412 if (unlikely(pos > SDT_TASK_ENTS_PER_CHUNK))
413 return NULL;
414
415 if (pos == SDT_TASK_ENTS_PER_CHUNK)
416 return NULL;
417
418 idx <<= SDT_TASK_ENTS_PER_PAGE_SHIFT;
419 idx |= pos;
420
421 /* Log the levels to complete allocation. */
422 lv_desc[level] = desc;
423 lv_pos[level] = pos;
424
425 /* The rest of the loop is for internal node traversal. */
426 if (level == SDT_TASK_LEVELS - 1)
427 break;
428
429 /* Allocate an internal node if necessary. */
430 chunk = desc->chunk;
431 desc_children = (sdt_desc_t * __arena *)chunk->descs;
432
433 desc = desc_children[pos];
434 if (!desc) {
435 desc = scx_alloc_chunk();
436 if (!desc)
437 return NULL;
438
439 desc_children[pos] = desc;
440 }
441 }
442
443 /*
444 * Finding the descriptor along with any internal node
445 * allocations was successful. Update all levels with
446 * the new allocation.
447 */
448 bpf_for(u, 0, SDT_TASK_LEVELS) {
449 level = SDT_TASK_LEVELS - 1 - u;
450 tmp = lv_desc[level];
451
452 ret = set_idx_state(tmp, lv_pos[level], true);
453 if (ret != 0)
454 break;
455
456 tmp->nr_free -= 1;
457 if (tmp->nr_free > 0)
458 break;
459 }
460
461 *idxp = idx;
462
463 return desc;
464 }
465
466 __hidden
467 void __arena *scx_alloc(struct scx_allocator *alloc)
468 {
469 struct sdt_data __arena *data = NULL;
470 struct sdt_chunk __arena *chunk;
471 sdt_desc_t *desc;
472 __u64 idx, pos;
473
474 if (!alloc)
475 return NULL;
476
477 bpf_spin_lock(&alloc_lock);
478
479 /* We unlock if we encounter an error in the function. */
480 desc = desc_find_empty(alloc->root, &idx);
481 if (unlikely(desc == NULL)) {
482 bpf_spin_unlock(&alloc_lock);
483 return NULL;
484 }
485
486 chunk = desc->chunk;
487
488 /* Populate the leaf node if necessary. */
489 pos = idx & (SDT_TASK_ENTS_PER_CHUNK - 1);
490 data = chunk->data[pos];
491 if (!data) {
492 data = scx_alloc_from_pool(&alloc->pool);
493 if (!data) {
494 scx_alloc_free_idx(alloc, idx);
495 bpf_spin_unlock(&alloc_lock);
496 return NULL;
497 }
498 }
499
500 chunk->data[pos] = data;
501
502 /* The data counts as a chunk */
503 alloc_stats.data_allocs += 1;
504 alloc_stats.alloc_ops += 1;
505 alloc_stats.active_allocs += 1;
506
507 data->tid.idx = idx;
508
509 bpf_spin_unlock(&alloc_lock);
510
511 return data;
512 }
513
514 /*
515 * Task BPF map entry recording the task's assigned ID and pointing to the data
516 * area allocated in arena.
517 */
518 struct scx_task_map_val {
519 union sdt_id tid;
520 __u64 tptr;
521 struct sdt_data __arena *data;
522 };
523
524 struct {
525 __uint(type, BPF_MAP_TYPE_TASK_STORAGE);
526 __uint(map_flags, BPF_F_NO_PREALLOC);
527 __type(key, int);
528 __type(value, struct scx_task_map_val);
529 } scx_task_map SEC(".maps");
530
531 static struct scx_allocator scx_task_allocator;
532
533 __hidden
534 void __arena *scx_task_alloc(struct task_struct *p)
535 {
536 struct sdt_data __arena *data = NULL;
537 struct scx_task_map_val *mval;
538
539 mval = bpf_task_storage_get(&scx_task_map, p, 0,
540 BPF_LOCAL_STORAGE_GET_F_CREATE);
541 if (!mval)
542 return NULL;
543
544 data = scx_alloc(&scx_task_allocator);
545 if (unlikely(!data))
546 return NULL;
547
548 mval->tid = data->tid;
549 mval->tptr = (__u64) p;
550 mval->data = data;
551
552 return (void __arena *)data->payload;
553 }
554
555 __hidden
556 int scx_task_init(__u64 data_size)
557 {
558 return scx_alloc_init(&scx_task_allocator, data_size);
559 }
560
561 __hidden
562 void __arena *scx_task_data(struct task_struct *p)
563 {
564 struct sdt_data __arena *data;
565 struct scx_task_map_val *mval;
566
567 scx_arena_subprog_init();
568
569 mval = bpf_task_storage_get(&scx_task_map, p, 0, 0);
570 if (!mval)
571 return NULL;
572
573 data = mval->data;
574
575 return (void __arena *)data->payload;
576 }
577
578 __hidden
579 void scx_task_free(struct task_struct *p)
580 {
581 struct scx_task_map_val *mval;
582
583 scx_arena_subprog_init();
584
585 mval = bpf_task_storage_get(&scx_task_map, p, 0, 0);
586 if (!mval)
587 return;
588
589 bpf_spin_lock(&alloc_lock);
590 scx_alloc_free_idx(&scx_task_allocator, mval->tid.idx);
591 bpf_spin_unlock(&alloc_lock);
592
593 bpf_task_storage_delete(&scx_task_map, p);
594 }
595
596 static inline void
597 scx_stat_global_update(struct scx_stats __arena *stats)
598 {
599 cast_kern(stats);
600 __sync_fetch_and_add(&stat_enqueue, stats->enqueue);
601 __sync_fetch_and_add(&stat_init, stats->init);
602 __sync_fetch_and_add(&stat_exit, stats->exit);
603 __sync_fetch_and_add(&stat_select_idle_cpu, stats->select_idle_cpu);
604 __sync_fetch_and_add(&stat_select_busy_cpu, stats->select_busy_cpu);
605 }
606
607 s32 BPF_STRUCT_OPS(sdt_select_cpu, struct task_struct *p, s32 prev_cpu, u64 wake_flags)
608 {
609 struct scx_stats __arena *stats;
610 bool is_idle = false;
611 s32 cpu;
612
613 stats = scx_task_data(p);
614 if (!stats) {
615 scx_bpf_error("%s: no stats for pid %d", __func__, p->pid);
616 return 0;
617 }
618
619 cpu = scx_bpf_select_cpu_dfl(p, prev_cpu, wake_flags, &is_idle);
620 if (is_idle) {
621 stat_inc_select_idle_cpu(stats);
622 scx_bpf_dsq_insert(p, SCX_DSQ_LOCAL, SCX_SLICE_DFL, 0);
623 } else {
624 stat_inc_select_busy_cpu(stats);
625 }
626
627 return cpu;
628 }
629
630 void BPF_STRUCT_OPS(sdt_enqueue, struct task_struct *p, u64 enq_flags)
631 {
632 struct scx_stats __arena *stats;
633
634 stats = scx_task_data(p);
635 if (!stats) {
636 scx_bpf_error("%s: no stats for pid %d", __func__, p->pid);
637 return;
638 }
639
640 stat_inc_enqueue(stats);
641
642 scx_bpf_dsq_insert(p, SHARED_DSQ, SCX_SLICE_DFL, enq_flags);
643 }
644
645 void BPF_STRUCT_OPS(sdt_dispatch, s32 cpu, struct task_struct *prev)
646 {
647 scx_bpf_dsq_move_to_local(SHARED_DSQ);
648 }
649
650 s32 BPF_STRUCT_OPS_SLEEPABLE(sdt_init_task, struct task_struct *p,
651 struct scx_init_task_args *args)
652 {
653 struct scx_stats __arena *stats;
654
655 stats = scx_task_alloc(p);
656 if (!stats) {
657 scx_bpf_error("arena allocator out of memory");
658 return -ENOMEM;
659 }
660
661 stats->pid = p->pid;
662
663 stat_inc_init(stats);
664
665 return 0;
666 }
667
668 void BPF_STRUCT_OPS(sdt_exit_task, struct task_struct *p,
669 struct scx_exit_task_args *args)
670 {
671 struct scx_stats __arena *stats;
672
673 stats = scx_task_data(p);
674 if (!stats) {
675 scx_bpf_error("%s: no stats for pid %d", __func__, p->pid);
676 return;
677 }
678
679 stat_inc_exit(stats);
680 scx_stat_global_update(stats);
681
682 scx_task_free(p);
683 }
684
685 s32 BPF_STRUCT_OPS_SLEEPABLE(sdt_init)
686 {
687 int ret;
688
689 ret = scx_task_init(sizeof(struct scx_stats));
690 if (ret < 0) {
691 scx_bpf_error("%s: failed with %d", __func__, ret);
692 return ret;
693 }
694
695 ret = scx_bpf_create_dsq(SHARED_DSQ, -1);
696 if (ret) {
697 scx_bpf_error("failed to create DSQ %d (%d)", SHARED_DSQ, ret);
698 return ret;
699 }
700
701 return 0;
702 }
703
704 void BPF_STRUCT_OPS(sdt_exit, struct scx_exit_info *ei)
705 {
706 UEI_RECORD(uei, ei);
707 }
708
709 SCX_OPS_DEFINE(sdt_ops,
710 .select_cpu = (void *)sdt_select_cpu,
711 .enqueue = (void *)sdt_enqueue,
712 .dispatch = (void *)sdt_dispatch,
713 .init_task = (void *)sdt_init_task,
714 .exit_task = (void *)sdt_exit_task,
715 .init = (void *)sdt_init,
716 .exit = (void *)sdt_exit,
717 .name = "sdt");