blob: 3c7a16b5ed4fc14de59ff5be131491c2049d81ab [file] [log] [blame]
Craig Tillerc67cc992017-04-27 10:15:51 -07001/*
2 *
3 * Copyright 2016, Google Inc.
4 * All rights reserved.
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions are
8 * met:
9 *
10 * * Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * * Redistributions in binary form must reproduce the above
13 * copyright notice, this list of conditions and the following disclaimer
14 * in the documentation and/or other materials provided with the
15 * distribution.
16 * * Neither the name of Google Inc. nor the names of its
17 * contributors may be used to endorse or promote products derived from
18 * this software without specific prior written permission.
19 *
20 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31 *
32 */
33
34#include "src/core/lib/iomgr/port.h"
35
36/* This polling engine is only relevant on linux kernels supporting epoll() */
37#ifdef GRPC_LINUX_EPOLL
38
39#include "src/core/lib/iomgr/ev_epoll_linux.h"
40
41#include <assert.h>
42#include <errno.h>
43#include <poll.h>
44#include <pthread.h>
45#include <string.h>
46#include <sys/epoll.h>
47#include <sys/socket.h>
48#include <unistd.h>
49
50#include <grpc/support/alloc.h>
51#include <grpc/support/log.h>
52#include <grpc/support/string_util.h>
53#include <grpc/support/tls.h>
54#include <grpc/support/useful.h>
55
56#include "src/core/lib/iomgr/ev_posix.h"
57#include "src/core/lib/iomgr/iomgr_internal.h"
58#include "src/core/lib/iomgr/lockfree_event.h"
59#include "src/core/lib/iomgr/timer.h"
60#include "src/core/lib/iomgr/wakeup_fd_posix.h"
61#include "src/core/lib/iomgr/workqueue.h"
62#include "src/core/lib/profiling/timers.h"
63#include "src/core/lib/support/block_annotate.h"
64
65/* TODO: sreek: Right now, this wakes up all pollers. In future we should make
66 * sure to wake up one polling thread (which can wake up other threads if
67 * needed) */
68static grpc_wakeup_fd global_wakeup_fd;
69static int g_epfd;
70
71/*******************************************************************************
72 * Fd Declarations
73 */
74
75struct grpc_fd {
76 int fd;
77
78 /* The fd is either closed or we relinquished control of it. In either
79 cases, this indicates that the 'fd' on this structure is no longer
80 valid */
81 bool orphaned;
82
83 gpr_atm read_closure;
84 gpr_atm write_closure;
85
86 struct grpc_fd *freelist_next;
87 grpc_closure *on_done_closure;
88
89 /* The pollset that last noticed that the fd is readable. The actual type
90 * stored in this is (grpc_pollset *) */
91 gpr_atm read_notifier_pollset;
92
93 grpc_iomgr_object iomgr_object;
94};
95
96static void fd_global_init(void);
97static void fd_global_shutdown(void);
98
99/*******************************************************************************
100 * Pollset Declarations
101 */
102
103typedef struct pollset_worker_link {
104 grpc_pollset_worker *next;
105 grpc_pollset_worker *prev;
106} pollset_worker_link;
107
108typedef enum {
109 PWL_POLLSET,
110 PWL_POLLABLE,
111 POLLSET_WORKER_LINK_COUNT
112} pollset_worker_links;
113
114struct grpc_pollset_worker {
115 bool kicked;
116 bool initialized_cv;
117 pollset_worker_link links[POLLSET_WORKER_LINK_COUNT];
118 gpr_cv cv;
119};
120
121struct grpc_pollset {
122 grpc_pollset_worker root_worker;
123 bool kicked_without_pollers;
124
125 bool shutting_down; /* Is the pollset shutting down ? */
126 bool finish_shutdown_called; /* Is the 'finish_shutdown_locked()' called ? */
127 grpc_closure *shutdown_done; /* Called after after shutdown is complete */
128};
129
130/*******************************************************************************
131 * Pollset-set Declarations
132 */
133struct grpc_pollset_set {};
134
135/*******************************************************************************
136 * Common helpers
137 */
138
139static bool append_error(grpc_error **composite, grpc_error *error,
140 const char *desc) {
141 if (error == GRPC_ERROR_NONE) return true;
142 if (*composite == GRPC_ERROR_NONE) {
143 *composite = GRPC_ERROR_CREATE_FROM_COPIED_STRING(desc);
144 }
145 *composite = grpc_error_add_child(*composite, error);
146 return false;
147}
148
149/*******************************************************************************
150 * Fd Definitions
151 */
152
153/* We need to keep a freelist not because of any concerns of malloc performance
154 * but instead so that implementations with multiple threads in (for example)
155 * epoll_wait deal with the race between pollset removal and incoming poll
156 * notifications.
157 *
158 * The problem is that the poller ultimately holds a reference to this
159 * object, so it is very difficult to know when is safe to free it, at least
160 * without some expensive synchronization.
161 *
162 * If we keep the object freelisted, in the worst case losing this race just
163 * becomes a spurious read notification on a reused fd.
164 */
165
166/* The alarm system needs to be able to wakeup 'some poller' sometimes
167 * (specifically when a new alarm needs to be triggered earlier than the next
168 * alarm 'epoch'). This wakeup_fd gives us something to alert on when such a
169 * case occurs. */
170
171static grpc_fd *fd_freelist = NULL;
172static gpr_mu fd_freelist_mu;
173
174#ifdef GRPC_FD_REF_COUNT_DEBUG
175#define REF_BY(fd, n, reason) ref_by(fd, n, reason, __FILE__, __LINE__)
176#define UNREF_BY(fd, n, reason) unref_by(fd, n, reason, __FILE__, __LINE__)
177static void ref_by(grpc_fd *fd, int n, const char *reason, const char *file,
178 int line) {
179 gpr_log(GPR_DEBUG, "FD %d %p ref %d %ld -> %ld [%s; %s:%d]", fd->fd,
180 (void *)fd, n, gpr_atm_no_barrier_load(&fd->refst),
181 gpr_atm_no_barrier_load(&fd->refst) + n, reason, file, line);
182#else
183#define REF_BY(fd, n, reason) ref_by(fd, n)
184#define UNREF_BY(fd, n, reason) unref_by(fd, n)
185static void ref_by(grpc_fd *fd, int n) {
186#endif
187 GPR_ASSERT(gpr_atm_no_barrier_fetch_add(&fd->refst, n) > 0);
188}
189
190#ifdef GRPC_FD_REF_COUNT_DEBUG
191static void unref_by(grpc_fd *fd, int n, const char *reason, const char *file,
192 int line) {
193 gpr_atm old;
194 gpr_log(GPR_DEBUG, "FD %d %p unref %d %ld -> %ld [%s; %s:%d]", fd->fd,
195 (void *)fd, n, gpr_atm_no_barrier_load(&fd->refst),
196 gpr_atm_no_barrier_load(&fd->refst) - n, reason, file, line);
197#else
198static void unref_by(grpc_fd *fd, int n) {
199 gpr_atm old;
200#endif
201 old = gpr_atm_full_fetch_add(&fd->refst, -n);
202 if (old == n) {
203 /* Add the fd to the freelist */
204 gpr_mu_lock(&fd_freelist_mu);
205 fd->freelist_next = fd_freelist;
206 fd_freelist = fd;
207 grpc_iomgr_unregister_object(&fd->iomgr_object);
208
209 grpc_lfev_destroy(&fd->read_closure);
210 grpc_lfev_destroy(&fd->write_closure);
211
212 gpr_mu_unlock(&fd_freelist_mu);
213 } else {
214 GPR_ASSERT(old > n);
215 }
216}
217
218/* Increment refcount by two to avoid changing the orphan bit */
219#ifdef GRPC_FD_REF_COUNT_DEBUG
220static void fd_ref(grpc_fd *fd, const char *reason, const char *file,
221 int line) {
222 ref_by(fd, 2, reason, file, line);
223}
224
225static void fd_unref(grpc_fd *fd, const char *reason, const char *file,
226 int line) {
227 unref_by(fd, 2, reason, file, line);
228}
229#else
230static void fd_ref(grpc_fd *fd) { ref_by(fd, 2); }
231static void fd_unref(grpc_fd *fd) { unref_by(fd, 2); }
232#endif
233
234static void fd_global_init(void) { gpr_mu_init(&fd_freelist_mu); }
235
236static void fd_global_shutdown(void) {
237 gpr_mu_lock(&fd_freelist_mu);
238 gpr_mu_unlock(&fd_freelist_mu);
239 while (fd_freelist != NULL) {
240 grpc_fd *fd = fd_freelist;
241 fd_freelist = fd_freelist->freelist_next;
242 gpr_mu_destroy(&fd->po.mu);
243 gpr_free(fd);
244 }
245 gpr_mu_destroy(&fd_freelist_mu);
246}
247
248static grpc_fd *fd_create(int fd, const char *name) {
249 grpc_fd *new_fd = NULL;
250
251 gpr_mu_lock(&fd_freelist_mu);
252 if (fd_freelist != NULL) {
253 new_fd = fd_freelist;
254 fd_freelist = fd_freelist->freelist_next;
255 }
256 gpr_mu_unlock(&fd_freelist_mu);
257
258 if (new_fd == NULL) {
259 new_fd = gpr_malloc(sizeof(grpc_fd));
260 gpr_mu_init(&new_fd->po.mu);
261 }
262
263 /* Note: It is not really needed to get the new_fd->po.mu lock here. If this
264 * is a newly created fd (or an fd we got from the freelist), no one else
265 * would be holding a lock to it anyway. */
266 gpr_mu_lock(&new_fd->po.mu);
267 new_fd->po.pi = NULL;
268#ifdef PO_DEBUG
269 new_fd->po.obj_type = POLL_OBJ_FD;
270#endif
271
272 gpr_atm_rel_store(&new_fd->refst, (gpr_atm)1);
273 new_fd->fd = fd;
274 new_fd->orphaned = false;
275 grpc_lfev_init(&new_fd->read_closure);
276 grpc_lfev_init(&new_fd->write_closure);
277 gpr_atm_no_barrier_store(&new_fd->read_notifier_pollset, (gpr_atm)NULL);
278
279 new_fd->freelist_next = NULL;
280 new_fd->on_done_closure = NULL;
281
282 gpr_mu_unlock(&new_fd->po.mu);
283
284 char *fd_name;
285 gpr_asprintf(&fd_name, "%s fd=%d", name, fd);
286 grpc_iomgr_register_object(&new_fd->iomgr_object, fd_name);
287#ifdef GRPC_FD_REF_COUNT_DEBUG
288 gpr_log(GPR_DEBUG, "FD %d %p create %s", fd, (void *)new_fd, fd_name);
289#endif
290 gpr_free(fd_name);
291 return new_fd;
292}
293
294static int fd_wrapped_fd(grpc_fd *fd) {
295 int ret_fd = -1;
296 gpr_mu_lock(&fd->po.mu);
297 if (!fd->orphaned) {
298 ret_fd = fd->fd;
299 }
300 gpr_mu_unlock(&fd->po.mu);
301
302 return ret_fd;
303}
304
305static void fd_orphan(grpc_exec_ctx *exec_ctx, grpc_fd *fd,
306 grpc_closure *on_done, int *release_fd,
307 const char *reason) {
308 bool is_fd_closed = false;
309 grpc_error *error = GRPC_ERROR_NONE;
310 polling_island *unref_pi = NULL;
311
312 gpr_mu_lock(&fd->po.mu);
313 fd->on_done_closure = on_done;
314
315 /* If release_fd is not NULL, we should be relinquishing control of the file
316 descriptor fd->fd (but we still own the grpc_fd structure). */
317 if (release_fd != NULL) {
318 *release_fd = fd->fd;
319 } else {
320 close(fd->fd);
321 is_fd_closed = true;
322 }
323
324 fd->orphaned = true;
325
326 /* Remove the active status but keep referenced. We want this grpc_fd struct
327 to be alive (and not added to freelist) until the end of this function */
328 REF_BY(fd, 1, reason);
329
330 /* Remove the fd from the polling island:
331 - Get a lock on the latest polling island (i.e the last island in the
332 linked list pointed by fd->po.pi). This is the island that
333 would actually contain the fd
334 - Remove the fd from the latest polling island
335 - Unlock the latest polling island
336 - Set fd->po.pi to NULL (but remove the ref on the polling island
337 before doing this.) */
338 if (fd->po.pi != NULL) {
339 polling_island *pi_latest = polling_island_lock(fd->po.pi);
340 polling_island_remove_fd_locked(pi_latest, fd, is_fd_closed, &error);
341 gpr_mu_unlock(&pi_latest->mu);
342
343 unref_pi = fd->po.pi;
344 fd->po.pi = NULL;
345 }
346
347 grpc_closure_sched(exec_ctx, fd->on_done_closure, GRPC_ERROR_REF(error));
348
349 gpr_mu_unlock(&fd->po.mu);
350 UNREF_BY(fd, 2, reason); /* Drop the reference */
351 if (unref_pi != NULL) {
352 /* Unref stale polling island here, outside the fd lock above.
353 The polling island owns a workqueue which owns an fd, and unreffing
354 inside the lock can cause an eventual lock loop that makes TSAN very
355 unhappy. */
356 PI_UNREF(exec_ctx, unref_pi, "fd_orphan");
357 }
358 GRPC_LOG_IF_ERROR("fd_orphan", GRPC_ERROR_REF(error));
359 GRPC_ERROR_UNREF(error);
360}
361
362static grpc_pollset *fd_get_read_notifier_pollset(grpc_exec_ctx *exec_ctx,
363 grpc_fd *fd) {
364 gpr_atm notifier = gpr_atm_acq_load(&fd->read_notifier_pollset);
365 return (grpc_pollset *)notifier;
366}
367
368static bool fd_is_shutdown(grpc_fd *fd) {
369 return grpc_lfev_is_shutdown(&fd->read_closure);
370}
371
372/* Might be called multiple times */
373static void fd_shutdown(grpc_exec_ctx *exec_ctx, grpc_fd *fd, grpc_error *why) {
374 if (grpc_lfev_set_shutdown(exec_ctx, &fd->read_closure,
375 GRPC_ERROR_REF(why))) {
376 shutdown(fd->fd, SHUT_RDWR);
377 grpc_lfev_set_shutdown(exec_ctx, &fd->write_closure, GRPC_ERROR_REF(why));
378 }
379 GRPC_ERROR_UNREF(why);
380}
381
382static void fd_notify_on_read(grpc_exec_ctx *exec_ctx, grpc_fd *fd,
383 grpc_closure *closure) {
384 grpc_lfev_notify_on(exec_ctx, &fd->read_closure, closure);
385}
386
387static void fd_notify_on_write(grpc_exec_ctx *exec_ctx, grpc_fd *fd,
388 grpc_closure *closure) {
389 grpc_lfev_notify_on(exec_ctx, &fd->write_closure, closure);
390}
391
392static grpc_workqueue *fd_get_workqueue(grpc_fd *fd) {
393 gpr_mu_lock(&fd->po.mu);
394 grpc_workqueue *workqueue =
395 GRPC_WORKQUEUE_REF((grpc_workqueue *)fd->po.pi, "fd_get_workqueue");
396 gpr_mu_unlock(&fd->po.mu);
397 return workqueue;
398}
399
400/*******************************************************************************
401 * Pollset Definitions
402 */
403
404/* Return true if first in list */
405static bool worker_insert(grpc_pollset_worker **root, pollset_worker_links link,
406 grpc_pollset_worker *worker) {
407 if (*root == NULL) {
408 *root = worker;
409 worker->links[link].next = worker->links[link].prev = worker;
410 return true;
411 } else {
412 worker->links[link].next = *root;
413 worker->links[link].prev = worker->links[link].next->links[link].prev;
414 worker->links[link].next->links[link].prev = worker;
415 worker->links[link].prev->links[link].next = worker;
416 return false;
417 }
418}
419
420/* Return true if last in list */
421typedef enum { EMPTIED, NEW_ROOT, REMOVED } worker_remove_result;
422
423static worker_remove_result worker_remove(grpc_pollset_worker **root,
424 pollset_worker_links link,
425 grpc_pollset_worker *worker) {
426 if (worker == *root) {
427 if (worker == worker->links[link].next) {
428 *root = NULL;
429 return EMPTIED;
430 } else {
431 *root = worker->links[link].next;
432 worker->links[link].prev->links[link].next = worker->links[link].next;
433 worker->links[link].next->links[link].prev = worker->links[link].prev;
434 return NEW_ROOT;
435 }
436 } else {
437 worker->links[link].prev->links[link].next = worker->links[link].next;
438 worker->links[link].next->links[link].prev = worker->links[link].prev;
439 return REMOVED;
440 }
441}
442
443GPR_TLS_DECL(g_current_thread_pollset);
444GPR_TLS_DECL(g_current_thread_worker);
445
446/*******************************************************************************
447 * Pollset-set Definitions
448 */
449
450static grpc_pollset_set *pollset_set_create(void) {
451 return (grpc_pollset_set *)((intptr_t)0xdeafbeef);
452}
453
454static void pollset_set_destroy(grpc_exec_ctx *exec_ctx,
455 grpc_pollset_set *pss) {}
456
457static void pollset_set_add_fd(grpc_exec_ctx *exec_ctx, grpc_pollset_set *pss,
458 grpc_fd *fd) {}
459
460static void pollset_set_del_fd(grpc_exec_ctx *exec_ctx, grpc_pollset_set *pss,
461 grpc_fd *fd) {}
462
463static void pollset_set_add_pollset(grpc_exec_ctx *exec_ctx,
464 grpc_pollset_set *pss, grpc_pollset *ps) {}
465
466static void pollset_set_del_pollset(grpc_exec_ctx *exec_ctx,
467 grpc_pollset_set *pss, grpc_pollset *ps) {}
468
469static void pollset_set_add_pollset_set(grpc_exec_ctx *exec_ctx,
470 grpc_pollset_set *bag,
471 grpc_pollset_set *item) {}
472
473static void pollset_set_del_pollset_set(grpc_exec_ctx *exec_ctx,
474 grpc_pollset_set *bag,
475 grpc_pollset_set *item) {}
476
477/*******************************************************************************
478 * Event engine binding
479 */
480
481static void shutdown_engine(void) {
482 fd_global_shutdown();
483 pollset_global_shutdown();
484 polling_island_global_shutdown();
485}
486
487static const grpc_event_engine_vtable vtable = {
488 .pollset_size = sizeof(grpc_pollset),
489
490 .fd_create = fd_create,
491 .fd_wrapped_fd = fd_wrapped_fd,
492 .fd_orphan = fd_orphan,
493 .fd_shutdown = fd_shutdown,
494 .fd_is_shutdown = fd_is_shutdown,
495 .fd_notify_on_read = fd_notify_on_read,
496 .fd_notify_on_write = fd_notify_on_write,
497 .fd_get_read_notifier_pollset = fd_get_read_notifier_pollset,
498 .fd_get_workqueue = fd_get_workqueue,
499
500 .pollset_init = pollset_init,
501 .pollset_shutdown = pollset_shutdown,
502 .pollset_destroy = pollset_destroy,
503 .pollset_work = pollset_work,
504 .pollset_kick = pollset_kick,
505 .pollset_add_fd = pollset_add_fd,
506
507 .pollset_set_create = pollset_set_create,
508 .pollset_set_destroy = pollset_set_destroy,
509 .pollset_set_add_pollset = pollset_set_add_pollset,
510 .pollset_set_del_pollset = pollset_set_del_pollset,
511 .pollset_set_add_pollset_set = pollset_set_add_pollset_set,
512 .pollset_set_del_pollset_set = pollset_set_del_pollset_set,
513 .pollset_set_add_fd = pollset_set_add_fd,
514 .pollset_set_del_fd = pollset_set_del_fd,
515
516 .kick_poller = kick_poller,
517
518 .workqueue_ref = workqueue_ref,
519 .workqueue_unref = workqueue_unref,
520 .workqueue_scheduler = workqueue_scheduler,
521
522 .shutdown_engine = shutdown_engine,
523};
524
525/* It is possible that GLIBC has epoll but the underlying kernel doesn't.
526 * Create a dummy epoll_fd to make sure epoll support is available */
527static bool is_epoll_available() {
528 int fd = epoll_create1(EPOLL_CLOEXEC);
529 if (fd < 0) {
530 gpr_log(
531 GPR_ERROR,
532 "epoll_create1 failed with error: %d. Not using epoll polling engine",
533 fd);
534 return false;
535 }
536 close(fd);
537 return true;
538}
539
540const grpc_event_engine_vtable *grpc_init_epoll1_linux(void) {
541 /* If use of signals is disabled, we cannot use epoll engine*/
542 if (is_grpc_wakeup_signal_initialized && grpc_wakeup_signal < 0) {
543 return NULL;
544 }
545
546 if (!grpc_has_wakeup_fd()) {
547 return NULL;
548 }
549
550 if (!is_epoll_available()) {
551 return NULL;
552 }
553
554 if (!is_grpc_wakeup_signal_initialized) {
555 grpc_use_signal(SIGRTMIN + 6);
556 }
557
558 fd_global_init();
559
560 if (!GRPC_LOG_IF_ERROR("pollset_global_init", pollset_global_init())) {
561 return NULL;
562 }
563
564 if (!GRPC_LOG_IF_ERROR("polling_island_global_init",
565 polling_island_global_init())) {
566 return NULL;
567 }
568
569 return &vtable;
570}
571
572#else /* defined(GRPC_LINUX_EPOLL) */
573#if defined(GRPC_POSIX_SOCKET)
574#include "src/core/lib/iomgr/ev_posix.h"
575/* If GRPC_LINUX_EPOLL is not defined, it means epoll is not available. Return
576 * NULL */
577const grpc_event_engine_vtable *grpc_init_epoll1_linux(void) { return NULL; }
578#endif /* defined(GRPC_POSIX_SOCKET) */
579#endif /* !defined(GRPC_LINUX_EPOLL) */