xref: /linux/tools/testing/selftests/bpf/bench.c (revision d41bc48bfab2076f7db88d079a3a3203dd9c4a54)
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 false_hits_report_progress(int iter, struct bench_res *res, long delta_ns)
55 {
56 	long total = res->false_hits  + res->hits + res->drops;
57 
58 	printf("Iter %3d (%7.3lfus): ",
59 	       iter, (delta_ns - 1000000000) / 1000.0);
60 
61 	printf("%ld false hits of %ld total operations. Percentage = %2.2f %%\n",
62 	       res->false_hits, total, ((float)res->false_hits / total) * 100);
63 }
64 
65 void false_hits_report_final(struct bench_res res[], int res_cnt)
66 {
67 	long total_hits = 0, total_drops = 0, total_false_hits = 0, total_ops = 0;
68 	int i;
69 
70 	for (i = 0; i < res_cnt; i++) {
71 		total_hits += res[i].hits;
72 		total_false_hits += res[i].false_hits;
73 		total_drops += res[i].drops;
74 	}
75 	total_ops = total_hits + total_false_hits + total_drops;
76 
77 	printf("Summary: %ld false hits of %ld total operations. ",
78 	       total_false_hits, total_ops);
79 	printf("Percentage =  %2.2f %%\n",
80 	       ((float)total_false_hits / total_ops) * 100);
81 }
82 
83 void hits_drops_report_progress(int iter, struct bench_res *res, long delta_ns)
84 {
85 	double hits_per_sec, drops_per_sec;
86 	double hits_per_prod;
87 
88 	hits_per_sec = res->hits / 1000000.0 / (delta_ns / 1000000000.0);
89 	hits_per_prod = hits_per_sec / env.producer_cnt;
90 	drops_per_sec = res->drops / 1000000.0 / (delta_ns / 1000000000.0);
91 
92 	printf("Iter %3d (%7.3lfus): ",
93 	       iter, (delta_ns - 1000000000) / 1000.0);
94 
95 	printf("hits %8.3lfM/s (%7.3lfM/prod), drops %8.3lfM/s, total operations %8.3lfM/s\n",
96 	       hits_per_sec, hits_per_prod, drops_per_sec, hits_per_sec + drops_per_sec);
97 }
98 
99 void hits_drops_report_final(struct bench_res res[], int res_cnt)
100 {
101 	int i;
102 	double hits_mean = 0.0, drops_mean = 0.0, total_ops_mean = 0.0;
103 	double hits_stddev = 0.0, drops_stddev = 0.0, total_ops_stddev = 0.0;
104 	double total_ops;
105 
106 	for (i = 0; i < res_cnt; i++) {
107 		hits_mean += res[i].hits / 1000000.0 / (0.0 + res_cnt);
108 		drops_mean += res[i].drops / 1000000.0 / (0.0 + res_cnt);
109 	}
110 	total_ops_mean = hits_mean + drops_mean;
111 
112 	if (res_cnt > 1)  {
113 		for (i = 0; i < res_cnt; i++) {
114 			hits_stddev += (hits_mean - res[i].hits / 1000000.0) *
115 				       (hits_mean - res[i].hits / 1000000.0) /
116 				       (res_cnt - 1.0);
117 			drops_stddev += (drops_mean - res[i].drops / 1000000.0) *
118 					(drops_mean - res[i].drops / 1000000.0) /
119 					(res_cnt - 1.0);
120 			total_ops = res[i].hits + res[i].drops;
121 			total_ops_stddev += (total_ops_mean - total_ops / 1000000.0) *
122 					(total_ops_mean - total_ops / 1000000.0) /
123 					(res_cnt - 1.0);
124 		}
125 		hits_stddev = sqrt(hits_stddev);
126 		drops_stddev = sqrt(drops_stddev);
127 		total_ops_stddev = sqrt(total_ops_stddev);
128 	}
129 	printf("Summary: hits %8.3lf \u00B1 %5.3lfM/s (%7.3lfM/prod), ",
130 	       hits_mean, hits_stddev, hits_mean / env.producer_cnt);
131 	printf("drops %8.3lf \u00B1 %5.3lfM/s, ",
132 	       drops_mean, drops_stddev);
133 	printf("total operations %8.3lf \u00B1 %5.3lfM/s\n",
134 	       total_ops_mean, total_ops_stddev);
135 }
136 
137 const char *argp_program_version = "benchmark";
138 const char *argp_program_bug_address = "<bpf@vger.kernel.org>";
139 const char argp_program_doc[] =
140 "benchmark    Generic benchmarking framework.\n"
141 "\n"
142 "This tool runs benchmarks.\n"
143 "\n"
144 "USAGE: benchmark <bench-name>\n"
145 "\n"
146 "EXAMPLES:\n"
147 "    # run 'count-local' benchmark with 1 producer and 1 consumer\n"
148 "    benchmark count-local\n"
149 "    # run 'count-local' with 16 producer and 8 consumer thread, pinned to CPUs\n"
150 "    benchmark -p16 -c8 -a count-local\n";
151 
152 enum {
153 	ARG_PROD_AFFINITY_SET = 1000,
154 	ARG_CONS_AFFINITY_SET = 1001,
155 };
156 
157 static const struct argp_option opts[] = {
158 	{ "list", 'l', NULL, 0, "List available benchmarks"},
159 	{ "duration", 'd', "SEC", 0, "Duration of benchmark, seconds"},
160 	{ "warmup", 'w', "SEC", 0, "Warm-up period, seconds"},
161 	{ "producers", 'p', "NUM", 0, "Number of producer threads"},
162 	{ "consumers", 'c', "NUM", 0, "Number of consumer threads"},
163 	{ "verbose", 'v', NULL, 0, "Verbose debug output"},
164 	{ "affinity", 'a', NULL, 0, "Set consumer/producer thread affinity"},
165 	{ "prod-affinity", ARG_PROD_AFFINITY_SET, "CPUSET", 0,
166 	  "Set of CPUs for producer threads; implies --affinity"},
167 	{ "cons-affinity", ARG_CONS_AFFINITY_SET, "CPUSET", 0,
168 	  "Set of CPUs for consumer threads; implies --affinity"},
169 	{},
170 };
171 
172 extern struct argp bench_ringbufs_argp;
173 extern struct argp bench_bloom_map_argp;
174 
175 static const struct argp_child bench_parsers[] = {
176 	{ &bench_ringbufs_argp, 0, "Ring buffers benchmark", 0 },
177 	{ &bench_bloom_map_argp, 0, "Bloom filter map benchmark", 0 },
178 	{},
179 };
180 
181 static error_t parse_arg(int key, char *arg, struct argp_state *state)
182 {
183 	static int pos_args;
184 
185 	switch (key) {
186 	case 'v':
187 		env.verbose = true;
188 		break;
189 	case 'l':
190 		env.list = true;
191 		break;
192 	case 'd':
193 		env.duration_sec = strtol(arg, NULL, 10);
194 		if (env.duration_sec <= 0) {
195 			fprintf(stderr, "Invalid duration: %s\n", arg);
196 			argp_usage(state);
197 		}
198 		break;
199 	case 'w':
200 		env.warmup_sec = strtol(arg, NULL, 10);
201 		if (env.warmup_sec <= 0) {
202 			fprintf(stderr, "Invalid warm-up duration: %s\n", arg);
203 			argp_usage(state);
204 		}
205 		break;
206 	case 'p':
207 		env.producer_cnt = strtol(arg, NULL, 10);
208 		if (env.producer_cnt <= 0) {
209 			fprintf(stderr, "Invalid producer count: %s\n", arg);
210 			argp_usage(state);
211 		}
212 		break;
213 	case 'c':
214 		env.consumer_cnt = strtol(arg, NULL, 10);
215 		if (env.consumer_cnt <= 0) {
216 			fprintf(stderr, "Invalid consumer count: %s\n", arg);
217 			argp_usage(state);
218 		}
219 		break;
220 	case 'a':
221 		env.affinity = true;
222 		break;
223 	case ARG_PROD_AFFINITY_SET:
224 		env.affinity = true;
225 		if (parse_num_list(arg, &env.prod_cpus.cpus,
226 				   &env.prod_cpus.cpus_len)) {
227 			fprintf(stderr, "Invalid format of CPU set for producers.");
228 			argp_usage(state);
229 		}
230 		break;
231 	case ARG_CONS_AFFINITY_SET:
232 		env.affinity = true;
233 		if (parse_num_list(arg, &env.cons_cpus.cpus,
234 				   &env.cons_cpus.cpus_len)) {
235 			fprintf(stderr, "Invalid format of CPU set for consumers.");
236 			argp_usage(state);
237 		}
238 		break;
239 	case ARGP_KEY_ARG:
240 		if (pos_args++) {
241 			fprintf(stderr,
242 				"Unrecognized positional argument: %s\n", arg);
243 			argp_usage(state);
244 		}
245 		env.bench_name = strdup(arg);
246 		break;
247 	default:
248 		return ARGP_ERR_UNKNOWN;
249 	}
250 	return 0;
251 }
252 
253 static void parse_cmdline_args(int argc, char **argv)
254 {
255 	static const struct argp argp = {
256 		.options = opts,
257 		.parser = parse_arg,
258 		.doc = argp_program_doc,
259 		.children = bench_parsers,
260 	};
261 	if (argp_parse(&argp, argc, argv, 0, NULL, NULL))
262 		exit(1);
263 	if (!env.list && !env.bench_name) {
264 		argp_help(&argp, stderr, ARGP_HELP_DOC, "bench");
265 		exit(1);
266 	}
267 }
268 
269 static void collect_measurements(long delta_ns);
270 
271 static __u64 last_time_ns;
272 static void sigalarm_handler(int signo)
273 {
274 	long new_time_ns = get_time_ns();
275 	long delta_ns = new_time_ns - last_time_ns;
276 
277 	collect_measurements(delta_ns);
278 
279 	last_time_ns = new_time_ns;
280 }
281 
282 /* set up periodic 1-second timer */
283 static void setup_timer()
284 {
285 	static struct sigaction sigalarm_action = {
286 		.sa_handler = sigalarm_handler,
287 	};
288 	struct itimerval timer_settings = {};
289 	int err;
290 
291 	last_time_ns = get_time_ns();
292 	err = sigaction(SIGALRM, &sigalarm_action, NULL);
293 	if (err < 0) {
294 		fprintf(stderr, "failed to install SIGALRM handler: %d\n", -errno);
295 		exit(1);
296 	}
297 	timer_settings.it_interval.tv_sec = 1;
298 	timer_settings.it_value.tv_sec = 1;
299 	err = setitimer(ITIMER_REAL, &timer_settings, NULL);
300 	if (err < 0) {
301 		fprintf(stderr, "failed to arm interval timer: %d\n", -errno);
302 		exit(1);
303 	}
304 }
305 
306 static void set_thread_affinity(pthread_t thread, int cpu)
307 {
308 	cpu_set_t cpuset;
309 
310 	CPU_ZERO(&cpuset);
311 	CPU_SET(cpu, &cpuset);
312 	if (pthread_setaffinity_np(thread, sizeof(cpuset), &cpuset)) {
313 		fprintf(stderr, "setting affinity to CPU #%d failed: %d\n",
314 			cpu, errno);
315 		exit(1);
316 	}
317 }
318 
319 static int next_cpu(struct cpu_set *cpu_set)
320 {
321 	if (cpu_set->cpus) {
322 		int i;
323 
324 		/* find next available CPU */
325 		for (i = cpu_set->next_cpu; i < cpu_set->cpus_len; i++) {
326 			if (cpu_set->cpus[i]) {
327 				cpu_set->next_cpu = i + 1;
328 				return i;
329 			}
330 		}
331 		fprintf(stderr, "Not enough CPUs specified, need CPU #%d or higher.\n", i);
332 		exit(1);
333 	}
334 
335 	return cpu_set->next_cpu++;
336 }
337 
338 static struct bench_state {
339 	int res_cnt;
340 	struct bench_res *results;
341 	pthread_t *consumers;
342 	pthread_t *producers;
343 } state;
344 
345 const struct bench *bench = NULL;
346 
347 extern const struct bench bench_count_global;
348 extern const struct bench bench_count_local;
349 extern const struct bench bench_rename_base;
350 extern const struct bench bench_rename_kprobe;
351 extern const struct bench bench_rename_kretprobe;
352 extern const struct bench bench_rename_rawtp;
353 extern const struct bench bench_rename_fentry;
354 extern const struct bench bench_rename_fexit;
355 extern const struct bench bench_trig_base;
356 extern const struct bench bench_trig_tp;
357 extern const struct bench bench_trig_rawtp;
358 extern const struct bench bench_trig_kprobe;
359 extern const struct bench bench_trig_fentry;
360 extern const struct bench bench_trig_fentry_sleep;
361 extern const struct bench bench_trig_fmodret;
362 extern const struct bench bench_trig_uprobe_base;
363 extern const struct bench bench_trig_uprobe_with_nop;
364 extern const struct bench bench_trig_uretprobe_with_nop;
365 extern const struct bench bench_trig_uprobe_without_nop;
366 extern const struct bench bench_trig_uretprobe_without_nop;
367 extern const struct bench bench_rb_libbpf;
368 extern const struct bench bench_rb_custom;
369 extern const struct bench bench_pb_libbpf;
370 extern const struct bench bench_pb_custom;
371 extern const struct bench bench_bloom_lookup;
372 extern const struct bench bench_bloom_update;
373 extern const struct bench bench_bloom_false_positive;
374 extern const struct bench bench_hashmap_without_bloom;
375 extern const struct bench bench_hashmap_with_bloom;
376 
377 static const struct bench *benchs[] = {
378 	&bench_count_global,
379 	&bench_count_local,
380 	&bench_rename_base,
381 	&bench_rename_kprobe,
382 	&bench_rename_kretprobe,
383 	&bench_rename_rawtp,
384 	&bench_rename_fentry,
385 	&bench_rename_fexit,
386 	&bench_trig_base,
387 	&bench_trig_tp,
388 	&bench_trig_rawtp,
389 	&bench_trig_kprobe,
390 	&bench_trig_fentry,
391 	&bench_trig_fentry_sleep,
392 	&bench_trig_fmodret,
393 	&bench_trig_uprobe_base,
394 	&bench_trig_uprobe_with_nop,
395 	&bench_trig_uretprobe_with_nop,
396 	&bench_trig_uprobe_without_nop,
397 	&bench_trig_uretprobe_without_nop,
398 	&bench_rb_libbpf,
399 	&bench_rb_custom,
400 	&bench_pb_libbpf,
401 	&bench_pb_custom,
402 	&bench_bloom_lookup,
403 	&bench_bloom_update,
404 	&bench_bloom_false_positive,
405 	&bench_hashmap_without_bloom,
406 	&bench_hashmap_with_bloom,
407 };
408 
409 static void setup_benchmark()
410 {
411 	int i, err;
412 
413 	if (!env.bench_name) {
414 		fprintf(stderr, "benchmark name is not specified\n");
415 		exit(1);
416 	}
417 
418 	for (i = 0; i < ARRAY_SIZE(benchs); i++) {
419 		if (strcmp(benchs[i]->name, env.bench_name) == 0) {
420 			bench = benchs[i];
421 			break;
422 		}
423 	}
424 	if (!bench) {
425 		fprintf(stderr, "benchmark '%s' not found\n", env.bench_name);
426 		exit(1);
427 	}
428 
429 	printf("Setting up benchmark '%s'...\n", bench->name);
430 
431 	state.producers = calloc(env.producer_cnt, sizeof(*state.producers));
432 	state.consumers = calloc(env.consumer_cnt, sizeof(*state.consumers));
433 	state.results = calloc(env.duration_sec + env.warmup_sec + 2,
434 			       sizeof(*state.results));
435 	if (!state.producers || !state.consumers || !state.results)
436 		exit(1);
437 
438 	if (bench->validate)
439 		bench->validate();
440 	if (bench->setup)
441 		bench->setup();
442 
443 	for (i = 0; i < env.consumer_cnt; i++) {
444 		err = pthread_create(&state.consumers[i], NULL,
445 				     bench->consumer_thread, (void *)(long)i);
446 		if (err) {
447 			fprintf(stderr, "failed to create consumer thread #%d: %d\n",
448 				i, -errno);
449 			exit(1);
450 		}
451 		if (env.affinity)
452 			set_thread_affinity(state.consumers[i],
453 					    next_cpu(&env.cons_cpus));
454 	}
455 
456 	/* unless explicit producer CPU list is specified, continue after
457 	 * last consumer CPU
458 	 */
459 	if (!env.prod_cpus.cpus)
460 		env.prod_cpus.next_cpu = env.cons_cpus.next_cpu;
461 
462 	for (i = 0; i < env.producer_cnt; i++) {
463 		err = pthread_create(&state.producers[i], NULL,
464 				     bench->producer_thread, (void *)(long)i);
465 		if (err) {
466 			fprintf(stderr, "failed to create producer thread #%d: %d\n",
467 				i, -errno);
468 			exit(1);
469 		}
470 		if (env.affinity)
471 			set_thread_affinity(state.producers[i],
472 					    next_cpu(&env.prod_cpus));
473 	}
474 
475 	printf("Benchmark '%s' started.\n", bench->name);
476 }
477 
478 static pthread_mutex_t bench_done_mtx = PTHREAD_MUTEX_INITIALIZER;
479 static pthread_cond_t bench_done = PTHREAD_COND_INITIALIZER;
480 
481 static void collect_measurements(long delta_ns) {
482 	int iter = state.res_cnt++;
483 	struct bench_res *res = &state.results[iter];
484 
485 	bench->measure(res);
486 
487 	if (bench->report_progress)
488 		bench->report_progress(iter, res, delta_ns);
489 
490 	if (iter == env.duration_sec + env.warmup_sec) {
491 		pthread_mutex_lock(&bench_done_mtx);
492 		pthread_cond_signal(&bench_done);
493 		pthread_mutex_unlock(&bench_done_mtx);
494 	}
495 }
496 
497 int main(int argc, char **argv)
498 {
499 	parse_cmdline_args(argc, argv);
500 
501 	if (env.list) {
502 		int i;
503 
504 		printf("Available benchmarks:\n");
505 		for (i = 0; i < ARRAY_SIZE(benchs); i++) {
506 			printf("- %s\n", benchs[i]->name);
507 		}
508 		return 0;
509 	}
510 
511 	setup_benchmark();
512 
513 	setup_timer();
514 
515 	pthread_mutex_lock(&bench_done_mtx);
516 	pthread_cond_wait(&bench_done, &bench_done_mtx);
517 	pthread_mutex_unlock(&bench_done_mtx);
518 
519 	if (bench->report_final)
520 		/* skip first sample */
521 		bench->report_final(state.results + env.warmup_sec,
522 				    state.res_cnt - env.warmup_sec);
523 
524 	return 0;
525 }
526