xref: /linux/tools/sched_ext/scx_simple.c (revision 07fdad3a93756b872da7b53647715c48d0f4a2d0)
1 /* SPDX-License-Identifier: GPL-2.0 */
2 /*
3  * Copyright (c) 2022 Meta Platforms, Inc. and affiliates.
4  * Copyright (c) 2022 Tejun Heo <tj@kernel.org>
5  * Copyright (c) 2022 David Vernet <dvernet@meta.com>
6  */
7 #include <stdio.h>
8 #include <unistd.h>
9 #include <signal.h>
10 #include <assert.h>
11 #include <libgen.h>
12 #include <bpf/bpf.h>
13 #include <scx/common.h>
14 #include "scx_simple.bpf.skel.h"
15 
16 const char help_fmt[] =
17 "A simple sched_ext scheduler.\n"
18 "\n"
19 "See the top-level comment in .bpf.c for more details.\n"
20 "\n"
21 "Usage: %s [-f] [-v]\n"
22 "\n"
23 "  -f            Use FIFO scheduling instead of weighted vtime scheduling\n"
24 "  -v            Print libbpf debug messages\n"
25 "  -h            Display this help and exit\n";
26 
27 static bool verbose;
28 static volatile int exit_req;
29 
30 static int libbpf_print_fn(enum libbpf_print_level level, const char *format, va_list args)
31 {
32 	if (level == LIBBPF_DEBUG && !verbose)
33 		return 0;
34 	return vfprintf(stderr, format, args);
35 }
36 
37 static void sigint_handler(int simple)
38 {
39 	exit_req = 1;
40 }
41 
42 static void read_stats(struct scx_simple *skel, __u64 *stats)
43 {
44 	int nr_cpus = libbpf_num_possible_cpus();
45 	assert(nr_cpus > 0);
46 	__u64 cnts[2][nr_cpus];
47 	__u32 idx;
48 
49 	memset(stats, 0, sizeof(stats[0]) * 2);
50 
51 	for (idx = 0; idx < 2; idx++) {
52 		int ret, cpu;
53 
54 		ret = bpf_map_lookup_elem(bpf_map__fd(skel->maps.stats),
55 					  &idx, cnts[idx]);
56 		if (ret < 0)
57 			continue;
58 		for (cpu = 0; cpu < nr_cpus; cpu++)
59 			stats[idx] += cnts[idx][cpu];
60 	}
61 }
62 
63 int main(int argc, char **argv)
64 {
65 	struct scx_simple *skel;
66 	struct bpf_link *link;
67 	__u32 opt;
68 	__u64 ecode;
69 
70 	libbpf_set_print(libbpf_print_fn);
71 	signal(SIGINT, sigint_handler);
72 	signal(SIGTERM, sigint_handler);
73 restart:
74 	skel = SCX_OPS_OPEN(simple_ops, scx_simple);
75 
76 	while ((opt = getopt(argc, argv, "fvh")) != -1) {
77 		switch (opt) {
78 		case 'f':
79 			skel->rodata->fifo_sched = true;
80 			break;
81 		case 'v':
82 			verbose = true;
83 			break;
84 		default:
85 			fprintf(stderr, help_fmt, basename(argv[0]));
86 			return opt != 'h';
87 		}
88 	}
89 
90 	SCX_OPS_LOAD(skel, simple_ops, scx_simple, uei);
91 	link = SCX_OPS_ATTACH(skel, simple_ops, scx_simple);
92 
93 	while (!exit_req && !UEI_EXITED(skel, uei)) {
94 		__u64 stats[2];
95 
96 		read_stats(skel, stats);
97 		printf("local=%llu global=%llu\n", stats[0], stats[1]);
98 		fflush(stdout);
99 		sleep(1);
100 	}
101 
102 	bpf_link__destroy(link);
103 	ecode = UEI_REPORT(skel, uei);
104 	scx_simple__destroy(skel);
105 
106 	if (UEI_ECODE_RESTART(ecode))
107 		goto restart;
108 	return 0;
109 }
110