epoll-wait.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  1. // SPDX-License-Identifier: GPL-2.0
  2. #ifdef HAVE_EVENTFD_SUPPORT
  3. /*
  4. * Copyright (C) 2018 Davidlohr Bueso.
  5. *
  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):
  10. *
  11. * |---> [worker A]
  12. * |---> [worker B]
  13. * [combined queue] .---> [worker C]
  14. * |---> [worker D]
  15. * |---> [worker E]
  16. *
  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. * distribute the accept()'ing connections across CPUs. In this case each
  21. * worker does a limited amount of processing.
  22. *
  23. * [queue A] ---> [worker]
  24. * [queue B] ---> [worker]
  25. * [queue C] ---> [worker]
  26. * [queue D] ---> [worker]
  27. * [queue E] ---> [worker]
  28. *
  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.
  33. * Each thread has a number of private, nonblocking file descriptors,
  34. * referred to as fdmap. A writer thread will constantly be writing to
  35. * the fdmaps of all threads, minimizing each threads's chances of
  36. * epoll_wait not finding any ready read events and blocking as this
  37. * is not what we want to stress. The size of the fdmap can be adjusted
  38. * by the user; enlarging the value will increase the chances of
  39. * epoll_wait(2) blocking as the lineal writer thread will take "longer",
  40. * at least at a high level.
  41. *
  42. * Note that because fds are private to each thread, this workload does
  43. * not stress scenarios where multiple tasks are awoken per ready IO; ie:
  44. * EPOLLEXCLUSIVE semantics.
  45. *
  46. * The end result/metric is throughput: number of ops/second where an
  47. * operation consists of:
  48. *
  49. * epoll_wait(2) + [others]
  50. *
  51. * ... where [others] is the cost of re-adding the fd (EPOLLET),
  52. * or rearming it (EPOLLONESHOT).
  53. *
  54. *
  55. * The purpose of this is program is that it be useful for measuring
  56. * kernel related changes to the sys_epoll, and not comparing different
  57. * IO polling methods, for example. Hence everything is very adhoc and
  58. * outputs raw microbenchmark numbers. Also this uses eventfd, similar
  59. * tools tend to use pipes or sockets, but the result is the same.
  60. */
  61. /* For the CLR_() macros */
  62. #include <string.h>
  63. #include <pthread.h>
  64. #include <unistd.h>
  65. #include <errno.h>
  66. #include <inttypes.h>
  67. #include <signal.h>
  68. #include <stdlib.h>
  69. #include <linux/compiler.h>
  70. #include <linux/kernel.h>
  71. #include <sys/time.h>
  72. #include <sys/resource.h>
  73. #include <sys/epoll.h>
  74. #include <sys/eventfd.h>
  75. #include <sys/types.h>
  76. #include <perf/cpumap.h>
  77. #include "../util/stat.h"
  78. #include "../util/mutex.h"
  79. #include <subcmd/parse-options.h>
  80. #include "bench.h"
  81. #include <err.h>
  82. #define printinfo(fmt, arg...) \
  83. do { if (__verbose) { printf(fmt, ## arg); fflush(stdout); } } while (0)
  84. static unsigned int nthreads = 0;
  85. static unsigned int nsecs = 8;
  86. static bool wdone, done, __verbose, randomize, nonblocking;
  87. /*
  88. * epoll related shared variables.
  89. */
  90. /* Maximum number of nesting allowed inside epoll sets */
  91. #define EPOLL_MAXNESTS 4
  92. static int epollfd;
  93. static int *epollfdp;
  94. static bool noaffinity;
  95. static unsigned int nested = 0;
  96. static bool et; /* edge-trigger */
  97. static bool oneshot;
  98. static bool multiq; /* use an epoll instance per thread */
  99. /* amount of fds to monitor, per thread */
  100. static unsigned int nfds = 64;
  101. static struct mutex thread_lock;
  102. static unsigned int threads_starting;
  103. static struct stats throughput_stats;
  104. static struct cond thread_parent, thread_worker;
  105. struct worker {
  106. int tid;
  107. int epollfd; /* for --multiq */
  108. pthread_t thread;
  109. unsigned long ops;
  110. int *fdmap;
  111. };
  112. static const struct option options[] = {
  113. /* general benchmark options */
  114. OPT_UINTEGER('t', "threads", &nthreads, "Specify amount of threads"),
  115. OPT_UINTEGER('r', "runtime", &nsecs, "Specify runtime (in seconds)"),
  116. OPT_UINTEGER('f', "nfds", &nfds, "Specify amount of file descriptors to monitor for each thread"),
  117. OPT_BOOLEAN( 'n', "noaffinity", &noaffinity, "Disables CPU affinity"),
  118. OPT_BOOLEAN('R', "randomize", &randomize, "Enable random write behaviour (default is lineal)"),
  119. OPT_BOOLEAN( 'v', "verbose", &__verbose, "Verbose mode"),
  120. /* epoll specific options */
  121. OPT_BOOLEAN( 'm', "multiq", &multiq, "Use multiple epoll instances (one per thread)"),
  122. OPT_BOOLEAN( 'B', "nonblocking", &nonblocking, "Nonblocking epoll_wait(2) behaviour"),
  123. OPT_UINTEGER( 'N', "nested", &nested, "Nesting level epoll hierarchy (default is 0, no nesting)"),
  124. OPT_BOOLEAN( 'S', "oneshot", &oneshot, "Use EPOLLONESHOT semantics"),
  125. OPT_BOOLEAN( 'E', "edge", &et, "Use Edge-triggered interface (default is LT)"),
  126. OPT_END()
  127. };
  128. static const char * const bench_epoll_wait_usage[] = {
  129. "perf bench epoll wait <options>",
  130. NULL
  131. };
  132. /*
  133. * Arrange the N elements of ARRAY in random order.
  134. * Only effective if N is much smaller than RAND_MAX;
  135. * if this may not be the case, use a better random
  136. * number generator. -- Ben Pfaff.
  137. */
  138. static void shuffle(void *array, size_t n, size_t size)
  139. {
  140. char *carray = array;
  141. void *aux;
  142. size_t i;
  143. if (n <= 1)
  144. return;
  145. aux = calloc(1, size);
  146. if (!aux)
  147. err(EXIT_FAILURE, "calloc");
  148. for (i = 1; i < n; ++i) {
  149. size_t j = i + rand() / (RAND_MAX / (n - i) + 1);
  150. j *= size;
  151. memcpy(aux, &carray[j], size);
  152. memcpy(&carray[j], &carray[i*size], size);
  153. memcpy(&carray[i*size], aux, size);
  154. }
  155. free(aux);
  156. }
  157. static void *workerfn(void *arg)
  158. {
  159. int fd, ret, r;
  160. struct worker *w = (struct worker *) arg;
  161. unsigned long ops = w->ops;
  162. struct epoll_event ev;
  163. uint64_t val;
  164. int to = nonblocking? 0 : -1;
  165. int efd = multiq ? w->epollfd : epollfd;
  166. mutex_lock(&thread_lock);
  167. threads_starting--;
  168. if (!threads_starting)
  169. cond_signal(&thread_parent);
  170. cond_wait(&thread_worker, &thread_lock);
  171. mutex_unlock(&thread_lock);
  172. do {
  173. /*
  174. * Block indefinitely waiting for the IN event.
  175. * In order to stress the epoll_wait(2) syscall,
  176. * call it event per event, instead of a larger
  177. * batch (max)limit.
  178. */
  179. do {
  180. ret = epoll_wait(efd, &ev, 1, to);
  181. } while (ret < 0 && errno == EINTR);
  182. if (ret < 0)
  183. err(EXIT_FAILURE, "epoll_wait");
  184. fd = ev.data.fd;
  185. do {
  186. r = read(fd, &val, sizeof(val));
  187. } while (!done && (r < 0 && errno == EAGAIN));
  188. if (et) {
  189. ev.events = EPOLLIN | EPOLLET;
  190. ret = epoll_ctl(efd, EPOLL_CTL_ADD, fd, &ev);
  191. }
  192. if (oneshot) {
  193. /* rearm the file descriptor with a new event mask */
  194. ev.events |= EPOLLIN | EPOLLONESHOT;
  195. ret = epoll_ctl(efd, EPOLL_CTL_MOD, fd, &ev);
  196. }
  197. ops++;
  198. } while (!done);
  199. if (multiq)
  200. close(w->epollfd);
  201. w->ops = ops;
  202. return NULL;
  203. }
  204. static void nest_epollfd(struct worker *w)
  205. {
  206. unsigned int i;
  207. struct epoll_event ev;
  208. int efd = multiq ? w->epollfd : epollfd;
  209. if (nested > EPOLL_MAXNESTS)
  210. nested = EPOLL_MAXNESTS;
  211. epollfdp = calloc(nested, sizeof(*epollfdp));
  212. if (!epollfdp)
  213. err(EXIT_FAILURE, "calloc");
  214. for (i = 0; i < nested; i++) {
  215. epollfdp[i] = epoll_create(1);
  216. if (epollfdp[i] < 0)
  217. err(EXIT_FAILURE, "epoll_create");
  218. }
  219. ev.events = EPOLLHUP; /* anything */
  220. ev.data.u64 = i; /* any number */
  221. for (i = nested - 1; i; i--) {
  222. if (epoll_ctl(epollfdp[i - 1], EPOLL_CTL_ADD,
  223. epollfdp[i], &ev) < 0)
  224. err(EXIT_FAILURE, "epoll_ctl");
  225. }
  226. if (epoll_ctl(efd, EPOLL_CTL_ADD, *epollfdp, &ev) < 0)
  227. err(EXIT_FAILURE, "epoll_ctl");
  228. }
  229. static void toggle_done(int sig __maybe_unused,
  230. siginfo_t *info __maybe_unused,
  231. void *uc __maybe_unused)
  232. {
  233. /* inform all threads that we're done for the day */
  234. done = true;
  235. gettimeofday(&bench__end, NULL);
  236. timersub(&bench__end, &bench__start, &bench__runtime);
  237. }
  238. static void print_summary(void)
  239. {
  240. unsigned long avg = avg_stats(&throughput_stats);
  241. double stddev = stddev_stats(&throughput_stats);
  242. printf("\nAveraged %ld operations/sec (+- %.2f%%), total secs = %d\n",
  243. avg, rel_stddev_stats(stddev, avg),
  244. (int)bench__runtime.tv_sec);
  245. }
  246. static int do_threads(struct worker *worker, struct perf_cpu_map *cpu)
  247. {
  248. pthread_attr_t thread_attr, *attrp = NULL;
  249. cpu_set_t *cpuset;
  250. unsigned int i, j;
  251. int ret = 0, events = EPOLLIN;
  252. int nrcpus;
  253. size_t size;
  254. if (oneshot)
  255. events |= EPOLLONESHOT;
  256. if (et)
  257. events |= EPOLLET;
  258. printinfo("starting worker/consumer %sthreads%s\n",
  259. noaffinity ? "":"CPU affinity ",
  260. nonblocking ? " (nonblocking)":"");
  261. if (!noaffinity)
  262. pthread_attr_init(&thread_attr);
  263. nrcpus = cpu__max_cpu().cpu;
  264. cpuset = CPU_ALLOC(nrcpus);
  265. BUG_ON(!cpuset);
  266. size = CPU_ALLOC_SIZE(nrcpus);
  267. for (i = 0; i < nthreads; i++) {
  268. struct worker *w = &worker[i];
  269. if (multiq) {
  270. w->epollfd = epoll_create(1);
  271. if (w->epollfd < 0)
  272. err(EXIT_FAILURE, "epoll_create");
  273. if (nested)
  274. nest_epollfd(w);
  275. }
  276. w->tid = i;
  277. w->fdmap = calloc(nfds, sizeof(int));
  278. if (!w->fdmap)
  279. return 1;
  280. for (j = 0; j < nfds; j++) {
  281. int efd = multiq ? w->epollfd : epollfd;
  282. struct epoll_event ev;
  283. w->fdmap[j] = eventfd(0, EFD_NONBLOCK);
  284. if (w->fdmap[j] < 0)
  285. err(EXIT_FAILURE, "eventfd");
  286. ev.data.fd = w->fdmap[j];
  287. ev.events = events;
  288. ret = epoll_ctl(efd, EPOLL_CTL_ADD,
  289. w->fdmap[j], &ev);
  290. if (ret < 0)
  291. err(EXIT_FAILURE, "epoll_ctl");
  292. }
  293. if (!noaffinity) {
  294. CPU_ZERO_S(size, cpuset);
  295. CPU_SET_S(perf_cpu_map__cpu(cpu, i % perf_cpu_map__nr(cpu)).cpu,
  296. size, cpuset);
  297. ret = pthread_attr_setaffinity_np(&thread_attr, size, cpuset);
  298. if (ret) {
  299. CPU_FREE(cpuset);
  300. err(EXIT_FAILURE, "pthread_attr_setaffinity_np");
  301. }
  302. attrp = &thread_attr;
  303. }
  304. ret = pthread_create(&w->thread, attrp, workerfn,
  305. (void *)(struct worker *) w);
  306. if (ret) {
  307. CPU_FREE(cpuset);
  308. err(EXIT_FAILURE, "pthread_create");
  309. }
  310. }
  311. CPU_FREE(cpuset);
  312. if (!noaffinity)
  313. pthread_attr_destroy(&thread_attr);
  314. return ret;
  315. }
  316. static void *writerfn(void *p)
  317. {
  318. struct worker *worker = p;
  319. size_t i, j, iter;
  320. const uint64_t val = 1;
  321. ssize_t sz;
  322. struct timespec ts = { .tv_sec = 0,
  323. .tv_nsec = 500 };
  324. printinfo("starting writer-thread: doing %s writes ...\n",
  325. randomize? "random":"lineal");
  326. for (iter = 0; !wdone; iter++) {
  327. if (randomize) {
  328. shuffle((void *)worker, nthreads, sizeof(*worker));
  329. }
  330. for (i = 0; i < nthreads; i++) {
  331. struct worker *w = &worker[i];
  332. if (randomize) {
  333. shuffle((void *)w->fdmap, nfds, sizeof(int));
  334. }
  335. for (j = 0; j < nfds; j++) {
  336. do {
  337. sz = write(w->fdmap[j], &val, sizeof(val));
  338. } while (!wdone && (sz < 0 && errno == EAGAIN));
  339. }
  340. }
  341. nanosleep(&ts, NULL);
  342. }
  343. printinfo("exiting writer-thread (total full-loops: %zd)\n", iter);
  344. return NULL;
  345. }
  346. static int cmpworker(const void *p1, const void *p2)
  347. {
  348. struct worker *w1 = (struct worker *) p1;
  349. struct worker *w2 = (struct worker *) p2;
  350. if (w1->tid > w2->tid)
  351. return 1;
  352. if (w1->tid < w2->tid)
  353. return -1;
  354. return 0;
  355. }
  356. int bench_epoll_wait(int argc, const char **argv)
  357. {
  358. int ret = 0;
  359. struct sigaction act;
  360. unsigned int i;
  361. struct worker *worker = NULL;
  362. struct perf_cpu_map *cpu;
  363. pthread_t wthread;
  364. struct rlimit rl, prevrl;
  365. argc = parse_options(argc, argv, options, bench_epoll_wait_usage, 0);
  366. if (argc) {
  367. usage_with_options(bench_epoll_wait_usage, options);
  368. exit(EXIT_FAILURE);
  369. }
  370. memset(&act, 0, sizeof(act));
  371. sigfillset(&act.sa_mask);
  372. act.sa_sigaction = toggle_done;
  373. sigaction(SIGINT, &act, NULL);
  374. cpu = perf_cpu_map__new_online_cpus();
  375. if (!cpu)
  376. goto errmem;
  377. /* a single, main epoll instance */
  378. if (!multiq) {
  379. epollfd = epoll_create(1);
  380. if (epollfd < 0)
  381. err(EXIT_FAILURE, "epoll_create");
  382. /*
  383. * Deal with nested epolls, if any.
  384. */
  385. if (nested)
  386. nest_epollfd(NULL);
  387. }
  388. printinfo("Using %s queue model\n", multiq ? "multi" : "single");
  389. printinfo("Nesting level(s): %d\n", nested);
  390. /* default to the number of CPUs and leave one for the writer pthread */
  391. if (!nthreads)
  392. nthreads = perf_cpu_map__nr(cpu) - 1;
  393. worker = calloc(nthreads, sizeof(*worker));
  394. if (!worker) {
  395. goto errmem;
  396. }
  397. if (getrlimit(RLIMIT_NOFILE, &prevrl))
  398. err(EXIT_FAILURE, "getrlimit");
  399. rl.rlim_cur = rl.rlim_max = nfds * nthreads * 2 + 50;
  400. printinfo("Setting RLIMIT_NOFILE rlimit from %" PRIu64 " to: %" PRIu64 "\n",
  401. (uint64_t)prevrl.rlim_max, (uint64_t)rl.rlim_max);
  402. if (setrlimit(RLIMIT_NOFILE, &rl) < 0)
  403. err(EXIT_FAILURE, "setrlimit");
  404. printf("Run summary [PID %d]: %d threads monitoring%s on "
  405. "%d file-descriptors for %d secs.\n\n",
  406. getpid(), nthreads, oneshot ? " (EPOLLONESHOT semantics)": "", nfds, nsecs);
  407. init_stats(&throughput_stats);
  408. mutex_init(&thread_lock);
  409. cond_init(&thread_parent);
  410. cond_init(&thread_worker);
  411. threads_starting = nthreads;
  412. gettimeofday(&bench__start, NULL);
  413. do_threads(worker, cpu);
  414. mutex_lock(&thread_lock);
  415. while (threads_starting)
  416. cond_wait(&thread_parent, &thread_lock);
  417. cond_broadcast(&thread_worker);
  418. mutex_unlock(&thread_lock);
  419. /*
  420. * At this point the workers should be blocked waiting for read events
  421. * to become ready. Launch the writer which will constantly be writing
  422. * to each thread's fdmap.
  423. */
  424. ret = pthread_create(&wthread, NULL, writerfn,
  425. (void *)(struct worker *) worker);
  426. if (ret)
  427. err(EXIT_FAILURE, "pthread_create");
  428. sleep(nsecs);
  429. toggle_done(0, NULL, NULL);
  430. printinfo("main thread: toggling done\n");
  431. sleep(1); /* meh */
  432. wdone = true;
  433. ret = pthread_join(wthread, NULL);
  434. if (ret)
  435. err(EXIT_FAILURE, "pthread_join");
  436. /* cleanup & report results */
  437. cond_destroy(&thread_parent);
  438. cond_destroy(&thread_worker);
  439. mutex_destroy(&thread_lock);
  440. /* sort the array back before reporting */
  441. if (randomize)
  442. qsort(worker, nthreads, sizeof(struct worker), cmpworker);
  443. for (i = 0; i < nthreads; i++) {
  444. unsigned long t = bench__runtime.tv_sec > 0 ?
  445. worker[i].ops / bench__runtime.tv_sec : 0;
  446. update_stats(&throughput_stats, t);
  447. if (nfds == 1)
  448. printf("[thread %2d] fdmap: %p [ %04ld ops/sec ]\n",
  449. worker[i].tid, &worker[i].fdmap[0], t);
  450. else
  451. printf("[thread %2d] fdmap: %p ... %p [ %04ld ops/sec ]\n",
  452. worker[i].tid, &worker[i].fdmap[0],
  453. &worker[i].fdmap[nfds-1], t);
  454. }
  455. print_summary();
  456. close(epollfd);
  457. perf_cpu_map__put(cpu);
  458. for (i = 0; i < nthreads; i++)
  459. free(worker[i].fdmap);
  460. free(worker);
  461. return ret;
  462. errmem:
  463. err(EXIT_FAILURE, "calloc");
  464. }
  465. #endif // HAVE_EVENTFD_SUPPORT