Imported Upstream version 1.21.0
[platform/upstream/grpc.git] / src / core / lib / iomgr / ev_posix.cc
1 /*
2  *
3  * Copyright 2015 gRPC authors.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *     http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  */
18
19 #include <grpc/support/port_platform.h>
20
21 #include "src/core/lib/iomgr/port.h"
22
23 #ifdef GRPC_POSIX_SOCKET_EV
24
25 #include "src/core/lib/iomgr/ev_posix.h"
26
27 #include <string.h>
28
29 #include <grpc/support/alloc.h>
30 #include <grpc/support/log.h>
31 #include <grpc/support/string_util.h>
32
33 #include "src/core/lib/debug/trace.h"
34 #include "src/core/lib/gpr/useful.h"
35 #include "src/core/lib/gprpp/global_config.h"
36 #include "src/core/lib/iomgr/ev_epoll1_linux.h"
37 #include "src/core/lib/iomgr/ev_epollex_linux.h"
38 #include "src/core/lib/iomgr/ev_poll_posix.h"
39 #include "src/core/lib/iomgr/internal_errqueue.h"
40
41 GPR_GLOBAL_CONFIG_DEFINE_STRING(
42     grpc_poll_strategy, "all",
43     "Declares which polling engines to try when starting gRPC. "
44     "This is a comma-separated list of engines, which are tried in priority "
45     "order first -> last.")
46
47 grpc_core::TraceFlag grpc_polling_trace(false,
48                                         "polling"); /* Disabled by default */
49
50 /* Traces fd create/close operations */
51 grpc_core::TraceFlag grpc_fd_trace(false, "fd_trace");
52 grpc_core::DebugOnlyTraceFlag grpc_trace_fd_refcount(false, "fd_refcount");
53 grpc_core::DebugOnlyTraceFlag grpc_polling_api_trace(false, "polling_api");
54
55 // Polling API trace only enabled in debug builds
56 #ifndef NDEBUG
57 #define GRPC_POLLING_API_TRACE(format, ...)                  \
58   if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_api_trace)) {     \
59     gpr_log(GPR_INFO, "(polling-api) " format, __VA_ARGS__); \
60   }
61 #else
62 #define GRPC_POLLING_API_TRACE(...)
63 #endif  // NDEBUG
64
65 /** Default poll() function - a pointer so that it can be overridden by some
66  *  tests */
67 #ifndef GPR_AIX
68 grpc_poll_function_type grpc_poll_function = poll;
69 #else
70 int aix_poll(struct pollfd fds[], nfds_t nfds, int timeout) {
71   return poll(fds, nfds, timeout);
72 }
73 grpc_poll_function_type grpc_poll_function = aix_poll;
74 #endif  // GPR_AIX
75
76 grpc_wakeup_fd grpc_global_wakeup_fd;
77
78 static const grpc_event_engine_vtable* g_event_engine = nullptr;
79 static const char* g_poll_strategy_name = nullptr;
80
81 typedef const grpc_event_engine_vtable* (*event_engine_factory_fn)(
82     bool explicit_request);
83
84 typedef struct {
85   const char* name;
86   event_engine_factory_fn factory;
87 } event_engine_factory;
88
89 namespace {
90
91 grpc_poll_function_type real_poll_function;
92
93 int dummy_poll(struct pollfd fds[], nfds_t nfds, int timeout) {
94   if (timeout == 0) {
95     return real_poll_function(fds, nfds, 0);
96   } else {
97     gpr_log(GPR_ERROR, "Attempted a blocking poll when declared non-polling.");
98     GPR_ASSERT(false);
99     return -1;
100   }
101 }
102
103 const grpc_event_engine_vtable* init_non_polling(bool explicit_request) {
104   if (!explicit_request) {
105     return nullptr;
106   }
107   // return the simplest engine as a dummy but also override the poller
108   auto ret = grpc_init_poll_posix(explicit_request);
109   real_poll_function = grpc_poll_function;
110   grpc_poll_function = dummy_poll;
111
112   return ret;
113 }
114 }  // namespace
115
116 #define ENGINE_HEAD_CUSTOM "head_custom"
117 #define ENGINE_TAIL_CUSTOM "tail_custom"
118
119 // The global array of event-engine factories. Each entry is a pair with a name
120 // and an event-engine generator function (nullptr if there is no generator
121 // registered for this name). The middle entries are the engines predefined by
122 // open-source gRPC. The head entries represent an opportunity for specific
123 // high-priority custom pollers to be added by the initializer plugins of
124 // custom-built gRPC libraries. The tail entries represent the same, but for
125 // low-priority custom pollers. The actual poller selected is either the first
126 // available one in the list if no specific poller is requested, or the first
127 // specific poller that is requested by name in the GRPC_POLL_STRATEGY
128 // environment variable if that variable is set (which should be a
129 // comma-separated list of one or more event engine names)
130 static event_engine_factory g_factories[] = {
131     {ENGINE_HEAD_CUSTOM, nullptr},        {ENGINE_HEAD_CUSTOM, nullptr},
132     {ENGINE_HEAD_CUSTOM, nullptr},        {ENGINE_HEAD_CUSTOM, nullptr},
133     {"epollex", grpc_init_epollex_linux}, {"epoll1", grpc_init_epoll1_linux},
134     {"poll", grpc_init_poll_posix},       {"none", init_non_polling},
135     {ENGINE_TAIL_CUSTOM, nullptr},        {ENGINE_TAIL_CUSTOM, nullptr},
136     {ENGINE_TAIL_CUSTOM, nullptr},        {ENGINE_TAIL_CUSTOM, nullptr},
137 };
138
139 static void add(const char* beg, const char* end, char*** ss, size_t* ns) {
140   size_t n = *ns;
141   size_t np = n + 1;
142   char* s;
143   size_t len;
144   GPR_ASSERT(end >= beg);
145   len = static_cast<size_t>(end - beg);
146   s = static_cast<char*>(gpr_malloc(len + 1));
147   memcpy(s, beg, len);
148   s[len] = 0;
149   *ss = static_cast<char**>(gpr_realloc(*ss, sizeof(char**) * np));
150   (*ss)[n] = s;
151   *ns = np;
152 }
153
154 static void split(const char* s, char*** ss, size_t* ns) {
155   const char* c = strchr(s, ',');
156   if (c == nullptr) {
157     add(s, s + strlen(s), ss, ns);
158   } else {
159     add(s, c, ss, ns);
160     split(c + 1, ss, ns);
161   }
162 }
163
164 static bool is(const char* want, const char* have) {
165   return 0 == strcmp(want, "all") || 0 == strcmp(want, have);
166 }
167
168 static void try_engine(const char* engine) {
169   for (size_t i = 0; i < GPR_ARRAY_SIZE(g_factories); i++) {
170     if (g_factories[i].factory != nullptr && is(engine, g_factories[i].name)) {
171       if ((g_event_engine = g_factories[i].factory(
172                0 == strcmp(engine, g_factories[i].name)))) {
173         g_poll_strategy_name = g_factories[i].name;
174         gpr_log(GPR_DEBUG, "Using polling engine: %s", g_factories[i].name);
175         return;
176       }
177     }
178   }
179 }
180
181 /* Call this before calling grpc_event_engine_init() */
182 void grpc_register_event_engine_factory(const char* name,
183                                         event_engine_factory_fn factory,
184                                         bool add_at_head) {
185   const char* custom_match =
186       add_at_head ? ENGINE_HEAD_CUSTOM : ENGINE_TAIL_CUSTOM;
187
188   // Overwrite an existing registration if already registered
189   for (size_t i = 0; i < GPR_ARRAY_SIZE(g_factories); i++) {
190     if (0 == strcmp(name, g_factories[i].name)) {
191       g_factories[i].factory = factory;
192       return;
193     }
194   }
195
196   // Otherwise fill in an available custom slot
197   for (size_t i = 0; i < GPR_ARRAY_SIZE(g_factories); i++) {
198     if (0 == strcmp(g_factories[i].name, custom_match)) {
199       g_factories[i].name = name;
200       g_factories[i].factory = factory;
201       return;
202     }
203   }
204
205   // Otherwise fail
206   GPR_ASSERT(false);
207 }
208
209 /* Call this only after calling grpc_event_engine_init() */
210 const char* grpc_get_poll_strategy_name() { return g_poll_strategy_name; }
211
212 void grpc_event_engine_init(void) {
213   grpc_core::UniquePtr<char> value = GPR_GLOBAL_CONFIG_GET(grpc_poll_strategy);
214
215   char** strings = nullptr;
216   size_t nstrings = 0;
217   split(value.get(), &strings, &nstrings);
218
219   for (size_t i = 0; g_event_engine == nullptr && i < nstrings; i++) {
220     try_engine(strings[i]);
221   }
222
223   for (size_t i = 0; i < nstrings; i++) {
224     gpr_free(strings[i]);
225   }
226   gpr_free(strings);
227
228   if (g_event_engine == nullptr) {
229     gpr_log(GPR_ERROR, "No event engine could be initialized from %s",
230             value.get());
231     abort();
232   }
233 }
234
235 void grpc_event_engine_shutdown(void) {
236   g_event_engine->shutdown_engine();
237   g_event_engine = nullptr;
238 }
239
240 bool grpc_event_engine_can_track_errors(void) {
241   /* Only track errors if platform supports errqueue. */
242   if (grpc_core::kernel_supports_errqueue()) {
243     return g_event_engine->can_track_err;
244   }
245   return false;
246 }
247
248 bool grpc_event_engine_run_in_background(void) {
249   return g_event_engine->run_in_background;
250 }
251
252 grpc_fd* grpc_fd_create(int fd, const char* name, bool track_err) {
253   GRPC_POLLING_API_TRACE("fd_create(%d, %s, %d)", fd, name, track_err);
254   GRPC_FD_TRACE("fd_create(%d, %s, %d)", fd, name, track_err);
255   return g_event_engine->fd_create(
256       fd, name, track_err && grpc_event_engine_can_track_errors());
257 }
258
259 int grpc_fd_wrapped_fd(grpc_fd* fd) {
260   return g_event_engine->fd_wrapped_fd(fd);
261 }
262
263 void grpc_fd_orphan(grpc_fd* fd, grpc_closure* on_done, int* release_fd,
264                     const char* reason) {
265   GRPC_POLLING_API_TRACE("fd_orphan(%d, %p, %p, %s)", grpc_fd_wrapped_fd(fd),
266                          on_done, release_fd, reason);
267   GRPC_FD_TRACE("grpc_fd_orphan, fd:%d closed", grpc_fd_wrapped_fd(fd));
268
269   g_event_engine->fd_orphan(fd, on_done, release_fd, reason);
270 }
271
272 void grpc_fd_shutdown(grpc_fd* fd, grpc_error* why) {
273   GRPC_POLLING_API_TRACE("fd_shutdown(%d)", grpc_fd_wrapped_fd(fd));
274   GRPC_FD_TRACE("fd_shutdown(%d)", grpc_fd_wrapped_fd(fd));
275   g_event_engine->fd_shutdown(fd, why);
276 }
277
278 bool grpc_fd_is_shutdown(grpc_fd* fd) {
279   return g_event_engine->fd_is_shutdown(fd);
280 }
281
282 void grpc_fd_notify_on_read(grpc_fd* fd, grpc_closure* closure) {
283   g_event_engine->fd_notify_on_read(fd, closure);
284 }
285
286 void grpc_fd_notify_on_write(grpc_fd* fd, grpc_closure* closure) {
287   g_event_engine->fd_notify_on_write(fd, closure);
288 }
289
290 void grpc_fd_notify_on_error(grpc_fd* fd, grpc_closure* closure) {
291   g_event_engine->fd_notify_on_error(fd, closure);
292 }
293
294 void grpc_fd_set_readable(grpc_fd* fd) { g_event_engine->fd_set_readable(fd); }
295
296 void grpc_fd_set_writable(grpc_fd* fd) { g_event_engine->fd_set_writable(fd); }
297
298 void grpc_fd_set_error(grpc_fd* fd) { g_event_engine->fd_set_error(fd); }
299
300 static size_t pollset_size(void) { return g_event_engine->pollset_size; }
301
302 static void pollset_init(grpc_pollset* pollset, gpr_mu** mu) {
303   GRPC_POLLING_API_TRACE("pollset_init(%p)", pollset);
304   g_event_engine->pollset_init(pollset, mu);
305 }
306
307 static void pollset_shutdown(grpc_pollset* pollset, grpc_closure* closure) {
308   GRPC_POLLING_API_TRACE("pollset_shutdown(%p)", pollset);
309   g_event_engine->pollset_shutdown(pollset, closure);
310 }
311
312 static void pollset_destroy(grpc_pollset* pollset) {
313   GRPC_POLLING_API_TRACE("pollset_destroy(%p)", pollset);
314   g_event_engine->pollset_destroy(pollset);
315 }
316
317 static grpc_error* pollset_work(grpc_pollset* pollset,
318                                 grpc_pollset_worker** worker,
319                                 grpc_millis deadline) {
320   GRPC_POLLING_API_TRACE("pollset_work(%p, %" PRId64 ") begin", pollset,
321                          deadline);
322   grpc_error* err = g_event_engine->pollset_work(pollset, worker, deadline);
323   GRPC_POLLING_API_TRACE("pollset_work(%p, %" PRId64 ") end", pollset,
324                          deadline);
325   return err;
326 }
327
328 static grpc_error* pollset_kick(grpc_pollset* pollset,
329                                 grpc_pollset_worker* specific_worker) {
330   GRPC_POLLING_API_TRACE("pollset_kick(%p, %p)", pollset, specific_worker);
331   return g_event_engine->pollset_kick(pollset, specific_worker);
332 }
333
334 void grpc_pollset_add_fd(grpc_pollset* pollset, struct grpc_fd* fd) {
335   GRPC_POLLING_API_TRACE("pollset_add_fd(%p, %d)", pollset,
336                          grpc_fd_wrapped_fd(fd));
337   g_event_engine->pollset_add_fd(pollset, fd);
338 }
339
340 void pollset_global_init() {}
341 void pollset_global_shutdown() {}
342
343 grpc_pollset_vtable grpc_posix_pollset_vtable = {
344     pollset_global_init, pollset_global_shutdown,
345     pollset_init,        pollset_shutdown,
346     pollset_destroy,     pollset_work,
347     pollset_kick,        pollset_size};
348
349 static grpc_pollset_set* pollset_set_create(void) {
350   grpc_pollset_set* pss = g_event_engine->pollset_set_create();
351   GRPC_POLLING_API_TRACE("pollset_set_create(%p)", pss);
352   return pss;
353 }
354
355 static void pollset_set_destroy(grpc_pollset_set* pollset_set) {
356   GRPC_POLLING_API_TRACE("pollset_set_destroy(%p)", pollset_set);
357   g_event_engine->pollset_set_destroy(pollset_set);
358 }
359
360 static void pollset_set_add_pollset(grpc_pollset_set* pollset_set,
361                                     grpc_pollset* pollset) {
362   GRPC_POLLING_API_TRACE("pollset_set_add_pollset(%p, %p)", pollset_set,
363                          pollset);
364   g_event_engine->pollset_set_add_pollset(pollset_set, pollset);
365 }
366
367 static void pollset_set_del_pollset(grpc_pollset_set* pollset_set,
368                                     grpc_pollset* pollset) {
369   GRPC_POLLING_API_TRACE("pollset_set_del_pollset(%p, %p)", pollset_set,
370                          pollset);
371   g_event_engine->pollset_set_del_pollset(pollset_set, pollset);
372 }
373
374 static void pollset_set_add_pollset_set(grpc_pollset_set* bag,
375                                         grpc_pollset_set* item) {
376   GRPC_POLLING_API_TRACE("pollset_set_add_pollset_set(%p, %p)", bag, item);
377   g_event_engine->pollset_set_add_pollset_set(bag, item);
378 }
379
380 static void pollset_set_del_pollset_set(grpc_pollset_set* bag,
381                                         grpc_pollset_set* item) {
382   GRPC_POLLING_API_TRACE("pollset_set_del_pollset_set(%p, %p)", bag, item);
383   g_event_engine->pollset_set_del_pollset_set(bag, item);
384 }
385
386 grpc_pollset_set_vtable grpc_posix_pollset_set_vtable = {
387     pollset_set_create,          pollset_set_destroy,
388     pollset_set_add_pollset,     pollset_set_del_pollset,
389     pollset_set_add_pollset_set, pollset_set_del_pollset_set};
390
391 void grpc_pollset_set_add_fd(grpc_pollset_set* pollset_set, grpc_fd* fd) {
392   GRPC_POLLING_API_TRACE("pollset_set_add_fd(%p, %d)", pollset_set,
393                          grpc_fd_wrapped_fd(fd));
394   g_event_engine->pollset_set_add_fd(pollset_set, fd);
395 }
396
397 void grpc_pollset_set_del_fd(grpc_pollset_set* pollset_set, grpc_fd* fd) {
398   GRPC_POLLING_API_TRACE("pollset_set_del_fd(%p, %d)", pollset_set,
399                          grpc_fd_wrapped_fd(fd));
400   g_event_engine->pollset_set_del_fd(pollset_set, fd);
401 }
402
403 bool grpc_is_any_background_poller_thread(void) {
404   return g_event_engine->is_any_background_poller_thread();
405 }
406
407 bool grpc_add_closure_to_background_poller(grpc_closure* closure,
408                                            grpc_error* error) {
409   return g_event_engine->add_closure_to_background_poller(closure, error);
410 }
411
412 void grpc_shutdown_background_closure(void) {
413   g_event_engine->shutdown_background_closure();
414 }
415
416 #endif  // GRPC_POSIX_SOCKET_EV