1 // SPDX-License-Identifier: GPL-2.0
4 * Copyright (C) 2018 Davidlohr Bueso.
6 * This program benchmarks concurrent epoll_wait(2) monitoring multiple
7 * file descriptors under one or two load balancing models. The first,
8 * and default, is the single/combined queueing (which refers to a single
9 * epoll instance for N worker threads):
13 * [combined queue] .---> [worker C]
17 * While the second model, enabled via --multiq option, uses multiple
18 * queueing (which refers to one epoll instance per worker). For example,
19 * short lived tcp connections in a high throughput httpd server will
20 * ditribute the accept()'ing connections across CPUs. In this case each
21 * worker does a limited amount of processing.
23 * [queue A] ---> [worker]
24 * [queue B] ---> [worker]
25 * [queue C] ---> [worker]
26 * [queue D] ---> [worker]
27 * [queue E] ---> [worker]
29 * Naturally, the single queue will enforce more concurrency on the epoll
30 * instance, and can therefore scale poorly compared to multiple queues.
31 * However, this is a benchmark raw data and must be taken with a grain of
32 * salt when choosing how to make use of sys_epoll.
34 * Each thread has a number of private, nonblocking file descriptors,
35 * referred to as fdmap. A writer thread will constantly be writing to
36 * the fdmaps of all threads, minimizing each threads's chances of
37 * epoll_wait not finding any ready read events and blocking as this
38 * is not what we want to stress. The size of the fdmap can be adjusted
39 * by the user; enlarging the value will increase the chances of
40 * epoll_wait(2) blocking as the lineal writer thread will take "longer",
41 * at least at a high level.
43 * Note that because fds are private to each thread, this workload does
44 * not stress scenarios where multiple tasks are awoken per ready IO; ie:
45 * EPOLLEXCLUSIVE semantics.
47 * The end result/metric is throughput: number of ops/second where an
48 * operation consists of:
50 * epoll_wait(2) + [others]
52 * ... where [others] is the cost of re-adding the fd (EPOLLET),
53 * or rearming it (EPOLLONESHOT).
56 * The purpose of this is program is that it be useful for measuring
57 * kernel related changes to the sys_epoll, and not comparing different
58 * IO polling methods, for example. Hence everything is very adhoc and
59 * outputs raw microbenchmark numbers. Also this uses eventfd, similar
60 * tools tend to use pipes or sockets, but the result is the same.
63 /* For the CLR_() macros */
72 #include <linux/compiler.h>
73 #include <linux/kernel.h>
75 #include <sys/resource.h>
76 #include <sys/epoll.h>
77 #include <sys/eventfd.h>
78 #include <sys/types.h>
79 #include <internal/cpumap.h>
80 #include <perf/cpumap.h>
82 #include "../util/stat.h"
83 #include <subcmd/parse-options.h>
88 #define printinfo(fmt, arg...) \
89 do { if (__verbose) { printf(fmt, ## arg); fflush(stdout); } } while (0)
91 static unsigned int nthreads = 0;
92 static unsigned int nsecs = 8;
93 struct timeval start, end, runtime;
94 static bool wdone, done, __verbose, randomize, nonblocking;
97 * epoll related shared variables.
100 /* Maximum number of nesting allowed inside epoll sets */
101 #define EPOLL_MAXNESTS 4
104 static int *epollfdp;
105 static bool noaffinity;
106 static unsigned int nested = 0;
107 static bool et; /* edge-trigger */
109 static bool multiq; /* use an epoll instance per thread */
111 /* amount of fds to monitor, per thread */
112 static unsigned int nfds = 64;
114 static pthread_mutex_t thread_lock;
115 static unsigned int threads_starting;
116 static struct stats throughput_stats;
117 static pthread_cond_t thread_parent, thread_worker;
121 int epollfd; /* for --multiq */
127 static const struct option options[] = {
128 /* general benchmark options */
129 OPT_UINTEGER('t', "threads", &nthreads, "Specify amount of threads"),
130 OPT_UINTEGER('r', "runtime", &nsecs, "Specify runtime (in seconds)"),
131 OPT_UINTEGER('f', "nfds", &nfds, "Specify amount of file descriptors to monitor for each thread"),
132 OPT_BOOLEAN( 'n', "noaffinity", &noaffinity, "Disables CPU affinity"),
133 OPT_BOOLEAN('R', "randomize", &randomize, "Enable random write behaviour (default is lineal)"),
134 OPT_BOOLEAN( 'v', "verbose", &__verbose, "Verbose mode"),
136 /* epoll specific options */
137 OPT_BOOLEAN( 'm', "multiq", &multiq, "Use multiple epoll instances (one per thread)"),
138 OPT_BOOLEAN( 'B', "nonblocking", &nonblocking, "Nonblocking epoll_wait(2) behaviour"),
139 OPT_UINTEGER( 'N', "nested", &nested, "Nesting level epoll hierarchy (default is 0, no nesting)"),
140 OPT_BOOLEAN( 'S', "oneshot", &oneshot, "Use EPOLLONESHOT semantics"),
141 OPT_BOOLEAN( 'E', "edge", &et, "Use Edge-triggered interface (default is LT)"),
146 static const char * const bench_epoll_wait_usage[] = {
147 "perf bench epoll wait <options>",
153 * Arrange the N elements of ARRAY in random order.
154 * Only effective if N is much smaller than RAND_MAX;
155 * if this may not be the case, use a better random
156 * number generator. -- Ben Pfaff.
158 static void shuffle(void *array, size_t n, size_t size)
160 char *carray = array;
167 aux = calloc(1, size);
169 err(EXIT_FAILURE, "calloc");
171 for (i = 1; i < n; ++i) {
172 size_t j = i + rand() / (RAND_MAX / (n - i) + 1);
175 memcpy(aux, &carray[j], size);
176 memcpy(&carray[j], &carray[i*size], size);
177 memcpy(&carray[i*size], aux, size);
184 static void *workerfn(void *arg)
187 struct worker *w = (struct worker *) arg;
188 unsigned long ops = w->ops;
189 struct epoll_event ev;
191 int to = nonblocking? 0 : -1;
192 int efd = multiq ? w->epollfd : epollfd;
194 pthread_mutex_lock(&thread_lock);
196 if (!threads_starting)
197 pthread_cond_signal(&thread_parent);
198 pthread_cond_wait(&thread_worker, &thread_lock);
199 pthread_mutex_unlock(&thread_lock);
203 * Block undefinitely waiting for the IN event.
204 * In order to stress the epoll_wait(2) syscall,
205 * call it event per event, instead of a larger
209 ret = epoll_wait(efd, &ev, 1, to);
210 } while (ret < 0 && errno == EINTR);
212 err(EXIT_FAILURE, "epoll_wait");
217 r = read(fd, &val, sizeof(val));
218 } while (!done && (r < 0 && errno == EAGAIN));
221 ev.events = EPOLLIN | EPOLLET;
222 ret = epoll_ctl(efd, EPOLL_CTL_ADD, fd, &ev);
226 /* rearm the file descriptor with a new event mask */
227 ev.events |= EPOLLIN | EPOLLONESHOT;
228 ret = epoll_ctl(efd, EPOLL_CTL_MOD, fd, &ev);
241 static void nest_epollfd(struct worker *w)
244 struct epoll_event ev;
245 int efd = multiq ? w->epollfd : epollfd;
247 if (nested > EPOLL_MAXNESTS)
248 nested = EPOLL_MAXNESTS;
250 epollfdp = calloc(nested, sizeof(*epollfdp));
252 err(EXIT_FAILURE, "calloc");
254 for (i = 0; i < nested; i++) {
255 epollfdp[i] = epoll_create(1);
257 err(EXIT_FAILURE, "epoll_create");
260 ev.events = EPOLLHUP; /* anything */
261 ev.data.u64 = i; /* any number */
263 for (i = nested - 1; i; i--) {
264 if (epoll_ctl(epollfdp[i - 1], EPOLL_CTL_ADD,
265 epollfdp[i], &ev) < 0)
266 err(EXIT_FAILURE, "epoll_ctl");
269 if (epoll_ctl(efd, EPOLL_CTL_ADD, *epollfdp, &ev) < 0)
270 err(EXIT_FAILURE, "epoll_ctl");
273 static void toggle_done(int sig __maybe_unused,
274 siginfo_t *info __maybe_unused,
275 void *uc __maybe_unused)
277 /* inform all threads that we're done for the day */
279 gettimeofday(&end, NULL);
280 timersub(&end, &start, &runtime);
283 static void print_summary(void)
285 unsigned long avg = avg_stats(&throughput_stats);
286 double stddev = stddev_stats(&throughput_stats);
288 printf("\nAveraged %ld operations/sec (+- %.2f%%), total secs = %d\n",
289 avg, rel_stddev_stats(stddev, avg),
290 (int) runtime.tv_sec);
293 static int do_threads(struct worker *worker, struct perf_cpu_map *cpu)
295 pthread_attr_t thread_attr, *attrp = NULL;
298 int ret = 0, events = EPOLLIN;
301 events |= EPOLLONESHOT;
305 printinfo("starting worker/consumer %sthreads%s\n",
306 noaffinity ? "":"CPU affinity ",
307 nonblocking ? " (nonblocking)":"");
309 pthread_attr_init(&thread_attr);
311 for (i = 0; i < nthreads; i++) {
312 struct worker *w = &worker[i];
315 w->epollfd = epoll_create(1);
317 err(EXIT_FAILURE, "epoll_create");
324 w->fdmap = calloc(nfds, sizeof(int));
328 for (j = 0; j < nfds; j++) {
329 int efd = multiq ? w->epollfd : epollfd;
330 struct epoll_event ev;
332 w->fdmap[j] = eventfd(0, EFD_NONBLOCK);
334 err(EXIT_FAILURE, "eventfd");
336 ev.data.fd = w->fdmap[j];
339 ret = epoll_ctl(efd, EPOLL_CTL_ADD,
342 err(EXIT_FAILURE, "epoll_ctl");
347 CPU_SET(cpu->map[i % cpu->nr], &cpuset);
349 ret = pthread_attr_setaffinity_np(&thread_attr, sizeof(cpu_set_t), &cpuset);
351 err(EXIT_FAILURE, "pthread_attr_setaffinity_np");
353 attrp = &thread_attr;
356 ret = pthread_create(&w->thread, attrp, workerfn,
357 (void *)(struct worker *) w);
359 err(EXIT_FAILURE, "pthread_create");
363 pthread_attr_destroy(&thread_attr);
368 static void *writerfn(void *p)
370 struct worker *worker = p;
372 const uint64_t val = 1;
374 struct timespec ts = { .tv_sec = 0,
377 printinfo("starting writer-thread: doing %s writes ...\n",
378 randomize? "random":"lineal");
380 for (iter = 0; !wdone; iter++) {
382 shuffle((void *)worker, nthreads, sizeof(*worker));
385 for (i = 0; i < nthreads; i++) {
386 struct worker *w = &worker[i];
389 shuffle((void *)w->fdmap, nfds, sizeof(int));
392 for (j = 0; j < nfds; j++) {
394 sz = write(w->fdmap[j], &val, sizeof(val));
395 } while (!wdone && (sz < 0 && errno == EAGAIN));
399 nanosleep(&ts, NULL);
402 printinfo("exiting writer-thread (total full-loops: %zd)\n", iter);
406 static int cmpworker(const void *p1, const void *p2)
409 struct worker *w1 = (struct worker *) p1;
410 struct worker *w2 = (struct worker *) p2;
411 return w1->tid > w2->tid;
414 int bench_epoll_wait(int argc, const char **argv)
417 struct sigaction act;
419 struct worker *worker = NULL;
420 struct perf_cpu_map *cpu;
422 struct rlimit rl, prevrl;
424 argc = parse_options(argc, argv, options, bench_epoll_wait_usage, 0);
426 usage_with_options(bench_epoll_wait_usage, options);
430 sigfillset(&act.sa_mask);
431 act.sa_sigaction = toggle_done;
432 sigaction(SIGINT, &act, NULL);
434 cpu = perf_cpu_map__new(NULL);
438 /* a single, main epoll instance */
440 epollfd = epoll_create(1);
442 err(EXIT_FAILURE, "epoll_create");
445 * Deal with nested epolls, if any.
451 printinfo("Using %s queue model\n", multiq ? "multi" : "single");
452 printinfo("Nesting level(s): %d\n", nested);
454 /* default to the number of CPUs and leave one for the writer pthread */
456 nthreads = cpu->nr - 1;
458 worker = calloc(nthreads, sizeof(*worker));
463 if (getrlimit(RLIMIT_NOFILE, &prevrl))
464 err(EXIT_FAILURE, "getrlimit");
465 rl.rlim_cur = rl.rlim_max = nfds * nthreads * 2 + 50;
466 printinfo("Setting RLIMIT_NOFILE rlimit from %" PRIu64 " to: %" PRIu64 "\n",
467 (uint64_t)prevrl.rlim_max, (uint64_t)rl.rlim_max);
468 if (setrlimit(RLIMIT_NOFILE, &rl) < 0)
469 err(EXIT_FAILURE, "setrlimit");
471 printf("Run summary [PID %d]: %d threads monitoring%s on "
472 "%d file-descriptors for %d secs.\n\n",
473 getpid(), nthreads, oneshot ? " (EPOLLONESHOT semantics)": "", nfds, nsecs);
475 init_stats(&throughput_stats);
476 pthread_mutex_init(&thread_lock, NULL);
477 pthread_cond_init(&thread_parent, NULL);
478 pthread_cond_init(&thread_worker, NULL);
480 threads_starting = nthreads;
482 gettimeofday(&start, NULL);
484 do_threads(worker, cpu);
486 pthread_mutex_lock(&thread_lock);
487 while (threads_starting)
488 pthread_cond_wait(&thread_parent, &thread_lock);
489 pthread_cond_broadcast(&thread_worker);
490 pthread_mutex_unlock(&thread_lock);
493 * At this point the workers should be blocked waiting for read events
494 * to become ready. Launch the writer which will constantly be writing
495 * to each thread's fdmap.
497 ret = pthread_create(&wthread, NULL, writerfn,
498 (void *)(struct worker *) worker);
500 err(EXIT_FAILURE, "pthread_create");
503 toggle_done(0, NULL, NULL);
504 printinfo("main thread: toggling done\n");
508 ret = pthread_join(wthread, NULL);
510 err(EXIT_FAILURE, "pthread_join");
512 /* cleanup & report results */
513 pthread_cond_destroy(&thread_parent);
514 pthread_cond_destroy(&thread_worker);
515 pthread_mutex_destroy(&thread_lock);
517 /* sort the array back before reporting */
519 qsort(worker, nthreads, sizeof(struct worker), cmpworker);
521 for (i = 0; i < nthreads; i++) {
522 unsigned long t = worker[i].ops/runtime.tv_sec;
524 update_stats(&throughput_stats, t);
527 printf("[thread %2d] fdmap: %p [ %04ld ops/sec ]\n",
528 worker[i].tid, &worker[i].fdmap[0], t);
530 printf("[thread %2d] fdmap: %p ... %p [ %04ld ops/sec ]\n",
531 worker[i].tid, &worker[i].fdmap[0],
532 &worker[i].fdmap[nfds-1], t);
540 err(EXIT_FAILURE, "calloc");
542 #endif // HAVE_EVENTFD