blob: ce42a9e7ce614558217296a6a7f8f42b6f6cd4bf [file] [log] [blame]
Sree Kuchibhotlaf448c342016-05-19 10:51:24 -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 <grpc/support/port_platform.h>
35
36#ifdef GPR_POSIX_SOCKET
37
38#include "src/core/lib/iomgr/ev_epoll_posix.h"
39
40#include <assert.h>
41#include <errno.h>
42#include <poll.h>
43#include <signal.h>
44#include <string.h>
45#include <sys/epoll.h>
46#include <sys/socket.h>
47#include <unistd.h>
48
49#include <grpc/support/alloc.h>
50#include <grpc/support/log.h>
51#include <grpc/support/string_util.h>
52#include <grpc/support/tls.h>
53#include <grpc/support/useful.h>
54
55#include "src/core/lib/iomgr/ev_posix.h"
56#include "src/core/lib/iomgr/iomgr_internal.h"
57#include "src/core/lib/iomgr/wakeup_fd_posix.h"
58#include "src/core/lib/profiling/timers.h"
59#include "src/core/lib/support/block_annotate.h"
60
61struct polling_island;
62
63/*******************************************************************************
Sree Kuchibhotla0bcbd792016-06-01 15:43:03 -070064 * Fd Declarations
Sree Kuchibhotlaf448c342016-05-19 10:51:24 -070065 */
Sree Kuchibhotlaf448c342016-05-19 10:51:24 -070066struct grpc_fd {
67 int fd;
68 /* refst format:
Sree Kuchibhotla5098f912016-05-31 10:58:17 -070069 bit 0 : 1=Active / 0=Orphaned
70 bits 1-n : refcount
Sree Kuchibhotla0bcbd792016-06-01 15:43:03 -070071 Ref/Unref by two to avoid altering the orphaned bit */
Sree Kuchibhotlaf448c342016-05-19 10:51:24 -070072 gpr_atm refst;
73
74 gpr_mu mu;
Sree Kuchibhotla0bcbd792016-06-01 15:43:03 -070075 bool shutdown;
Sree Kuchibhotlaf448c342016-05-19 10:51:24 -070076 int closed;
Sree Kuchibhotla0bcbd792016-06-01 15:43:03 -070077 bool released;
Sree Kuchibhotlaf448c342016-05-19 10:51:24 -070078
79 grpc_closure *read_closure;
80 grpc_closure *write_closure;
81
Sree Kuchibhotla0bcbd792016-06-01 15:43:03 -070082 /* The polling island to which this fd belongs to and the mutex protecting the
83 the field */
Sree Kuchibhotlaf448c342016-05-19 10:51:24 -070084 gpr_mu pi_mu;
Sree Kuchibhotlaf448c342016-05-19 10:51:24 -070085 struct polling_island *polling_island;
86
87 struct grpc_fd *freelist_next;
Sree Kuchibhotlaf448c342016-05-19 10:51:24 -070088 grpc_closure *on_done_closure;
89
90 grpc_iomgr_object iomgr_object;
91};
92
Sree Kuchibhotlaf448c342016-05-19 10:51:24 -070093/* Reference counting for fds */
Sree Kuchibhotlaf448c342016-05-19 10:51:24 -070094#ifdef GRPC_FD_REF_COUNT_DEBUG
95static void fd_ref(grpc_fd *fd, const char *reason, const char *file, int line);
96static void fd_unref(grpc_fd *fd, const char *reason, const char *file,
97 int line);
98#define GRPC_FD_REF(fd, reason) fd_ref(fd, reason, __FILE__, __LINE__)
99#define GRPC_FD_UNREF(fd, reason) fd_unref(fd, reason, __FILE__, __LINE__)
100#else
101static void fd_ref(grpc_fd *fd);
102static void fd_unref(grpc_fd *fd);
103#define GRPC_FD_REF(fd, reason) fd_ref(fd)
104#define GRPC_FD_UNREF(fd, reason) fd_unref(fd)
105#endif
106
107static void fd_global_init(void);
108static void fd_global_shutdown(void);
109
110#define CLOSURE_NOT_READY ((grpc_closure *)0)
111#define CLOSURE_READY ((grpc_closure *)1)
112
113/*******************************************************************************
Sree Kuchibhotla0bcbd792016-06-01 15:43:03 -0700114 * Polling-island Declarations
Sree Kuchibhotlaf448c342016-05-19 10:51:24 -0700115 */
116typedef struct polling_island {
117 gpr_mu mu;
118 int ref_cnt;
119
Sree Kuchibhotla0bcbd792016-06-01 15:43:03 -0700120 /* Points to the polling_island this merged into.
121 * If merged_to is not NULL, all the remaining fields (except mu and ref_cnt)
122 * are invalid and must be ignored */
Sree Kuchibhotlaf448c342016-05-19 10:51:24 -0700123 struct polling_island *merged_to;
124
125 /* The fd of the underlying epoll set */
126 int epoll_fd;
127
128 /* The file descriptors in the epoll set */
129 size_t fd_cnt;
130 size_t fd_capacity;
131 grpc_fd **fds;
132
133 /* Polling islands that are no longer needed are kept in a freelist so that
134 they can be reused. This field points to the next polling island in the
Sree Kuchibhotlaf448c342016-05-19 10:51:24 -0700135 free list */
136 struct polling_island *next_free;
137} polling_island;
138
Sree Kuchibhotla0bcbd792016-06-01 15:43:03 -0700139/*******************************************************************************
140 * Pollset Declarations
141 */
142
143struct grpc_pollset_worker {
144 int kicked_specifically;
145 pthread_t pt_id; /* TODO (sreek) - Add an abstraction here */
146 struct grpc_pollset_worker *next;
147 struct grpc_pollset_worker *prev;
148};
149
150struct grpc_pollset {
151 gpr_mu mu;
152 grpc_pollset_worker root_worker;
153 bool kicked_without_pollers;
154
155 bool shutting_down; /* Is the pollset shutting down ? */
156 bool finish_shutdown_called; /* Is the 'finish_shutdown_locked()' called ? */
157 grpc_closure *shutdown_done; /* Called after after shutdown is complete */
158
159 /* The polling island to which this pollset belongs to and the mutex
160 protecting the field */
161 gpr_mu pi_mu;
162 struct polling_island *polling_island;
163};
164
165/*******************************************************************************
166 * Pollset-set Declarations
167 */
168struct grpc_pollset_set {
169 gpr_mu mu;
170
171 size_t pollset_count;
172 size_t pollset_capacity;
173 grpc_pollset **pollsets;
174
175 size_t pollset_set_count;
176 size_t pollset_set_capacity;
177 struct grpc_pollset_set **pollset_sets;
178
179 size_t fd_count;
180 size_t fd_capacity;
181 grpc_fd **fds;
182};
183
184/*******************************************************************************
185 * Polling-island Definitions
186 */
187
Sree Kuchibhotlaf448c342016-05-19 10:51:24 -0700188/* Polling island freelist */
189static gpr_mu g_pi_freelist_mu;
190static polling_island *g_pi_freelist = NULL;
191
Sree Kuchibhotla9442bab2016-05-20 17:54:06 -0700192/* The caller is expected to hold pi->mu lock before calling this function */
193static void polling_island_add_fds_locked(polling_island *pi, grpc_fd **fds,
Sree Kuchibhotla0bcbd792016-06-01 15:43:03 -0700194 size_t fd_count, bool add_fd_refs) {
Sree Kuchibhotlaf448c342016-05-19 10:51:24 -0700195 int err;
Sree Kuchibhotla9442bab2016-05-20 17:54:06 -0700196 size_t i;
Sree Kuchibhotlaf448c342016-05-19 10:51:24 -0700197 struct epoll_event ev;
198
Sree Kuchibhotla9442bab2016-05-20 17:54:06 -0700199 for (i = 0; i < fd_count; i++) {
200 ev.events = (uint32_t)(EPOLLIN | EPOLLOUT | EPOLLET);
201 ev.data.ptr = fds[i];
202 err = epoll_ctl(pi->epoll_fd, EPOLL_CTL_ADD, fds[i]->fd, &ev);
Sree Kuchibhotlaf448c342016-05-19 10:51:24 -0700203
Sree Kuchibhotla0bcbd792016-06-01 15:43:03 -0700204 if (err < 0) {
205 if (errno != EEXIST) {
206 /* TODO: sreek - We need a better way to bubble up this error instead of
207 just logging a message */
208 gpr_log(GPR_ERROR, "epoll_ctl add for fd: %d failed with error: %s",
209 fds[i]->fd, strerror(errno));
210 }
211
Sree Kuchibhotla9442bab2016-05-20 17:54:06 -0700212 continue;
213 }
214
215 if (pi->fd_cnt == pi->fd_capacity) {
216 pi->fd_capacity = GPR_MAX(pi->fd_capacity + 8, pi->fd_cnt * 3 / 2);
217 pi->fds = gpr_realloc(pi->fds, sizeof(grpc_fd *) * pi->fd_capacity);
218 }
219
220 pi->fds[pi->fd_cnt++] = fds[i];
Sree Kuchibhotla0bcbd792016-06-01 15:43:03 -0700221 if (add_fd_refs) {
222 GRPC_FD_REF(fds[i], "polling_island");
223 }
Sree Kuchibhotlaf448c342016-05-19 10:51:24 -0700224 }
Sree Kuchibhotlaf448c342016-05-19 10:51:24 -0700225}
226
Sree Kuchibhotla9442bab2016-05-20 17:54:06 -0700227/* The caller is expected to hold pi->mu lock before calling this function */
Sree Kuchibhotla0bcbd792016-06-01 15:43:03 -0700228static void polling_island_remove_all_fds_locked(polling_island *pi,
229 bool remove_fd_refs) {
Sree Kuchibhotla9442bab2016-05-20 17:54:06 -0700230 int err;
231 size_t i;
232
233 for (i = 0; i < pi->fd_cnt; i++) {
Sree Kuchibhotla0bcbd792016-06-01 15:43:03 -0700234 if (remove_fd_refs) {
235 GRPC_FD_UNREF(pi->fds[i], "polling_island");
236 }
Sree Kuchibhotla9442bab2016-05-20 17:54:06 -0700237
Sree Kuchibhotla0bcbd792016-06-01 15:43:03 -0700238 err = epoll_ctl(pi->epoll_fd, EPOLL_CTL_DEL, pi->fds[i]->fd, NULL);
Sree Kuchibhotla9442bab2016-05-20 17:54:06 -0700239 if (err < 0 && errno != ENOENT) {
240 gpr_log(GPR_ERROR,
241 "epoll_ctl delete for fds[i]: %d failed with error: %s", i,
242 pi->fds[i]->fd, strerror(errno));
Sree Kuchibhotla0bcbd792016-06-01 15:43:03 -0700243 /* TODO: sreek - We need a better way to bubble up this error instead of
244 * just logging a message */
Sree Kuchibhotla9442bab2016-05-20 17:54:06 -0700245 continue;
246 }
247 }
248
249 pi->fd_cnt = 0;
250}
251
Sree Kuchibhotla9442bab2016-05-20 17:54:06 -0700252/* The caller is expected to hold pi->mu lock before calling this function */
Sree Kuchibhotla0bcbd792016-06-01 15:43:03 -0700253static void polling_island_remove_fd_locked(polling_island *pi, grpc_fd *fd,
254 bool close_fd, bool remove_fd_ref) {
Sree Kuchibhotla9442bab2016-05-20 17:54:06 -0700255 int err;
256 size_t i;
Sree Kuchibhotla0bcbd792016-06-01 15:43:03 -0700257
258 /* Calling close() on the fd will automatically remove it from the epoll set.
259 If not calling close(), the fd must be explicitly removed from the epoll
260 set */
261 if (close_fd) {
262 close(fd->fd);
263 } else {
264 err = epoll_ctl(pi->epoll_fd, EPOLL_CTL_DEL, fd->fd, NULL);
265 if (err < 0 && errno != ENOENT) {
266 gpr_log(GPR_ERROR, "epoll_ctl delete for fd: %d failed with error; %s",
267 fd->fd, strerror(errno));
268 }
Sree Kuchibhotla9442bab2016-05-20 17:54:06 -0700269 }
270
271 for (i = 0; i < pi->fd_cnt; i++) {
272 if (pi->fds[i] == fd) {
273 pi->fds[i] = pi->fds[--pi->fd_cnt];
Sree Kuchibhotla0bcbd792016-06-01 15:43:03 -0700274 if (remove_fd_ref) {
275 GRPC_FD_UNREF(fd, "polling_island");
276 }
Sree Kuchibhotla9442bab2016-05-20 17:54:06 -0700277 break;
278 }
279 }
280}
281
282static polling_island *polling_island_create(grpc_fd *initial_fd,
283 int initial_ref_cnt) {
Sree Kuchibhotlaf448c342016-05-19 10:51:24 -0700284 polling_island *pi = NULL;
Sree Kuchibhotla0bcbd792016-06-01 15:43:03 -0700285 struct epoll_event ev;
286 int err;
287
288 /* Try to get one from the polling island freelist */
Sree Kuchibhotlaf448c342016-05-19 10:51:24 -0700289 gpr_mu_lock(&g_pi_freelist_mu);
290 if (g_pi_freelist != NULL) {
291 pi = g_pi_freelist;
292 g_pi_freelist = g_pi_freelist->next_free;
293 pi->next_free = NULL;
294 }
295 gpr_mu_unlock(&g_pi_freelist_mu);
296
297 /* Create new polling island if we could not get one from the free list */
298 if (pi == NULL) {
299 pi = gpr_malloc(sizeof(*pi));
300 gpr_mu_init(&pi->mu);
301 pi->fd_cnt = 0;
302 pi->fd_capacity = 0;
303 pi->fds = NULL;
Sree Kuchibhotla0bcbd792016-06-01 15:43:03 -0700304 }
Sree Kuchibhotlaf448c342016-05-19 10:51:24 -0700305
Sree Kuchibhotla0bcbd792016-06-01 15:43:03 -0700306 pi->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
307 if (pi->epoll_fd < 0) {
308 gpr_log(GPR_ERROR, "epoll_create1() failed with error: %s",
309 strerror(errno));
310 }
311 GPR_ASSERT(pi->epoll_fd >= 0);
312
313 ev.events = (uint32_t)(EPOLLIN | EPOLLET);
314 ev.data.ptr = NULL;
315 err = epoll_ctl(pi->epoll_fd, EPOLL_CTL_ADD,
316 GRPC_WAKEUP_FD_GET_READ_FD(&grpc_global_wakeup_fd), &ev);
317 if (err < 0) {
318 gpr_log(GPR_ERROR,
319 "Failed to add grpc_global_wake_up_fd (%d) to the epoll set "
320 "(epoll_fd: %d) with error: %s",
321 GRPC_WAKEUP_FD_GET_READ_FD(&grpc_global_wakeup_fd), pi->epoll_fd,
322 strerror(errno));
Sree Kuchibhotlaf448c342016-05-19 10:51:24 -0700323 }
324
325 pi->ref_cnt = initial_ref_cnt;
326 pi->merged_to = NULL;
327 pi->next_free = NULL;
328
329 if (initial_fd != NULL) {
Sree Kuchibhotla0bcbd792016-06-01 15:43:03 -0700330 /* It is not really needed to get the pi->mu lock here. If this is a newly
331 created polling island (or one that we got from the freelist), no one
332 else would be holding a lock to it anyway */
333 gpr_mu_lock(&pi->mu);
334 polling_island_add_fds_locked(pi, &initial_fd, 1, true);
335 gpr_mu_unlock(&pi->mu);
Sree Kuchibhotlaf448c342016-05-19 10:51:24 -0700336 }
337
338 return pi;
339}
340
Sree Kuchibhotla9442bab2016-05-20 17:54:06 -0700341static void polling_island_delete(polling_island *pi) {
342 GPR_ASSERT(pi->ref_cnt == 0);
343 GPR_ASSERT(pi->fd_cnt == 0);
344
Sree Kuchibhotla0bcbd792016-06-01 15:43:03 -0700345 close(pi->epoll_fd);
346 pi->epoll_fd = -1;
347
Sree Kuchibhotla9442bab2016-05-20 17:54:06 -0700348 pi->merged_to = NULL;
349
350 gpr_mu_lock(&g_pi_freelist_mu);
351 pi->next_free = g_pi_freelist;
352 g_pi_freelist = pi;
353 gpr_mu_unlock(&g_pi_freelist_mu);
354}
355
356void polling_island_unref_and_unlock(polling_island *pi, int unref_by) {
357 pi->ref_cnt -= unref_by;
358 int ref_cnt = pi->ref_cnt;
359 GPR_ASSERT(ref_cnt >= 0);
360
361 gpr_mu_unlock(&pi->mu);
362
363 if (ref_cnt == 0) {
364 polling_island_delete(pi);
365 }
366}
367
368polling_island *polling_island_update_and_lock(polling_island *pi, int unref_by,
369 int add_ref_by) {
370 polling_island *next = NULL;
371 gpr_mu_lock(&pi->mu);
372 while (pi->merged_to != NULL) {
373 next = pi->merged_to;
374 polling_island_unref_and_unlock(pi, unref_by);
375 pi = next;
376 gpr_mu_lock(&pi->mu);
377 }
378
379 pi->ref_cnt += add_ref_by;
380 return pi;
381}
382
383void polling_island_pair_update_and_lock(polling_island **p,
384 polling_island **q) {
385 polling_island *pi_1 = *p;
386 polling_island *pi_2 = *q;
387 polling_island *temp = NULL;
388 bool pi_1_locked = false;
389 bool pi_2_locked = false;
390 int num_swaps = 0;
391
Sree Kuchibhotla0bcbd792016-06-01 15:43:03 -0700392 /* Loop until either pi_1 == pi_2 or until we acquired locks on both pi_1
393 and pi_2 */
Sree Kuchibhotla9442bab2016-05-20 17:54:06 -0700394 while (pi_1 != pi_2 && !(pi_1_locked && pi_2_locked)) {
Sree Kuchibhotla0bcbd792016-06-01 15:43:03 -0700395 /* The following assertions are true at this point:
396 - pi_1 != pi_2 (else, the while loop would have exited)
397 - pi_1 MAY be locked
398 - pi_2 is NOT locked */
Sree Kuchibhotla9442bab2016-05-20 17:54:06 -0700399
Sree Kuchibhotla0bcbd792016-06-01 15:43:03 -0700400 /* To maintain lock order consistency, always lock polling_island node with
401 lower address first.
402 First, make sure pi_1 < pi_2 before proceeding any further. If it turns
403 out that pi_1 > pi_2, unlock pi_1 if locked (because pi_2 is not locked
404 at this point and having pi_1 locked would violate the lock order) and
405 swap pi_1 and pi_2 so that pi_1 becomes less than pi_2 */
Sree Kuchibhotla9442bab2016-05-20 17:54:06 -0700406 if (pi_1 > pi_2) {
407 if (pi_1_locked) {
408 gpr_mu_unlock(&pi_1->mu);
409 pi_1_locked = false;
410 }
411
412 GPR_SWAP(polling_island *, pi_1, pi_2);
413 num_swaps++;
414 }
415
Sree Kuchibhotla0bcbd792016-06-01 15:43:03 -0700416 /* The following assertions are true at this point:
417 - pi_1 != pi_2
418 - pi_1 < pi_2 (address of pi_1 is less than that of pi_2)
419 - pi_1 MAYBE locked
420 - pi_2 is NOT locked */
Sree Kuchibhotla9442bab2016-05-20 17:54:06 -0700421
Sree Kuchibhotla0bcbd792016-06-01 15:43:03 -0700422 /* Lock pi_1 (if pi_1 is pointing to the terminal node in the list) */
Sree Kuchibhotla9442bab2016-05-20 17:54:06 -0700423 if (!pi_1_locked) {
424 gpr_mu_lock(&pi_1->mu);
425 pi_1_locked = true;
426
Sree Kuchibhotla0bcbd792016-06-01 15:43:03 -0700427 /* If pi_1 is not terminal node (i.e pi_1->merged_to != NULL), we are not
428 done locking this polling_island yet. Release the lock on this node and
429 advance pi_1 to the next node in the list; and go to the beginning of
430 the loop (we can't proceed to locking pi_2 unless we locked pi_1 first)
431 */
Sree Kuchibhotla9442bab2016-05-20 17:54:06 -0700432 if (pi_1->merged_to != NULL) {
433 temp = pi_1->merged_to;
434 polling_island_unref_and_unlock(pi_1, 1);
435 pi_1 = temp;
436 pi_1_locked = false;
437
438 continue;
439 }
440 }
441
Sree Kuchibhotla0bcbd792016-06-01 15:43:03 -0700442 /* The following assertions are true at this point:
443 - pi_1 is locked
444 - pi_2 is unlocked
445 - pi_1 != pi_2 */
Sree Kuchibhotla9442bab2016-05-20 17:54:06 -0700446
447 gpr_mu_lock(&pi_2->mu);
448 pi_2_locked = true;
449
Sree Kuchibhotla0bcbd792016-06-01 15:43:03 -0700450 /* If pi_2 is not terminal node, we are not done locking this polling_island
451 yet. Release the lock and update pi_2 to the next node in the list */
Sree Kuchibhotla9442bab2016-05-20 17:54:06 -0700452 if (pi_2->merged_to != NULL) {
453 temp = pi_2->merged_to;
454 polling_island_unref_and_unlock(pi_2, 1);
455 pi_2 = temp;
456 pi_2_locked = false;
457 }
458 }
459
Sree Kuchibhotla0bcbd792016-06-01 15:43:03 -0700460 /* At this point, either pi_1 == pi_2 AND/OR we got both locks */
Sree Kuchibhotla9442bab2016-05-20 17:54:06 -0700461 if (pi_1 == pi_2) {
Sree Kuchibhotla0bcbd792016-06-01 15:43:03 -0700462 /* We may or may not have gotten the lock. If we didn't, walk the rest of
463 the polling_island list and get the lock */
Sree Kuchibhotla9442bab2016-05-20 17:54:06 -0700464 GPR_ASSERT(pi_1_locked || (!pi_1_locked && !pi_2_locked));
465 if (!pi_1_locked) {
466 pi_1 = pi_2 = polling_island_update_and_lock(pi_1, 2, 0);
467 }
468 } else {
469 GPR_ASSERT(pi_1_locked && pi_2_locked);
Sree Kuchibhotla0bcbd792016-06-01 15:43:03 -0700470 /* If we swapped pi_1 and pi_2 odd number of times, do one more swap so that
471 pi_1 and pi_2 point to the same polling_island lists they started off
472 with at the beginning of this function (i.e *p and *q respectively) */
Sree Kuchibhotla9442bab2016-05-20 17:54:06 -0700473 if (num_swaps % 2 > 0) {
474 GPR_SWAP(polling_island *, pi_1, pi_2);
475 }
476 }
477
478 *p = pi_1;
479 *q = pi_2;
480}
481
482polling_island *polling_island_merge(polling_island *p, polling_island *q) {
Sree Kuchibhotla0bcbd792016-06-01 15:43:03 -0700483 /* Get locks on both the polling islands */
Sree Kuchibhotla9442bab2016-05-20 17:54:06 -0700484 polling_island_pair_update_and_lock(&p, &q);
485
486 /* TODO: sreek: Think about this scenario some more. Is it possible ?. what
487 * does it mean, when would this happen */
488 if (p == q) {
Sree Kuchibhotla0bcbd792016-06-01 15:43:03 -0700489 /* Nothing needs to be done here */
490 gpr_mu_unlock(&p->mu);
491 return p;
Sree Kuchibhotla9442bab2016-05-20 17:54:06 -0700492 }
493
Sree Kuchibhotla0bcbd792016-06-01 15:43:03 -0700494 /* Make sure that p points to the polling island with fewer fds than q */
495 if (p->fd_cnt > q->fd_cnt) {
496 GPR_SWAP(polling_island *, p, q);
497 }
Sree Kuchibhotla9442bab2016-05-20 17:54:06 -0700498
Sree Kuchibhotla0bcbd792016-06-01 15:43:03 -0700499 /* "Merge" p with q i.e move all the fds from p (the polling_island with fewer
500 fds) to q.
501 Note: Not altering the ref counts on the affected fds here because they
502 would effectively remain unchanged */
503 polling_island_add_fds_locked(q, p->fds, p->fd_cnt, false);
504 polling_island_remove_all_fds_locked(p, false);
505
506 /* The merged polling island inherits all the ref counts of the island merging
507 with it */
Sree Kuchibhotla9442bab2016-05-20 17:54:06 -0700508 q->ref_cnt += p->ref_cnt;
509
510 gpr_mu_unlock(&p->mu);
511 gpr_mu_unlock(&q->mu);
512
Sree Kuchibhotla0bcbd792016-06-01 15:43:03 -0700513 return q;
Sree Kuchibhotla9442bab2016-05-20 17:54:06 -0700514}
515
Sree Kuchibhotlaf448c342016-05-19 10:51:24 -0700516static void polling_island_global_init() {
Sree Kuchibhotlaf448c342016-05-19 10:51:24 -0700517 gpr_mu_init(&g_pi_freelist_mu);
518 g_pi_freelist = NULL;
519}
520
521/*******************************************************************************
Sree Kuchibhotla0bcbd792016-06-01 15:43:03 -0700522 * Fd Definitions
Sree Kuchibhotlaf448c342016-05-19 10:51:24 -0700523 */
524
Sree Kuchibhotla0bcbd792016-06-01 15:43:03 -0700525/* We need to keep a freelist not because of any concerns of malloc performance
Sree Kuchibhotlaf448c342016-05-19 10:51:24 -0700526 * but instead so that implementations with multiple threads in (for example)
527 * epoll_wait deal with the race between pollset removal and incoming poll
528 * notifications.
529 *
530 * The problem is that the poller ultimately holds a reference to this
531 * object, so it is very difficult to know when is safe to free it, at least
532 * without some expensive synchronization.
533 *
534 * If we keep the object freelisted, in the worst case losing this race just
535 * becomes a spurious read notification on a reused fd.
536 */
Sree Kuchibhotla0bcbd792016-06-01 15:43:03 -0700537
538/* The alarm system needs to be able to wakeup 'some poller' sometimes
539 * (specifically when a new alarm needs to be triggered earlier than the next
540 * alarm 'epoch'). This wakeup_fd gives us something to alert on when such a
541 * case occurs. */
542/* TODO: sreek: Right now, this wakes up all pollers */
543grpc_wakeup_fd grpc_global_wakeup_fd;
544
Sree Kuchibhotlaf448c342016-05-19 10:51:24 -0700545static grpc_fd *fd_freelist = NULL;
546static gpr_mu fd_freelist_mu;
547
Sree Kuchibhotlaf448c342016-05-19 10:51:24 -0700548#ifdef GRPC_FD_REF_COUNT_DEBUG
549#define REF_BY(fd, n, reason) ref_by(fd, n, reason, __FILE__, __LINE__)
550#define UNREF_BY(fd, n, reason) unref_by(fd, n, reason, __FILE__, __LINE__)
551static void ref_by(grpc_fd *fd, int n, const char *reason, const char *file,
552 int line) {
553 gpr_log(GPR_DEBUG, "FD %d %p ref %d %d -> %d [%s; %s:%d]", fd->fd, fd, n,
554 gpr_atm_no_barrier_load(&fd->refst),
555 gpr_atm_no_barrier_load(&fd->refst) + n, reason, file, line);
556#else
557#define REF_BY(fd, n, reason) ref_by(fd, n)
558#define UNREF_BY(fd, n, reason) unref_by(fd, n)
559static void ref_by(grpc_fd *fd, int n) {
560#endif
561 GPR_ASSERT(gpr_atm_no_barrier_fetch_add(&fd->refst, n) > 0);
562}
563
564#ifdef GRPC_FD_REF_COUNT_DEBUG
565static void unref_by(grpc_fd *fd, int n, const char *reason, const char *file,
566 int line) {
567 gpr_atm old;
568 gpr_log(GPR_DEBUG, "FD %d %p unref %d %d -> %d [%s; %s:%d]", fd->fd, fd, n,
569 gpr_atm_no_barrier_load(&fd->refst),
570 gpr_atm_no_barrier_load(&fd->refst) - n, reason, file, line);
571#else
572static void unref_by(grpc_fd *fd, int n) {
573 gpr_atm old;
574#endif
575 old = gpr_atm_full_fetch_add(&fd->refst, -n);
576 if (old == n) {
Sree Kuchibhotla0bcbd792016-06-01 15:43:03 -0700577 /* Add the fd to the freelist */
578 gpr_mu_lock(&fd_freelist_mu);
579 fd->freelist_next = fd_freelist;
580 fd_freelist = fd;
581 grpc_iomgr_unregister_object(&fd->iomgr_object);
582 gpr_mu_unlock(&fd_freelist_mu);
Sree Kuchibhotlaf448c342016-05-19 10:51:24 -0700583 } else {
584 GPR_ASSERT(old > n);
585 }
586}
587
Sree Kuchibhotla0bcbd792016-06-01 15:43:03 -0700588/* Increment refcount by two to avoid changing the orphan bit */
Sree Kuchibhotlaf448c342016-05-19 10:51:24 -0700589#ifdef GRPC_FD_REF_COUNT_DEBUG
590static void fd_ref(grpc_fd *fd, const char *reason, const char *file,
591 int line) {
592 ref_by(fd, 2, reason, file, line);
593}
594
595static void fd_unref(grpc_fd *fd, const char *reason, const char *file,
596 int line) {
597 unref_by(fd, 2, reason, file, line);
598}
599#else
600static void fd_ref(grpc_fd *fd) { ref_by(fd, 2); }
Sree Kuchibhotlaf448c342016-05-19 10:51:24 -0700601static void fd_unref(grpc_fd *fd) { unref_by(fd, 2); }
602#endif
603
Sree Kuchibhotla0bcbd792016-06-01 15:43:03 -0700604static void fd_global_init(void) { gpr_mu_init(&fd_freelist_mu); }
605
606static void fd_global_shutdown(void) {
607 gpr_mu_lock(&fd_freelist_mu);
608 gpr_mu_unlock(&fd_freelist_mu);
609 while (fd_freelist != NULL) {
610 grpc_fd *fd = fd_freelist;
611 fd_freelist = fd_freelist->freelist_next;
612 gpr_mu_destroy(&fd->mu);
613 gpr_free(fd);
614 }
615 gpr_mu_destroy(&fd_freelist_mu);
616}
617
618static grpc_fd *fd_create(int fd, const char *name) {
619 grpc_fd *new_fd = NULL;
620
621 gpr_mu_lock(&fd_freelist_mu);
622 if (fd_freelist != NULL) {
623 new_fd = fd_freelist;
624 fd_freelist = fd_freelist->freelist_next;
625 }
626 gpr_mu_unlock(&fd_freelist_mu);
627
628 if (new_fd == NULL) {
629 new_fd = gpr_malloc(sizeof(grpc_fd));
630 gpr_mu_init(&new_fd->mu);
631 gpr_mu_init(&new_fd->pi_mu);
632 }
633
634 /* Note: It is not really needed to get the new_fd->mu lock here. If this is a
635 newly created fd (or an fd we got from the freelist), no one else would be
636 holding a lock to it anyway. */
637 gpr_mu_lock(&new_fd->mu);
638
639 gpr_atm_rel_store(&new_fd->refst, 1);
640 new_fd->shutdown = false;
641 new_fd->read_closure = CLOSURE_NOT_READY;
642 new_fd->write_closure = CLOSURE_NOT_READY;
643 new_fd->fd = fd;
644 new_fd->polling_island = NULL;
645 new_fd->freelist_next = NULL;
646 new_fd->on_done_closure = NULL;
647 new_fd->closed = 0;
648 new_fd->released = false;
649
650 gpr_mu_unlock(&new_fd->mu);
651
652 char *fd_name;
653 gpr_asprintf(&fd_name, "%s fd=%d", name, fd);
654 grpc_iomgr_register_object(&new_fd->iomgr_object, fd_name);
655 gpr_free(fd_name);
656#ifdef GRPC_FD_REF_COUNT_DEBUG
657 gpr_log(GPR_DEBUG, "FD %d %p create %s", fd, r, fd_name);
658#endif
659 return new_fd;
660}
661
662static bool fd_is_orphaned(grpc_fd *fd) {
663 return (gpr_atm_acq_load(&fd->refst) & 1) == 0;
664}
665
666static int fd_wrapped_fd(grpc_fd *fd) {
667 int ret_fd = -1;
668 gpr_mu_lock(&fd->mu);
669 if (!fd->released && !fd->closed) {
670 ret_fd = fd->fd;
671 }
672 gpr_mu_unlock(&fd->mu);
673
674 return ret_fd;
675}
676
677static void fd_orphan(grpc_exec_ctx *exec_ctx, grpc_fd *fd,
678 grpc_closure *on_done, int *release_fd,
679 const char *reason) {
680 /* TODO(sreek) In ev_poll_posix.c,the lock is acquired a little later. Why? */
681 gpr_mu_lock(&fd->mu);
682 fd->on_done_closure = on_done;
683
684 /* If release_fd is not NULL, we should be relinquishing control of the file
685 descriptor fd->fd (but we still own the grpc_fd structure). */
686 fd->released = release_fd != NULL;
687 if (!fd->released) {
688 shutdown(fd->fd, SHUT_RDWR);
689 } else {
690 *release_fd = fd->fd;
691 }
692
693 REF_BY(fd, 1, reason); /* Remove active status, but keep referenced */
694 fd->closed = 1;
695
696 /* Remove the fd from the polling island:
697 - Update the fd->polling_island to point to the latest polling island
698 - Remove the fd from the polling island. Also, call close() on the file
699 descriptor fd->fd ONLY if we haven't relinquised control (i.e
700 fd->released is 'false')
701 - Decrement the ref count on the polling island and det fd->polling_island
702 to NULL */
703 gpr_mu_lock(&fd->pi_mu);
704
705 fd->polling_island = polling_island_update_and_lock(fd->polling_island, 1, 0);
706 polling_island_remove_fd_locked(fd->polling_island, fd, !fd->released, true);
707 polling_island_unref_and_unlock(fd->polling_island, 1);
708 fd->polling_island = NULL;
709
710 gpr_mu_unlock(&fd->pi_mu);
711
712 grpc_exec_ctx_enqueue(exec_ctx, fd->on_done_closure, true, NULL);
713
714 gpr_mu_unlock(&fd->mu);
715 UNREF_BY(fd, 2, reason); /* Drop the reference */
716}
717
Sree Kuchibhotlaf448c342016-05-19 10:51:24 -0700718static void notify_on_locked(grpc_exec_ctx *exec_ctx, grpc_fd *fd,
719 grpc_closure **st, grpc_closure *closure) {
720 if (*st == CLOSURE_NOT_READY) {
721 /* not ready ==> switch to a waiting state by setting the closure */
722 *st = closure;
723 } else if (*st == CLOSURE_READY) {
724 /* already ready ==> queue the closure to run immediately */
725 *st = CLOSURE_NOT_READY;
726 grpc_exec_ctx_enqueue(exec_ctx, closure, !fd->shutdown, NULL);
727 } else {
728 /* upcallptr was set to a different closure. This is an error! */
729 gpr_log(GPR_ERROR,
730 "User called a notify_on function with a previous callback still "
731 "pending");
732 abort();
733 }
734}
735
736/* returns 1 if state becomes not ready */
737static int set_ready_locked(grpc_exec_ctx *exec_ctx, grpc_fd *fd,
738 grpc_closure **st) {
739 if (*st == CLOSURE_READY) {
740 /* duplicate ready ==> ignore */
741 return 0;
742 } else if (*st == CLOSURE_NOT_READY) {
743 /* not ready, and not waiting ==> flag ready */
744 *st = CLOSURE_READY;
745 return 0;
746 } else {
747 /* waiting ==> queue closure */
748 grpc_exec_ctx_enqueue(exec_ctx, *st, !fd->shutdown, NULL);
749 *st = CLOSURE_NOT_READY;
750 return 1;
751 }
752}
753
Sree Kuchibhotlaf448c342016-05-19 10:51:24 -0700754static void fd_shutdown(grpc_exec_ctx *exec_ctx, grpc_fd *fd) {
755 gpr_mu_lock(&fd->mu);
756 GPR_ASSERT(!fd->shutdown);
Sree Kuchibhotla0bcbd792016-06-01 15:43:03 -0700757 fd->shutdown = true;
758
759 /* Flush any pending read and write closures. Since fd->shutdown is 'true' at
760 this point, the closures would be called with 'success = false' */
Sree Kuchibhotlaf448c342016-05-19 10:51:24 -0700761 set_ready_locked(exec_ctx, fd, &fd->read_closure);
762 set_ready_locked(exec_ctx, fd, &fd->write_closure);
763 gpr_mu_unlock(&fd->mu);
764}
765
766static void fd_notify_on_read(grpc_exec_ctx *exec_ctx, grpc_fd *fd,
767 grpc_closure *closure) {
768 gpr_mu_lock(&fd->mu);
769 notify_on_locked(exec_ctx, fd, &fd->read_closure, closure);
770 gpr_mu_unlock(&fd->mu);
771}
772
773static void fd_notify_on_write(grpc_exec_ctx *exec_ctx, grpc_fd *fd,
774 grpc_closure *closure) {
775 gpr_mu_lock(&fd->mu);
776 notify_on_locked(exec_ctx, fd, &fd->write_closure, closure);
777 gpr_mu_unlock(&fd->mu);
778}
779
780/*******************************************************************************
Sree Kuchibhotla0bcbd792016-06-01 15:43:03 -0700781 * Pollset Definitions
Sree Kuchibhotlaf448c342016-05-19 10:51:24 -0700782 */
783
Sree Kuchibhotla0bcbd792016-06-01 15:43:03 -0700784static void sig_handler(int sig_num) {
785 /* TODO: sreek - Remove this expensive log line */
786 gpr_log(GPR_INFO, "Received signal %d", sig_num);
787}
Sree Kuchibhotlaf448c342016-05-19 10:51:24 -0700788
Sree Kuchibhotla0bcbd792016-06-01 15:43:03 -0700789/* Global state management */
790static void pollset_global_init(void) {
791 gpr_tls_init(&g_current_thread_poller);
792 gpr_tls_init(&g_current_thread_worker);
793 grpc_wakeup_fd_init(&grpc_global_wakeup_fd);
794 signal(SIGUSR1, sig_handler);
795}
796
797static void pollset_global_shutdown(void) {
798 grpc_wakeup_fd_destroy(&grpc_global_wakeup_fd);
799 gpr_tls_destroy(&g_current_thread_poller);
800 gpr_tls_destroy(&g_current_thread_worker);
801}
802
803/* Return 1 if the pollset has active threads in pollset_work (pollset must
804 * be locked) */
805static int pollset_has_workers(grpc_pollset *p) {
806 return p->root_worker.next != &p->root_worker;
807}
Sree Kuchibhotlaf448c342016-05-19 10:51:24 -0700808
809static void remove_worker(grpc_pollset *p, grpc_pollset_worker *worker) {
810 worker->prev->next = worker->next;
811 worker->next->prev = worker->prev;
812}
813
Sree Kuchibhotlaf448c342016-05-19 10:51:24 -0700814static grpc_pollset_worker *pop_front_worker(grpc_pollset *p) {
815 if (pollset_has_workers(p)) {
816 grpc_pollset_worker *w = p->root_worker.next;
817 remove_worker(p, w);
818 return w;
819 } else {
820 return NULL;
821 }
822}
823
824static void push_back_worker(grpc_pollset *p, grpc_pollset_worker *worker) {
825 worker->next = &p->root_worker;
826 worker->prev = worker->next->prev;
827 worker->prev->next = worker->next->prev = worker;
828}
829
830static void push_front_worker(grpc_pollset *p, grpc_pollset_worker *worker) {
831 worker->prev = &p->root_worker;
832 worker->next = worker->prev->next;
833 worker->prev->next = worker->next->prev = worker;
834}
835
Sree Kuchibhotla0bcbd792016-06-01 15:43:03 -0700836/* p->mu must be held before calling this function */
837static void pollset_kick(grpc_pollset *p,
838 grpc_pollset_worker *specific_worker) {
839 GPR_TIMER_BEGIN("pollset_kick", 0);
Sree Kuchibhotlaf448c342016-05-19 10:51:24 -0700840
Sree Kuchibhotla0bcbd792016-06-01 15:43:03 -0700841 grpc_pollset_worker *worker = specific_worker;
842 if (worker != NULL) {
843 if (worker == GRPC_POLLSET_KICK_BROADCAST) {
844 GPR_TIMER_BEGIN("pollset_kick.broadcast", 0);
845 if (pollset_has_workers(p)) {
846 for (worker = p->root_worker.next; worker != &p->root_worker;
847 worker = worker->next) {
848 pthread_kill(worker->pt_id, SIGUSR1);
Sree Kuchibhotlaf448c342016-05-19 10:51:24 -0700849 }
Sree Kuchibhotla0bcbd792016-06-01 15:43:03 -0700850 } else {
851 p->kicked_without_pollers = true;
Sree Kuchibhotlaf448c342016-05-19 10:51:24 -0700852 }
Sree Kuchibhotla0bcbd792016-06-01 15:43:03 -0700853 GPR_TIMER_END("pollset_kick.broadcast", 0);
854 } else {
855 GPR_TIMER_MARK("kicked_specifically", 0);
856 worker->kicked_specifically = true;
857 pthread_kill(worker->pt_id, SIGUSR1);
858 }
859 } else {
860 GPR_TIMER_MARK("kick_anonymous", 0);
861 worker = pop_front_worker(p);
862 if (worker != NULL) {
863 GPR_TIMER_MARK("finally_kick", 0);
864 push_back_worker(p, worker);
865 pthread_kill(worker->pt_id, SIGUSR1);
Sree Kuchibhotlaf448c342016-05-19 10:51:24 -0700866 } else {
867 GPR_TIMER_MARK("kicked_no_pollers", 0);
Sree Kuchibhotla0bcbd792016-06-01 15:43:03 -0700868 p->kicked_without_pollers = true;
Sree Kuchibhotlaf448c342016-05-19 10:51:24 -0700869 }
870 }
871
Sree Kuchibhotla0bcbd792016-06-01 15:43:03 -0700872 GPR_TIMER_END("pollset_kick", 0);
Sree Kuchibhotlaf448c342016-05-19 10:51:24 -0700873}
874
875static void kick_poller(void) { grpc_wakeup_fd_wakeup(&grpc_global_wakeup_fd); }
876
Sree Kuchibhotlaf448c342016-05-19 10:51:24 -0700877static void pollset_init(grpc_pollset *pollset, gpr_mu **mu) {
878 gpr_mu_init(&pollset->mu);
879 *mu = &pollset->mu;
Sree Kuchibhotla0bcbd792016-06-01 15:43:03 -0700880
Sree Kuchibhotlaf448c342016-05-19 10:51:24 -0700881 pollset->root_worker.next = pollset->root_worker.prev = &pollset->root_worker;
Sree Kuchibhotla0bcbd792016-06-01 15:43:03 -0700882 pollset->kicked_without_pollers = false;
883
884 pollset->shutting_down = false;
885 pollset->finish_shutdown_called = false;
886 pollset->shutdown_done = NULL;
887
Sree Kuchibhotlaf448c342016-05-19 10:51:24 -0700888 gpr_mu_init(&pollset->pi_mu);
889 pollset->polling_island = NULL;
Sree Kuchibhotlaf448c342016-05-19 10:51:24 -0700890}
891
Sree Kuchibhotla0bcbd792016-06-01 15:43:03 -0700892/* Convert a timespec to milliseconds:
893 - Very small or negative poll times are clamped to zero to do a non-blocking
894 poll (which becomes spin polling)
895 - Other small values are rounded up to one millisecond
896 - Longer than a millisecond polls are rounded up to the next nearest
897 millisecond to avoid spinning
898 - Infinite timeouts are converted to -1 */
Sree Kuchibhotlaf448c342016-05-19 10:51:24 -0700899static int poll_deadline_to_millis_timeout(gpr_timespec deadline,
900 gpr_timespec now) {
901 gpr_timespec timeout;
902 static const int64_t max_spin_polling_us = 10;
903 if (gpr_time_cmp(deadline, gpr_inf_future(deadline.clock_type)) == 0) {
904 return -1;
905 }
Sree Kuchibhotla0bcbd792016-06-01 15:43:03 -0700906
Sree Kuchibhotlaf448c342016-05-19 10:51:24 -0700907 if (gpr_time_cmp(deadline, gpr_time_add(now, gpr_time_from_micros(
908 max_spin_polling_us,
909 GPR_TIMESPAN))) <= 0) {
910 return 0;
911 }
912 timeout = gpr_time_sub(deadline, now);
913 return gpr_time_to_millis(gpr_time_add(
914 timeout, gpr_time_from_nanos(GPR_NS_PER_MS - 1, GPR_TIMESPAN)));
915}
916
Sree Kuchibhotlaf448c342016-05-19 10:51:24 -0700917static void set_ready(grpc_exec_ctx *exec_ctx, grpc_fd *fd, grpc_closure **st) {
918 /* only one set_ready can be active at once (but there may be a racing
919 notify_on) */
920 gpr_mu_lock(&fd->mu);
921 set_ready_locked(exec_ctx, fd, st);
922 gpr_mu_unlock(&fd->mu);
923}
924
925static void fd_become_readable(grpc_exec_ctx *exec_ctx, grpc_fd *fd) {
926 set_ready(exec_ctx, fd, &fd->read_closure);
927}
928
929static void fd_become_writable(grpc_exec_ctx *exec_ctx, grpc_fd *fd) {
930 set_ready(exec_ctx, fd, &fd->write_closure);
931}
932
Sree Kuchibhotla0bcbd792016-06-01 15:43:03 -0700933/* TODO(klempner): We probably want to turn this down a bit */
934#define GRPC_EPOLL_MAX_EVENTS 1000
935static void pollset_work_and_unlock(grpc_exec_ctx *exec_ctx,
936 grpc_pollset *pollset, int timeout_ms,
937 sigset_t *sig_mask) {
938 struct epoll_event ep_ev[GRPC_EPOLL_MAX_EVENTS];
939 int epoll_fd;
940 int ep_rv;
941 GPR_TIMER_BEGIN("pollset_work_and_unlock", 0);
942
943 /* We need to get the epoll_fd to wait on. The epoll_fd is in inside the
944 polling island pointed by pollset->polling_island.
945 Acquire the following locks:
946 - pollset->mu (which we already have)
947 - pollset->pi_mu
948 - pollset->polling_island->mu */
949 gpr_mu_lock(&pollset->pi_mu);
950 pollset->polling_island =
951 polling_island_update_and_lock(pollset->polling_island, 1, 0);
952
953 epoll_fd = pollset->polling_island->epoll_fd;
954
955 /* Release the locks */
956 polling_island_unref_and_unlock(pollset->polling_island, 0); /* Keep the ref*/
957 gpr_mu_unlock(&pollset->pi_mu);
958 gpr_mu_unlock(&pollset->mu);
959
960 do {
961 ep_rv = epoll_pwait(epoll_fd, ep_ev, GRPC_EPOLL_MAX_EVENTS, timeout_ms,
962 sig_mask);
963
964 if (ep_rv < 0) {
965 if (errno != EINTR) {
966 /* TODO (sreek) - Check for bad file descriptor error */
967 gpr_log(GPR_ERROR, "epoll_pwait() failed: %s", strerror(errno));
968 }
969 } else {
970 int i;
971 for (i = 0; i < ep_rv; ++i) {
972 grpc_fd *fd = ep_ev[i].data.ptr;
973 int cancel = ep_ev[i].events & (EPOLLERR | EPOLLHUP);
974 int read_ev = ep_ev[i].events & (EPOLLIN | EPOLLPRI);
975 int write_ev = ep_ev[i].events & EPOLLOUT;
976 if (fd == NULL) {
977 grpc_wakeup_fd_consume_wakeup(&grpc_global_wakeup_fd);
978 } else {
979 if (read_ev || cancel) {
980 fd_become_readable(exec_ctx, fd);
981 }
982 if (write_ev || cancel) {
983 fd_become_writable(exec_ctx, fd);
984 }
985 }
986 }
987 }
988 } while (ep_rv == GRPC_EPOLL_MAX_EVENTS);
989
990 GPR_TIMER_END("pollset_work_and_unlock", 0);
991}
992
993/* Release the reference to pollset->polling_island and set it to NULL.
994 pollset->mu must be held */
995static void pollset_release_polling_island_locked(grpc_pollset *pollset) {
996 gpr_mu_lock(&pollset->pi_mu);
997 if (pollset->polling_island) {
998 pollset->polling_island =
999 polling_island_update_and_lock(pollset->polling_island, 1, 0);
1000 polling_island_unref_and_unlock(pollset->polling_island, 1);
1001 pollset->polling_island = NULL;
1002 }
1003 gpr_mu_unlock(&pollset->pi_mu);
1004}
1005
1006static void finish_shutdown_locked(grpc_exec_ctx *exec_ctx,
1007 grpc_pollset *pollset) {
1008 /* The pollset cannot have any workers if we are at this stage */
1009 GPR_ASSERT(!pollset_has_workers(pollset));
1010
1011 pollset->finish_shutdown_called = true;
1012 pollset_release_polling_island_locked(pollset);
1013
1014 grpc_exec_ctx_enqueue(exec_ctx, pollset->shutdown_done, true, NULL);
1015}
1016
1017/* pollset->mu lock must be held by the caller before calling this */
1018static void pollset_shutdown(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset,
1019 grpc_closure *closure) {
1020 GPR_TIMER_BEGIN("pollset_shutdown", 0);
1021 GPR_ASSERT(!pollset->shutting_down);
1022 pollset->shutting_down = true;
1023 pollset->shutdown_done = closure;
1024 pollset_kick(pollset, GRPC_POLLSET_KICK_BROADCAST);
1025
1026 /* If the pollset has any workers, we cannot call finish_shutdown_locked()
1027 because it would release the underlying polling island. In such a case, we
1028 let the last worker call finish_shutdown_locked() from pollset_work() */
1029 if (!pollset_has_workers(pollset)) {
1030 GPR_ASSERT(!pollset->finish_shutdown_called);
1031 GPR_TIMER_MARK("pollset_shutdown.finish_shutdown_locked", 0);
1032 finish_shutdown_locked(exec_ctx, pollset);
1033 }
1034 GPR_TIMER_END("pollset_shutdown", 0);
1035}
1036
1037/* TODO(sreek) Is pollset_shutdown() guranteed to be called before this? */
1038static void pollset_destroy(grpc_pollset *pollset) {
1039 GPR_ASSERT(!pollset_has_workers(pollset));
1040 gpr_mu_destroy(&pollset->pi_mu);
1041 gpr_mu_destroy(&pollset->mu);
1042}
1043
1044static void pollset_reset(grpc_pollset *pollset) {
1045 GPR_ASSERT(pollset->shutting_down);
1046 GPR_ASSERT(!pollset_has_workers(pollset));
1047 pollset->shutting_down = false;
1048 pollset->finish_shutdown_called = false;
1049 pollset->kicked_without_pollers = false;
1050 /* TODO(sreek) - Should pollset->shutdown closure be set to NULL here? */
1051 pollset_release_polling_island_locked(pollset);
1052}
1053
1054/* pollset->mu lock must be held by the caller before calling this.
1055 The function pollset_work() may temporarily release the lock (pollset->mu)
1056 during the course of its execution but it will always re-acquire the lock and
1057 ensure that it is held by the time the function returns */
1058static void pollset_work(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset,
1059 grpc_pollset_worker **worker_hdl, gpr_timespec now,
1060 gpr_timespec deadline) {
1061 GPR_TIMER_BEGIN("pollset_work", 0);
1062
1063 int timeout_ms = poll_deadline_to_millis_timeout(deadline, now);
1064
1065 sigset_t new_mask;
1066 sigset_t orig_mask;
1067
1068 grpc_pollset_worker worker;
1069 worker.next = worker.prev = NULL;
1070 worker.kicked_specifically = 0;
1071 worker.pt_id = pthread_self();
1072
1073 *worker_hdl = &worker;
1074
1075 if (pollset->kicked_without_pollers) {
1076 /* If the pollset was kicked without pollers, pretend that the current
1077 worker got the kick and skip polling. A kick indicates that there is some
1078 work that needs attention like an event on the completion queue or an
1079 alarm */
1080 GPR_TIMER_MARK("pollset_work.kicked_without_pollers", 0);
1081 pollset->kicked_without_pollers = 0;
1082 } else if (!pollset->shutting_down) {
1083 sigemptyset(&new_mask);
1084 sigaddset(&new_mask, SIGUSR1);
1085 pthread_sigmask(SIG_BLOCK, &new_mask, &orig_mask);
1086 sigdelset(&orig_mask, SIGUSR1);
1087
1088 push_front_worker(pollset, &worker);
1089
1090 pollset_work_and_unlock(exec_ctx, pollset, timeout_ms, &orig_mask);
1091 grpc_exec_ctx_flush(exec_ctx);
1092
1093 gpr_mu_lock(&pollset->mu);
1094 remove_worker(pollset, &worker);
1095 }
1096
1097 /* If we are the last worker on the pollset (i.e pollset_has_workers() is
1098 false at this point) and the pollset is shutting down, we may have to
1099 finish the shutdown process by calling finish_shutdown_locked().
1100 See pollset_shutdown() for more details.
1101
1102 Note: Continuing to access pollset here is safe; it is the caller's
1103 responsibility to not destroy a pollset when it has outstanding calls to
1104 pollset_work() */
1105 if (pollset->shutting_down && !pollset_has_workers(pollset) &&
1106 !pollset->finish_shutdown_called) {
1107 GPR_TIMER_MARK("pollset_work.finish_shutdown_locked", 0);
1108 finish_shutdown_locked(exec_ctx, pollset);
1109
1110 gpr_mu_unlock(&pollset->mu);
1111 grpc_exec_ctx_flush(exec_ctx);
1112 gpr_mu_lock(&pollset->mu);
1113 }
1114
1115 *worker_hdl = NULL;
1116 GPR_TIMER_END("pollset_work", 0);
1117}
1118
Sree Kuchibhotlaf448c342016-05-19 10:51:24 -07001119static void pollset_add_fd(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset,
1120 grpc_fd *fd) {
Sree Kuchibhotlaf448c342016-05-19 10:51:24 -07001121 /* TODO sreek - Check if we need to get a pollset->mu lock here */
Sree Kuchibhotla9442bab2016-05-20 17:54:06 -07001122 gpr_mu_lock(&pollset->pi_mu);
1123 gpr_mu_lock(&fd->pi_mu);
Sree Kuchibhotlaf448c342016-05-19 10:51:24 -07001124
Sree Kuchibhotla9442bab2016-05-20 17:54:06 -07001125 polling_island *pi_new = NULL;
Sree Kuchibhotlaf448c342016-05-19 10:51:24 -07001126
Sree Kuchibhotla0bcbd792016-06-01 15:43:03 -07001127 /* 1) If fd->polling_island and pollset->polling_island are both non-NULL and
1128 * equal, do nothing.
1129 * 2) If fd->polling_island and pollset->polling_island are both NULL, create
1130 * a new polling island (with a refcount of 2) and make the polling_island
1131 * fields in both fd and pollset to point to the new island
1132 * 3) If one of fd->polling_island or pollset->polling_island is NULL, update
1133 * the NULL polling_island field to point to the non-NULL polling_island
1134 * field (ensure that the refcount on the polling island is incremented by
1135 * 1 to account for the newly added reference)
1136 * 4) Finally, if fd->polling_island and pollset->polling_island are non-NULL
1137 * and different, merge both the polling islands and update the
1138 * polling_island fields in both fd and pollset to point to the merged
1139 * polling island.
1140 */
Sree Kuchibhotla9442bab2016-05-20 17:54:06 -07001141 if (fd->polling_island == pollset->polling_island) {
1142 pi_new = fd->polling_island;
1143 if (pi_new == NULL) {
1144 pi_new = polling_island_create(fd, 2);
Sree Kuchibhotlaf448c342016-05-19 10:51:24 -07001145 }
Sree Kuchibhotla9442bab2016-05-20 17:54:06 -07001146 } else if (fd->polling_island == NULL) {
1147 pi_new = polling_island_update_and_lock(pollset->polling_island, 1, 1);
Sree Kuchibhotla9442bab2016-05-20 17:54:06 -07001148 } else if (pollset->polling_island == NULL) {
1149 pi_new = polling_island_update_and_lock(fd->polling_island, 1, 1);
Sree Kuchibhotla5098f912016-05-31 10:58:17 -07001150 } else {
Sree Kuchibhotla9442bab2016-05-20 17:54:06 -07001151 pi_new = polling_island_merge(fd->polling_island, pollset->polling_island);
Sree Kuchibhotlaf448c342016-05-19 10:51:24 -07001152 }
1153
Sree Kuchibhotla9442bab2016-05-20 17:54:06 -07001154 fd->polling_island = pollset->polling_island = pi_new;
Sree Kuchibhotlaf448c342016-05-19 10:51:24 -07001155
Sree Kuchibhotla9442bab2016-05-20 17:54:06 -07001156 gpr_mu_unlock(&fd->pi_mu);
1157 gpr_mu_unlock(&pollset->pi_mu);
Sree Kuchibhotlaf448c342016-05-19 10:51:24 -07001158}
1159
Sree Kuchibhotlaf448c342016-05-19 10:51:24 -07001160/*******************************************************************************
Sree Kuchibhotla0bcbd792016-06-01 15:43:03 -07001161 * Pollset-set Definitions
Sree Kuchibhotlaf448c342016-05-19 10:51:24 -07001162 */
1163
1164static grpc_pollset_set *pollset_set_create(void) {
1165 grpc_pollset_set *pollset_set = gpr_malloc(sizeof(*pollset_set));
1166 memset(pollset_set, 0, sizeof(*pollset_set));
1167 gpr_mu_init(&pollset_set->mu);
1168 return pollset_set;
1169}
1170
1171static void pollset_set_destroy(grpc_pollset_set *pollset_set) {
1172 size_t i;
1173 gpr_mu_destroy(&pollset_set->mu);
1174 for (i = 0; i < pollset_set->fd_count; i++) {
1175 GRPC_FD_UNREF(pollset_set->fds[i], "pollset_set");
1176 }
1177 gpr_free(pollset_set->pollsets);
1178 gpr_free(pollset_set->pollset_sets);
1179 gpr_free(pollset_set->fds);
1180 gpr_free(pollset_set);
1181}
1182
Sree Kuchibhotla0bcbd792016-06-01 15:43:03 -07001183static void pollset_set_add_fd(grpc_exec_ctx *exec_ctx,
1184 grpc_pollset_set *pollset_set, grpc_fd *fd) {
1185 size_t i;
1186 gpr_mu_lock(&pollset_set->mu);
1187 if (pollset_set->fd_count == pollset_set->fd_capacity) {
1188 pollset_set->fd_capacity = GPR_MAX(8, 2 * pollset_set->fd_capacity);
1189 pollset_set->fds = gpr_realloc(
1190 pollset_set->fds, pollset_set->fd_capacity * sizeof(*pollset_set->fds));
1191 }
1192 GRPC_FD_REF(fd, "pollset_set");
1193 pollset_set->fds[pollset_set->fd_count++] = fd;
1194 for (i = 0; i < pollset_set->pollset_count; i++) {
1195 pollset_add_fd(exec_ctx, pollset_set->pollsets[i], fd);
1196 }
1197 for (i = 0; i < pollset_set->pollset_set_count; i++) {
1198 pollset_set_add_fd(exec_ctx, pollset_set->pollset_sets[i], fd);
1199 }
1200 gpr_mu_unlock(&pollset_set->mu);
1201}
1202
1203static void pollset_set_del_fd(grpc_exec_ctx *exec_ctx,
1204 grpc_pollset_set *pollset_set, grpc_fd *fd) {
1205 size_t i;
1206 gpr_mu_lock(&pollset_set->mu);
1207 for (i = 0; i < pollset_set->fd_count; i++) {
1208 if (pollset_set->fds[i] == fd) {
1209 pollset_set->fd_count--;
1210 GPR_SWAP(grpc_fd *, pollset_set->fds[i],
1211 pollset_set->fds[pollset_set->fd_count]);
1212 GRPC_FD_UNREF(fd, "pollset_set");
1213 break;
1214 }
1215 }
1216 for (i = 0; i < pollset_set->pollset_set_count; i++) {
1217 pollset_set_del_fd(exec_ctx, pollset_set->pollset_sets[i], fd);
1218 }
1219 gpr_mu_unlock(&pollset_set->mu);
1220}
1221
Sree Kuchibhotlaf448c342016-05-19 10:51:24 -07001222static void pollset_set_add_pollset(grpc_exec_ctx *exec_ctx,
1223 grpc_pollset_set *pollset_set,
1224 grpc_pollset *pollset) {
1225 size_t i, j;
1226 gpr_mu_lock(&pollset_set->mu);
1227 if (pollset_set->pollset_count == pollset_set->pollset_capacity) {
1228 pollset_set->pollset_capacity =
1229 GPR_MAX(8, 2 * pollset_set->pollset_capacity);
1230 pollset_set->pollsets =
1231 gpr_realloc(pollset_set->pollsets, pollset_set->pollset_capacity *
1232 sizeof(*pollset_set->pollsets));
1233 }
1234 pollset_set->pollsets[pollset_set->pollset_count++] = pollset;
1235 for (i = 0, j = 0; i < pollset_set->fd_count; i++) {
1236 if (fd_is_orphaned(pollset_set->fds[i])) {
1237 GRPC_FD_UNREF(pollset_set->fds[i], "pollset_set");
1238 } else {
1239 pollset_add_fd(exec_ctx, pollset, pollset_set->fds[i]);
1240 pollset_set->fds[j++] = pollset_set->fds[i];
1241 }
1242 }
1243 pollset_set->fd_count = j;
1244 gpr_mu_unlock(&pollset_set->mu);
1245}
1246
1247static void pollset_set_del_pollset(grpc_exec_ctx *exec_ctx,
1248 grpc_pollset_set *pollset_set,
1249 grpc_pollset *pollset) {
1250 size_t i;
1251 gpr_mu_lock(&pollset_set->mu);
1252 for (i = 0; i < pollset_set->pollset_count; i++) {
1253 if (pollset_set->pollsets[i] == pollset) {
1254 pollset_set->pollset_count--;
1255 GPR_SWAP(grpc_pollset *, pollset_set->pollsets[i],
1256 pollset_set->pollsets[pollset_set->pollset_count]);
1257 break;
1258 }
1259 }
1260 gpr_mu_unlock(&pollset_set->mu);
1261}
1262
1263static void pollset_set_add_pollset_set(grpc_exec_ctx *exec_ctx,
1264 grpc_pollset_set *bag,
1265 grpc_pollset_set *item) {
1266 size_t i, j;
1267 gpr_mu_lock(&bag->mu);
1268 if (bag->pollset_set_count == bag->pollset_set_capacity) {
1269 bag->pollset_set_capacity = GPR_MAX(8, 2 * bag->pollset_set_capacity);
1270 bag->pollset_sets =
1271 gpr_realloc(bag->pollset_sets,
1272 bag->pollset_set_capacity * sizeof(*bag->pollset_sets));
1273 }
1274 bag->pollset_sets[bag->pollset_set_count++] = item;
1275 for (i = 0, j = 0; i < bag->fd_count; i++) {
1276 if (fd_is_orphaned(bag->fds[i])) {
1277 GRPC_FD_UNREF(bag->fds[i], "pollset_set");
1278 } else {
1279 pollset_set_add_fd(exec_ctx, item, bag->fds[i]);
1280 bag->fds[j++] = bag->fds[i];
1281 }
1282 }
1283 bag->fd_count = j;
1284 gpr_mu_unlock(&bag->mu);
1285}
1286
1287static void pollset_set_del_pollset_set(grpc_exec_ctx *exec_ctx,
1288 grpc_pollset_set *bag,
1289 grpc_pollset_set *item) {
1290 size_t i;
1291 gpr_mu_lock(&bag->mu);
1292 for (i = 0; i < bag->pollset_set_count; i++) {
1293 if (bag->pollset_sets[i] == item) {
1294 bag->pollset_set_count--;
1295 GPR_SWAP(grpc_pollset_set *, bag->pollset_sets[i],
1296 bag->pollset_sets[bag->pollset_set_count]);
1297 break;
1298 }
1299 }
1300 gpr_mu_unlock(&bag->mu);
1301}
1302
Sree Kuchibhotlaf448c342016-05-19 10:51:24 -07001303/*******************************************************************************
Sree Kuchibhotla0bcbd792016-06-01 15:43:03 -07001304 * Event engine binding
Sree Kuchibhotlaf448c342016-05-19 10:51:24 -07001305 */
1306
1307static void shutdown_engine(void) {
1308 fd_global_shutdown();
1309 pollset_global_shutdown();
1310}
1311
1312static const grpc_event_engine_vtable vtable = {
1313 .pollset_size = sizeof(grpc_pollset),
1314
1315 .fd_create = fd_create,
1316 .fd_wrapped_fd = fd_wrapped_fd,
1317 .fd_orphan = fd_orphan,
1318 .fd_shutdown = fd_shutdown,
1319 .fd_notify_on_read = fd_notify_on_read,
1320 .fd_notify_on_write = fd_notify_on_write,
1321
1322 .pollset_init = pollset_init,
1323 .pollset_shutdown = pollset_shutdown,
1324 .pollset_reset = pollset_reset,
1325 .pollset_destroy = pollset_destroy,
1326 .pollset_work = pollset_work,
1327 .pollset_kick = pollset_kick,
1328 .pollset_add_fd = pollset_add_fd,
1329
1330 .pollset_set_create = pollset_set_create,
1331 .pollset_set_destroy = pollset_set_destroy,
1332 .pollset_set_add_pollset = pollset_set_add_pollset,
1333 .pollset_set_del_pollset = pollset_set_del_pollset,
1334 .pollset_set_add_pollset_set = pollset_set_add_pollset_set,
1335 .pollset_set_del_pollset_set = pollset_set_del_pollset_set,
1336 .pollset_set_add_fd = pollset_set_add_fd,
1337 .pollset_set_del_fd = pollset_set_del_fd,
1338
1339 .kick_poller = kick_poller,
1340
1341 .shutdown_engine = shutdown_engine,
1342};
1343
1344const grpc_event_engine_vtable *grpc_init_epoll_linux(void) {
1345 fd_global_init();
1346 pollset_global_init();
1347 polling_island_global_init();
1348 return &vtable;
1349}
1350
1351#endif