1 // SPDX-License-Identifier: GPL-2.0
2 /* Copyright (c) 2020 Facebook */
3 #define _GNU_SOURCE
4 #include <argp.h>
5 #include <linux/compiler.h>
6 #include <sys/time.h>
7 #include <sched.h>
8 #include <fcntl.h>
9 #include <pthread.h>
10 #include <sys/sysinfo.h>
11 #include <sys/resource.h>
12 #include <signal.h>
13 #include "bench.h"
14 #include "testing_helpers.h"
15 
16 struct env env = {
17 	.warmup_sec = 1,
18 	.duration_sec = 5,
19 	.affinity = false,
20 	.consumer_cnt = 1,
21 	.producer_cnt = 1,
22 };
23 
24 static int libbpf_print_fn(enum libbpf_print_level level,
25 		    const char *format, va_list args)
26 {
27 	if (level == LIBBPF_DEBUG && !env.verbose)
28 		return 0;
29 	return vfprintf(stderr, format, args);
30 }
31 
32 static int bump_memlock_rlimit(void)
33 {
34 	struct rlimit rlim_new = {
35 		.rlim_cur	= RLIM_INFINITY,
36 		.rlim_max	= RLIM_INFINITY,
37 	};
38 
39 	return setrlimit(RLIMIT_MEMLOCK, &rlim_new);
40 }
41 
42 void setup_libbpf()
43 {
44 	int err;
45 
46 	libbpf_set_strict_mode(LIBBPF_STRICT_ALL);
47 	libbpf_set_print(libbpf_print_fn);
48 
49 	err = bump_memlock_rlimit();
50 	if (err)
51 		fprintf(stderr, "failed to increase RLIMIT_MEMLOCK: %d", err);
52 }
53 
54 void hits_drops_report_progress(int iter, struct bench_res *res, long delta_ns)
55 {
56 	double hits_per_sec, drops_per_sec;
57 	double hits_per_prod;
58 
59 	hits_per_sec = res->hits / 1000000.0 / (delta_ns / 1000000000.0);
60 	hits_per_prod = hits_per_sec / env.producer_cnt;
61 	drops_per_sec = res->drops / 1000000.0 / (delta_ns / 1000000000.0);
62 
63 	printf("Iter %3d (%7.3lfus): ",
64 	       iter, (delta_ns - 1000000000) / 1000.0);
65 
66 	printf("hits %8.3lfM/s (%7.3lfM/prod), drops %8.3lfM/s\n",
67 	       hits_per_sec, hits_per_prod, drops_per_sec);
68 }
69 
70 void hits_drops_report_final(struct bench_res res[], int res_cnt)
71 {
72 	int i;
73 	double hits_mean = 0.0, drops_mean = 0.0;
74 	double hits_stddev = 0.0, drops_stddev = 0.0;
75 
76 	for (i = 0; i < res_cnt; i++) {
77 		hits_mean += res[i].hits / 1000000.0 / (0.0 + res_cnt);
78 		drops_mean += res[i].drops / 1000000.0 / (0.0 + res_cnt);
79 	}
80 
81 	if (res_cnt > 1)  {
82 		for (i = 0; i < res_cnt; i++) {
83 			hits_stddev += (hits_mean - res[i].hits / 1000000.0) *
84 				       (hits_mean - res[i].hits / 1000000.0) /
85 				       (res_cnt - 1.0);
86 			drops_stddev += (drops_mean - res[i].drops / 1000000.0) *
87 					(drops_mean - res[i].drops / 1000000.0) /
88 					(res_cnt - 1.0);
89 		}
90 		hits_stddev = sqrt(hits_stddev);
91 		drops_stddev = sqrt(drops_stddev);
92 	}
93 	printf("Summary: hits %8.3lf \u00B1 %5.3lfM/s (%7.3lfM/prod), ",
94 	       hits_mean, hits_stddev, hits_mean / env.producer_cnt);
95 	printf("drops %8.3lf \u00B1 %5.3lfM/s\n",
96 	       drops_mean, drops_stddev);
97 }
98 
99 const char *argp_program_version = "benchmark";
100 const char *argp_program_bug_address = "<bpf@vger.kernel.org>";
101 const char argp_program_doc[] =
102 "benchmark    Generic benchmarking framework.\n"
103 "\n"
104 "This tool runs benchmarks.\n"
105 "\n"
106 "USAGE: benchmark <bench-name>\n"
107 "\n"
108 "EXAMPLES:\n"
109 "    # run 'count-local' benchmark with 1 producer and 1 consumer\n"
110 "    benchmark count-local\n"
111 "    # run 'count-local' with 16 producer and 8 consumer thread, pinned to CPUs\n"
112 "    benchmark -p16 -c8 -a count-local\n";
113 
114 enum {
115 	ARG_PROD_AFFINITY_SET = 1000,
116 	ARG_CONS_AFFINITY_SET = 1001,
117 };
118 
119 static const struct argp_option opts[] = {
120 	{ "list", 'l', NULL, 0, "List available benchmarks"},
121 	{ "duration", 'd', "SEC", 0, "Duration of benchmark, seconds"},
122 	{ "warmup", 'w', "SEC", 0, "Warm-up period, seconds"},
123 	{ "producers", 'p', "NUM", 0, "Number of producer threads"},
124 	{ "consumers", 'c', "NUM", 0, "Number of consumer threads"},
125 	{ "verbose", 'v', NULL, 0, "Verbose debug output"},
126 	{ "affinity", 'a', NULL, 0, "Set consumer/producer thread affinity"},
127 	{ "prod-affinity", ARG_PROD_AFFINITY_SET, "CPUSET", 0,
128 	  "Set of CPUs for producer threads; implies --affinity"},
129 	{ "cons-affinity", ARG_CONS_AFFINITY_SET, "CPUSET", 0,
130 	  "Set of CPUs for consumer threads; implies --affinity"},
131 	{},
132 };
133 
134 extern struct argp bench_ringbufs_argp;
135 
136 static const struct argp_child bench_parsers[] = {
137 	{ &bench_ringbufs_argp, 0, "Ring buffers benchmark", 0 },
138 	{},
139 };
140 
141 static error_t parse_arg(int key, char *arg, struct argp_state *state)
142 {
143 	static int pos_args;
144 
145 	switch (key) {
146 	case 'v':
147 		env.verbose = true;
148 		break;
149 	case 'l':
150 		env.list = true;
151 		break;
152 	case 'd':
153 		env.duration_sec = strtol(arg, NULL, 10);
154 		if (env.duration_sec <= 0) {
155 			fprintf(stderr, "Invalid duration: %s\n", arg);
156 			argp_usage(state);
157 		}
158 		break;
159 	case 'w':
160 		env.warmup_sec = strtol(arg, NULL, 10);
161 		if (env.warmup_sec <= 0) {
162 			fprintf(stderr, "Invalid warm-up duration: %s\n", arg);
163 			argp_usage(state);
164 		}
165 		break;
166 	case 'p':
167 		env.producer_cnt = strtol(arg, NULL, 10);
168 		if (env.producer_cnt <= 0) {
169 			fprintf(stderr, "Invalid producer count: %s\n", arg);
170 			argp_usage(state);
171 		}
172 		break;
173 	case 'c':
174 		env.consumer_cnt = strtol(arg, NULL, 10);
175 		if (env.consumer_cnt <= 0) {
176 			fprintf(stderr, "Invalid consumer count: %s\n", arg);
177 			argp_usage(state);
178 		}
179 		break;
180 	case 'a':
181 		env.affinity = true;
182 		break;
183 	case ARG_PROD_AFFINITY_SET:
184 		env.affinity = true;
185 		if (parse_num_list(arg, &env.prod_cpus.cpus,
186 				   &env.prod_cpus.cpus_len)) {
187 			fprintf(stderr, "Invalid format of CPU set for producers.");
188 			argp_usage(state);
189 		}
190 		break;
191 	case ARG_CONS_AFFINITY_SET:
192 		env.affinity = true;
193 		if (parse_num_list(arg, &env.cons_cpus.cpus,
194 				   &env.cons_cpus.cpus_len)) {
195 			fprintf(stderr, "Invalid format of CPU set for consumers.");
196 			argp_usage(state);
197 		}
198 		break;
199 	case ARGP_KEY_ARG:
200 		if (pos_args++) {
201 			fprintf(stderr,
202 				"Unrecognized positional argument: %s\n", arg);
203 			argp_usage(state);
204 		}
205 		env.bench_name = strdup(arg);
206 		break;
207 	default:
208 		return ARGP_ERR_UNKNOWN;
209 	}
210 	return 0;
211 }
212 
213 static void parse_cmdline_args(int argc, char **argv)
214 {
215 	static const struct argp argp = {
216 		.options = opts,
217 		.parser = parse_arg,
218 		.doc = argp_program_doc,
219 		.children = bench_parsers,
220 	};
221 	if (argp_parse(&argp, argc, argv, 0, NULL, NULL))
222 		exit(1);
223 	if (!env.list && !env.bench_name) {
224 		argp_help(&argp, stderr, ARGP_HELP_DOC, "bench");
225 		exit(1);
226 	}
227 }
228 
229 static void collect_measurements(long delta_ns);
230 
231 static __u64 last_time_ns;
232 static void sigalarm_handler(int signo)
233 {
234 	long new_time_ns = get_time_ns();
235 	long delta_ns = new_time_ns - last_time_ns;
236 
237 	collect_measurements(delta_ns);
238 
239 	last_time_ns = new_time_ns;
240 }
241 
242 /* set up periodic 1-second timer */
243 static void setup_timer()
244 {
245 	static struct sigaction sigalarm_action = {
246 		.sa_handler = sigalarm_handler,
247 	};
248 	struct itimerval timer_settings = {};
249 	int err;
250 
251 	last_time_ns = get_time_ns();
252 	err = sigaction(SIGALRM, &sigalarm_action, NULL);
253 	if (err < 0) {
254 		fprintf(stderr, "failed to install SIGALRM handler: %d\n", -errno);
255 		exit(1);
256 	}
257 	timer_settings.it_interval.tv_sec = 1;
258 	timer_settings.it_value.tv_sec = 1;
259 	err = setitimer(ITIMER_REAL, &timer_settings, NULL);
260 	if (err < 0) {
261 		fprintf(stderr, "failed to arm interval timer: %d\n", -errno);
262 		exit(1);
263 	}
264 }
265 
266 static void set_thread_affinity(pthread_t thread, int cpu)
267 {
268 	cpu_set_t cpuset;
269 
270 	CPU_ZERO(&cpuset);
271 	CPU_SET(cpu, &cpuset);
272 	if (pthread_setaffinity_np(thread, sizeof(cpuset), &cpuset)) {
273 		fprintf(stderr, "setting affinity to CPU #%d failed: %d\n",
274 			cpu, errno);
275 		exit(1);
276 	}
277 }
278 
279 static int next_cpu(struct cpu_set *cpu_set)
280 {
281 	if (cpu_set->cpus) {
282 		int i;
283 
284 		/* find next available CPU */
285 		for (i = cpu_set->next_cpu; i < cpu_set->cpus_len; i++) {
286 			if (cpu_set->cpus[i]) {
287 				cpu_set->next_cpu = i + 1;
288 				return i;
289 			}
290 		}
291 		fprintf(stderr, "Not enough CPUs specified, need CPU #%d or higher.\n", i);
292 		exit(1);
293 	}
294 
295 	return cpu_set->next_cpu++;
296 }
297 
298 static struct bench_state {
299 	int res_cnt;
300 	struct bench_res *results;
301 	pthread_t *consumers;
302 	pthread_t *producers;
303 } state;
304 
305 const struct bench *bench = NULL;
306 
307 extern const struct bench bench_count_global;
308 extern const struct bench bench_count_local;
309 extern const struct bench bench_rename_base;
310 extern const struct bench bench_rename_kprobe;
311 extern const struct bench bench_rename_kretprobe;
312 extern const struct bench bench_rename_rawtp;
313 extern const struct bench bench_rename_fentry;
314 extern const struct bench bench_rename_fexit;
315 extern const struct bench bench_trig_base;
316 extern const struct bench bench_trig_tp;
317 extern const struct bench bench_trig_rawtp;
318 extern const struct bench bench_trig_kprobe;
319 extern const struct bench bench_trig_fentry;
320 extern const struct bench bench_trig_fentry_sleep;
321 extern const struct bench bench_trig_fmodret;
322 extern const struct bench bench_rb_libbpf;
323 extern const struct bench bench_rb_custom;
324 extern const struct bench bench_pb_libbpf;
325 extern const struct bench bench_pb_custom;
326 
327 static const struct bench *benchs[] = {
328 	&bench_count_global,
329 	&bench_count_local,
330 	&bench_rename_base,
331 	&bench_rename_kprobe,
332 	&bench_rename_kretprobe,
333 	&bench_rename_rawtp,
334 	&bench_rename_fentry,
335 	&bench_rename_fexit,
336 	&bench_trig_base,
337 	&bench_trig_tp,
338 	&bench_trig_rawtp,
339 	&bench_trig_kprobe,
340 	&bench_trig_fentry,
341 	&bench_trig_fentry_sleep,
342 	&bench_trig_fmodret,
343 	&bench_rb_libbpf,
344 	&bench_rb_custom,
345 	&bench_pb_libbpf,
346 	&bench_pb_custom,
347 };
348 
349 static void setup_benchmark()
350 {
351 	int i, err;
352 
353 	if (!env.bench_name) {
354 		fprintf(stderr, "benchmark name is not specified\n");
355 		exit(1);
356 	}
357 
358 	for (i = 0; i < ARRAY_SIZE(benchs); i++) {
359 		if (strcmp(benchs[i]->name, env.bench_name) == 0) {
360 			bench = benchs[i];
361 			break;
362 		}
363 	}
364 	if (!bench) {
365 		fprintf(stderr, "benchmark '%s' not found\n", env.bench_name);
366 		exit(1);
367 	}
368 
369 	printf("Setting up benchmark '%s'...\n", bench->name);
370 
371 	state.producers = calloc(env.producer_cnt, sizeof(*state.producers));
372 	state.consumers = calloc(env.consumer_cnt, sizeof(*state.consumers));
373 	state.results = calloc(env.duration_sec + env.warmup_sec + 2,
374 			       sizeof(*state.results));
375 	if (!state.producers || !state.consumers || !state.results)
376 		exit(1);
377 
378 	if (bench->validate)
379 		bench->validate();
380 	if (bench->setup)
381 		bench->setup();
382 
383 	for (i = 0; i < env.consumer_cnt; i++) {
384 		err = pthread_create(&state.consumers[i], NULL,
385 				     bench->consumer_thread, (void *)(long)i);
386 		if (err) {
387 			fprintf(stderr, "failed to create consumer thread #%d: %d\n",
388 				i, -errno);
389 			exit(1);
390 		}
391 		if (env.affinity)
392 			set_thread_affinity(state.consumers[i],
393 					    next_cpu(&env.cons_cpus));
394 	}
395 
396 	/* unless explicit producer CPU list is specified, continue after
397 	 * last consumer CPU
398 	 */
399 	if (!env.prod_cpus.cpus)
400 		env.prod_cpus.next_cpu = env.cons_cpus.next_cpu;
401 
402 	for (i = 0; i < env.producer_cnt; i++) {
403 		err = pthread_create(&state.producers[i], NULL,
404 				     bench->producer_thread, (void *)(long)i);
405 		if (err) {
406 			fprintf(stderr, "failed to create producer thread #%d: %d\n",
407 				i, -errno);
408 			exit(1);
409 		}
410 		if (env.affinity)
411 			set_thread_affinity(state.producers[i],
412 					    next_cpu(&env.prod_cpus));
413 	}
414 
415 	printf("Benchmark '%s' started.\n", bench->name);
416 }
417 
418 static pthread_mutex_t bench_done_mtx = PTHREAD_MUTEX_INITIALIZER;
419 static pthread_cond_t bench_done = PTHREAD_COND_INITIALIZER;
420 
421 static void collect_measurements(long delta_ns) {
422 	int iter = state.res_cnt++;
423 	struct bench_res *res = &state.results[iter];
424 
425 	bench->measure(res);
426 
427 	if (bench->report_progress)
428 		bench->report_progress(iter, res, delta_ns);
429 
430 	if (iter == env.duration_sec + env.warmup_sec) {
431 		pthread_mutex_lock(&bench_done_mtx);
432 		pthread_cond_signal(&bench_done);
433 		pthread_mutex_unlock(&bench_done_mtx);
434 	}
435 }
436 
437 int main(int argc, char **argv)
438 {
439 	parse_cmdline_args(argc, argv);
440 
441 	if (env.list) {
442 		int i;
443 
444 		printf("Available benchmarks:\n");
445 		for (i = 0; i < ARRAY_SIZE(benchs); i++) {
446 			printf("- %s\n", benchs[i]->name);
447 		}
448 		return 0;
449 	}
450 
451 	setup_benchmark();
452 
453 	setup_timer();
454 
455 	pthread_mutex_lock(&bench_done_mtx);
456 	pthread_cond_wait(&bench_done, &bench_done_mtx);
457 	pthread_mutex_unlock(&bench_done_mtx);
458 
459 	if (bench->report_final)
460 		/* skip first sample */
461 		bench->report_final(state.results + env.warmup_sec,
462 				    state.res_cnt - env.warmup_sec);
463 
464 	return 0;
465 }
466