ev_poll_posix.c 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532
  1. /*
  2. *
  3. * Copyright 2016 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. #include "src/core/lib/iomgr/port.h"
  19. #ifdef GRPC_POSIX_SOCKET
  20. #include "src/core/lib/iomgr/ev_poll_posix.h"
  21. #include <assert.h>
  22. #include <errno.h>
  23. #include <poll.h>
  24. #include <string.h>
  25. #include <sys/socket.h>
  26. #include <unistd.h>
  27. #include <grpc/support/alloc.h>
  28. #include <grpc/support/log.h>
  29. #include <grpc/support/string_util.h>
  30. #include <grpc/support/thd.h>
  31. #include <grpc/support/tls.h>
  32. #include <grpc/support/useful.h>
  33. #include "src/core/lib/iomgr/iomgr_internal.h"
  34. #include "src/core/lib/iomgr/timer.h"
  35. #include "src/core/lib/iomgr/wakeup_fd_cv.h"
  36. #include "src/core/lib/iomgr/wakeup_fd_posix.h"
  37. #include "src/core/lib/profiling/timers.h"
  38. #include "src/core/lib/support/block_annotate.h"
  39. #define GRPC_POLLSET_KICK_BROADCAST ((grpc_pollset_worker *)1)
  40. /*******************************************************************************
  41. * FD declarations
  42. */
  43. typedef struct grpc_fd_watcher {
  44. struct grpc_fd_watcher *next;
  45. struct grpc_fd_watcher *prev;
  46. grpc_pollset *pollset;
  47. grpc_pollset_worker *worker;
  48. grpc_fd *fd;
  49. } grpc_fd_watcher;
  50. struct grpc_fd {
  51. int fd;
  52. /* refst format:
  53. bit0: 1=active/0=orphaned
  54. bit1-n: refcount
  55. meaning that mostly we ref by two to avoid altering the orphaned bit,
  56. and just unref by 1 when we're ready to flag the object as orphaned */
  57. gpr_atm refst;
  58. gpr_mu mu;
  59. int shutdown;
  60. int closed;
  61. int released;
  62. grpc_error *shutdown_error;
  63. /* The watcher list.
  64. The following watcher related fields are protected by watcher_mu.
  65. An fd_watcher is an ephemeral object created when an fd wants to
  66. begin polling, and destroyed after the poll.
  67. It denotes the fd's interest in whether to read poll or write poll
  68. or both or neither on this fd.
  69. If a watcher is asked to poll for reads or writes, the read_watcher
  70. or write_watcher fields are set respectively. A watcher may be asked
  71. to poll for both, in which case both fields will be set.
  72. read_watcher and write_watcher may be NULL if no watcher has been
  73. asked to poll for reads or writes.
  74. If an fd_watcher is not asked to poll for reads or writes, it's added
  75. to a linked list of inactive watchers, rooted at inactive_watcher_root.
  76. If at a later time there becomes need of a poller to poll, one of
  77. the inactive pollers may be kicked out of their poll loops to take
  78. that responsibility. */
  79. grpc_fd_watcher inactive_watcher_root;
  80. grpc_fd_watcher *read_watcher;
  81. grpc_fd_watcher *write_watcher;
  82. grpc_closure *read_closure;
  83. grpc_closure *write_closure;
  84. grpc_closure *on_done_closure;
  85. grpc_iomgr_object iomgr_object;
  86. /* The pollset that last noticed and notified that the fd is readable */
  87. grpc_pollset *read_notifier_pollset;
  88. };
  89. /* Begin polling on an fd.
  90. Registers that the given pollset is interested in this fd - so that if read
  91. or writability interest changes, the pollset can be kicked to pick up that
  92. new interest.
  93. Return value is:
  94. (fd_needs_read? read_mask : 0) | (fd_needs_write? write_mask : 0)
  95. i.e. a combination of read_mask and write_mask determined by the fd's current
  96. interest in said events.
  97. Polling strategies that do not need to alter their behavior depending on the
  98. fd's current interest (such as epoll) do not need to call this function.
  99. MUST NOT be called with a pollset lock taken */
  100. static uint32_t fd_begin_poll(grpc_fd *fd, grpc_pollset *pollset,
  101. grpc_pollset_worker *worker, uint32_t read_mask,
  102. uint32_t write_mask, grpc_fd_watcher *rec);
  103. /* Complete polling previously started with fd_begin_poll
  104. MUST NOT be called with a pollset lock taken
  105. if got_read or got_write are 1, also does the become_{readable,writable} as
  106. appropriate. */
  107. static void fd_end_poll(grpc_exec_ctx *exec_ctx, grpc_fd_watcher *rec,
  108. int got_read, int got_write,
  109. grpc_pollset *read_notifier_pollset);
  110. /* Return 1 if this fd is orphaned, 0 otherwise */
  111. static bool fd_is_orphaned(grpc_fd *fd);
  112. /* Reference counting for fds */
  113. //#define GRPC_FD_REF_COUNT_DEBUG
  114. #ifdef GRPC_FD_REF_COUNT_DEBUG
  115. static void fd_ref(grpc_fd *fd, const char *reason, const char *file, int line);
  116. static void fd_unref(grpc_fd *fd, const char *reason, const char *file,
  117. int line);
  118. #define GRPC_FD_REF(fd, reason) fd_ref(fd, reason, __FILE__, __LINE__)
  119. #define GRPC_FD_UNREF(fd, reason) fd_unref(fd, reason, __FILE__, __LINE__)
  120. #else
  121. static void fd_ref(grpc_fd *fd);
  122. static void fd_unref(grpc_fd *fd);
  123. #define GRPC_FD_REF(fd, reason) fd_ref(fd)
  124. #define GRPC_FD_UNREF(fd, reason) fd_unref(fd)
  125. #endif
  126. #define CLOSURE_NOT_READY ((grpc_closure *)0)
  127. #define CLOSURE_READY ((grpc_closure *)1)
  128. /*******************************************************************************
  129. * pollset declarations
  130. */
  131. typedef struct grpc_cached_wakeup_fd {
  132. grpc_wakeup_fd fd;
  133. struct grpc_cached_wakeup_fd *next;
  134. } grpc_cached_wakeup_fd;
  135. struct grpc_pollset_worker {
  136. grpc_cached_wakeup_fd *wakeup_fd;
  137. int reevaluate_polling_on_wakeup;
  138. int kicked_specifically;
  139. struct grpc_pollset_worker *next;
  140. struct grpc_pollset_worker *prev;
  141. };
  142. struct grpc_pollset {
  143. gpr_mu mu;
  144. grpc_pollset_worker root_worker;
  145. int shutting_down;
  146. int called_shutdown;
  147. int kicked_without_pollers;
  148. grpc_closure *shutdown_done;
  149. grpc_closure_list idle_jobs;
  150. int pollset_set_count;
  151. /* all polled fds */
  152. size_t fd_count;
  153. size_t fd_capacity;
  154. grpc_fd **fds;
  155. /* Local cache of eventfds for workers */
  156. grpc_cached_wakeup_fd *local_wakeup_cache;
  157. };
  158. /* Add an fd to a pollset */
  159. static void pollset_add_fd(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset,
  160. struct grpc_fd *fd);
  161. static void pollset_set_add_fd(grpc_exec_ctx *exec_ctx,
  162. grpc_pollset_set *pollset_set, grpc_fd *fd);
  163. /* Convert a timespec to milliseconds:
  164. - very small or negative poll times are clamped to zero to do a
  165. non-blocking poll (which becomes spin polling)
  166. - other small values are rounded up to one millisecond
  167. - longer than a millisecond polls are rounded up to the next nearest
  168. millisecond to avoid spinning
  169. - infinite timeouts are converted to -1 */
  170. static int poll_deadline_to_millis_timeout(gpr_timespec deadline,
  171. gpr_timespec now);
  172. /* Allow kick to wakeup the currently polling worker */
  173. #define GRPC_POLLSET_CAN_KICK_SELF 1
  174. /* Force the wakee to repoll when awoken */
  175. #define GRPC_POLLSET_REEVALUATE_POLLING_ON_WAKEUP 2
  176. /* As per pollset_kick, with an extended set of flags (defined above)
  177. -- mostly for fd_posix's use. */
  178. static grpc_error *pollset_kick_ext(grpc_pollset *p,
  179. grpc_pollset_worker *specific_worker,
  180. uint32_t flags) GRPC_MUST_USE_RESULT;
  181. /* Return 1 if the pollset has active threads in pollset_work (pollset must
  182. * be locked) */
  183. static bool pollset_has_workers(grpc_pollset *pollset);
  184. /*******************************************************************************
  185. * pollset_set definitions
  186. */
  187. struct grpc_pollset_set {
  188. gpr_mu mu;
  189. size_t pollset_count;
  190. size_t pollset_capacity;
  191. grpc_pollset **pollsets;
  192. size_t pollset_set_count;
  193. size_t pollset_set_capacity;
  194. struct grpc_pollset_set **pollset_sets;
  195. size_t fd_count;
  196. size_t fd_capacity;
  197. grpc_fd **fds;
  198. };
  199. /*******************************************************************************
  200. * condition variable polling definitions
  201. */
  202. #define CV_POLL_PERIOD_MS 1000
  203. #define CV_DEFAULT_TABLE_SIZE 16
  204. typedef enum poll_status_t { INPROGRESS, COMPLETED, CANCELLED } poll_status_t;
  205. typedef struct poll_args {
  206. gpr_refcount refcount;
  207. gpr_cv *cv;
  208. struct pollfd *fds;
  209. nfds_t nfds;
  210. int timeout;
  211. int retval;
  212. int err;
  213. gpr_atm status;
  214. } poll_args;
  215. cv_fd_table g_cvfds;
  216. /*******************************************************************************
  217. * fd_posix.c
  218. */
  219. #ifdef GRPC_FD_REF_COUNT_DEBUG
  220. #define REF_BY(fd, n, reason) ref_by(fd, n, reason, __FILE__, __LINE__)
  221. #define UNREF_BY(fd, n, reason) unref_by(fd, n, reason, __FILE__, __LINE__)
  222. static void ref_by(grpc_fd *fd, int n, const char *reason, const char *file,
  223. int line) {
  224. gpr_log(GPR_DEBUG, "FD %d %p ref %d %d -> %d [%s; %s:%d]", fd->fd, fd, n,
  225. (int)gpr_atm_no_barrier_load(&fd->refst),
  226. (int)gpr_atm_no_barrier_load(&fd->refst) + n, reason, file, line);
  227. #else
  228. #define REF_BY(fd, n, reason) ref_by(fd, n)
  229. #define UNREF_BY(fd, n, reason) unref_by(fd, n)
  230. static void ref_by(grpc_fd *fd, int n) {
  231. #endif
  232. GPR_ASSERT(gpr_atm_no_barrier_fetch_add(&fd->refst, n) > 0);
  233. }
  234. #ifdef GRPC_FD_REF_COUNT_DEBUG
  235. static void unref_by(grpc_fd *fd, int n, const char *reason, const char *file,
  236. int line) {
  237. gpr_atm old;
  238. gpr_log(GPR_DEBUG, "FD %d %p unref %d %d -> %d [%s; %s:%d]", fd->fd, fd, n,
  239. (int)gpr_atm_no_barrier_load(&fd->refst),
  240. (int)gpr_atm_no_barrier_load(&fd->refst) - n, reason, file, line);
  241. #else
  242. static void unref_by(grpc_fd *fd, int n) {
  243. gpr_atm old;
  244. #endif
  245. old = gpr_atm_full_fetch_add(&fd->refst, -n);
  246. if (old == n) {
  247. gpr_mu_destroy(&fd->mu);
  248. grpc_iomgr_unregister_object(&fd->iomgr_object);
  249. if (fd->shutdown) GRPC_ERROR_UNREF(fd->shutdown_error);
  250. gpr_free(fd);
  251. } else {
  252. GPR_ASSERT(old > n);
  253. }
  254. }
  255. static grpc_fd *fd_create(int fd, const char *name) {
  256. grpc_fd *r = gpr_malloc(sizeof(*r));
  257. gpr_mu_init(&r->mu);
  258. gpr_atm_rel_store(&r->refst, 1);
  259. r->shutdown = 0;
  260. r->read_closure = CLOSURE_NOT_READY;
  261. r->write_closure = CLOSURE_NOT_READY;
  262. r->fd = fd;
  263. r->inactive_watcher_root.next = r->inactive_watcher_root.prev =
  264. &r->inactive_watcher_root;
  265. r->read_watcher = r->write_watcher = NULL;
  266. r->on_done_closure = NULL;
  267. r->closed = 0;
  268. r->released = 0;
  269. r->read_notifier_pollset = NULL;
  270. char *name2;
  271. gpr_asprintf(&name2, "%s fd=%d", name, fd);
  272. grpc_iomgr_register_object(&r->iomgr_object, name2);
  273. gpr_free(name2);
  274. #ifdef GRPC_FD_REF_COUNT_DEBUG
  275. gpr_log(GPR_DEBUG, "FD %d %p create %s", fd, r, name);
  276. #endif
  277. return r;
  278. }
  279. static bool fd_is_orphaned(grpc_fd *fd) {
  280. return (gpr_atm_acq_load(&fd->refst) & 1) == 0;
  281. }
  282. /* Return the read-notifier pollset */
  283. static grpc_pollset *fd_get_read_notifier_pollset(grpc_exec_ctx *exec_ctx,
  284. grpc_fd *fd) {
  285. grpc_pollset *notifier = NULL;
  286. gpr_mu_lock(&fd->mu);
  287. notifier = fd->read_notifier_pollset;
  288. gpr_mu_unlock(&fd->mu);
  289. return notifier;
  290. }
  291. static grpc_error *pollset_kick_locked(grpc_fd_watcher *watcher) {
  292. gpr_mu_lock(&watcher->pollset->mu);
  293. GPR_ASSERT(watcher->worker);
  294. grpc_error *err = pollset_kick_ext(watcher->pollset, watcher->worker,
  295. GRPC_POLLSET_REEVALUATE_POLLING_ON_WAKEUP);
  296. gpr_mu_unlock(&watcher->pollset->mu);
  297. return err;
  298. }
  299. static void maybe_wake_one_watcher_locked(grpc_fd *fd) {
  300. if (fd->inactive_watcher_root.next != &fd->inactive_watcher_root) {
  301. pollset_kick_locked(fd->inactive_watcher_root.next);
  302. } else if (fd->read_watcher) {
  303. pollset_kick_locked(fd->read_watcher);
  304. } else if (fd->write_watcher) {
  305. pollset_kick_locked(fd->write_watcher);
  306. }
  307. }
  308. static void wake_all_watchers_locked(grpc_fd *fd) {
  309. grpc_fd_watcher *watcher;
  310. for (watcher = fd->inactive_watcher_root.next;
  311. watcher != &fd->inactive_watcher_root; watcher = watcher->next) {
  312. pollset_kick_locked(watcher);
  313. }
  314. if (fd->read_watcher) {
  315. pollset_kick_locked(fd->read_watcher);
  316. }
  317. if (fd->write_watcher && fd->write_watcher != fd->read_watcher) {
  318. pollset_kick_locked(fd->write_watcher);
  319. }
  320. }
  321. static int has_watchers(grpc_fd *fd) {
  322. return fd->read_watcher != NULL || fd->write_watcher != NULL ||
  323. fd->inactive_watcher_root.next != &fd->inactive_watcher_root;
  324. }
  325. static void close_fd_locked(grpc_exec_ctx *exec_ctx, grpc_fd *fd) {
  326. fd->closed = 1;
  327. if (!fd->released) {
  328. close(fd->fd);
  329. }
  330. GRPC_CLOSURE_SCHED(exec_ctx, fd->on_done_closure, GRPC_ERROR_NONE);
  331. }
  332. static int fd_wrapped_fd(grpc_fd *fd) {
  333. if (fd->released || fd->closed) {
  334. return -1;
  335. } else {
  336. return fd->fd;
  337. }
  338. }
  339. static void fd_orphan(grpc_exec_ctx *exec_ctx, grpc_fd *fd,
  340. grpc_closure *on_done, int *release_fd,
  341. const char *reason) {
  342. fd->on_done_closure = on_done;
  343. fd->released = release_fd != NULL;
  344. if (fd->released) {
  345. *release_fd = fd->fd;
  346. }
  347. gpr_mu_lock(&fd->mu);
  348. REF_BY(fd, 1, reason); /* remove active status, but keep referenced */
  349. if (!has_watchers(fd)) {
  350. close_fd_locked(exec_ctx, fd);
  351. } else {
  352. wake_all_watchers_locked(fd);
  353. }
  354. gpr_mu_unlock(&fd->mu);
  355. UNREF_BY(fd, 2, reason); /* drop the reference */
  356. }
  357. /* increment refcount by two to avoid changing the orphan bit */
  358. #ifdef GRPC_FD_REF_COUNT_DEBUG
  359. static void fd_ref(grpc_fd *fd, const char *reason, const char *file,
  360. int line) {
  361. ref_by(fd, 2, reason, file, line);
  362. }
  363. static void fd_unref(grpc_fd *fd, const char *reason, const char *file,
  364. int line) {
  365. unref_by(fd, 2, reason, file, line);
  366. }
  367. #else
  368. static void fd_ref(grpc_fd *fd) { ref_by(fd, 2); }
  369. static void fd_unref(grpc_fd *fd) { unref_by(fd, 2); }
  370. #endif
  371. static grpc_error *fd_shutdown_error(grpc_fd *fd) {
  372. if (!fd->shutdown) {
  373. return GRPC_ERROR_NONE;
  374. } else {
  375. return GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING(
  376. "FD shutdown", &fd->shutdown_error, 1);
  377. }
  378. }
  379. static void notify_on_locked(grpc_exec_ctx *exec_ctx, grpc_fd *fd,
  380. grpc_closure **st, grpc_closure *closure) {
  381. if (fd->shutdown) {
  382. GRPC_CLOSURE_SCHED(exec_ctx, closure,
  383. GRPC_ERROR_CREATE_FROM_STATIC_STRING("FD shutdown"));
  384. } else if (*st == CLOSURE_NOT_READY) {
  385. /* not ready ==> switch to a waiting state by setting the closure */
  386. *st = closure;
  387. } else if (*st == CLOSURE_READY) {
  388. /* already ready ==> queue the closure to run immediately */
  389. *st = CLOSURE_NOT_READY;
  390. GRPC_CLOSURE_SCHED(exec_ctx, closure, fd_shutdown_error(fd));
  391. maybe_wake_one_watcher_locked(fd);
  392. } else {
  393. /* upcallptr was set to a different closure. This is an error! */
  394. gpr_log(GPR_ERROR,
  395. "User called a notify_on function with a previous callback still "
  396. "pending");
  397. abort();
  398. }
  399. }
  400. /* returns 1 if state becomes not ready */
  401. static int set_ready_locked(grpc_exec_ctx *exec_ctx, grpc_fd *fd,
  402. grpc_closure **st) {
  403. if (*st == CLOSURE_READY) {
  404. /* duplicate ready ==> ignore */
  405. return 0;
  406. } else if (*st == CLOSURE_NOT_READY) {
  407. /* not ready, and not waiting ==> flag ready */
  408. *st = CLOSURE_READY;
  409. return 0;
  410. } else {
  411. /* waiting ==> queue closure */
  412. GRPC_CLOSURE_SCHED(exec_ctx, *st, fd_shutdown_error(fd));
  413. *st = CLOSURE_NOT_READY;
  414. return 1;
  415. }
  416. }
  417. static void set_read_notifier_pollset_locked(
  418. grpc_exec_ctx *exec_ctx, grpc_fd *fd, grpc_pollset *read_notifier_pollset) {
  419. fd->read_notifier_pollset = read_notifier_pollset;
  420. }
  421. static void fd_shutdown(grpc_exec_ctx *exec_ctx, grpc_fd *fd, grpc_error *why) {
  422. gpr_mu_lock(&fd->mu);
  423. /* only shutdown once */
  424. if (!fd->shutdown) {
  425. fd->shutdown = 1;
  426. fd->shutdown_error = why;
  427. /* signal read/write closed to OS so that future operations fail */
  428. shutdown(fd->fd, SHUT_RDWR);
  429. set_ready_locked(exec_ctx, fd, &fd->read_closure);
  430. set_ready_locked(exec_ctx, fd, &fd->write_closure);
  431. } else {
  432. GRPC_ERROR_UNREF(why);
  433. }
  434. gpr_mu_unlock(&fd->mu);
  435. }
  436. static bool fd_is_shutdown(grpc_fd *fd) {
  437. gpr_mu_lock(&fd->mu);
  438. bool r = fd->shutdown;
  439. gpr_mu_unlock(&fd->mu);
  440. return r;
  441. }
  442. static void fd_notify_on_read(grpc_exec_ctx *exec_ctx, grpc_fd *fd,
  443. grpc_closure *closure) {
  444. gpr_mu_lock(&fd->mu);
  445. notify_on_locked(exec_ctx, fd, &fd->read_closure, closure);
  446. gpr_mu_unlock(&fd->mu);
  447. }
  448. static void fd_notify_on_write(grpc_exec_ctx *exec_ctx, grpc_fd *fd,
  449. grpc_closure *closure) {
  450. gpr_mu_lock(&fd->mu);
  451. notify_on_locked(exec_ctx, fd, &fd->write_closure, closure);
  452. gpr_mu_unlock(&fd->mu);
  453. }
  454. static uint32_t fd_begin_poll(grpc_fd *fd, grpc_pollset *pollset,
  455. grpc_pollset_worker *worker, uint32_t read_mask,
  456. uint32_t write_mask, grpc_fd_watcher *watcher) {
  457. uint32_t mask = 0;
  458. grpc_closure *cur;
  459. int requested;
  460. /* keep track of pollers that have requested our events, in case they change
  461. */
  462. GRPC_FD_REF(fd, "poll");
  463. gpr_mu_lock(&fd->mu);
  464. /* if we are shutdown, then don't add to the watcher set */
  465. if (fd->shutdown) {
  466. watcher->fd = NULL;
  467. watcher->pollset = NULL;
  468. watcher->worker = NULL;
  469. gpr_mu_unlock(&fd->mu);
  470. GRPC_FD_UNREF(fd, "poll");
  471. return 0;
  472. }
  473. /* if there is nobody polling for read, but we need to, then start doing so */
  474. cur = fd->read_closure;
  475. requested = cur != CLOSURE_READY;
  476. if (read_mask && fd->read_watcher == NULL && requested) {
  477. fd->read_watcher = watcher;
  478. mask |= read_mask;
  479. }
  480. /* if there is nobody polling for write, but we need to, then start doing so
  481. */
  482. cur = fd->write_closure;
  483. requested = cur != CLOSURE_READY;
  484. if (write_mask && fd->write_watcher == NULL && requested) {
  485. fd->write_watcher = watcher;
  486. mask |= write_mask;
  487. }
  488. /* if not polling, remember this watcher in case we need someone to later */
  489. if (mask == 0 && worker != NULL) {
  490. watcher->next = &fd->inactive_watcher_root;
  491. watcher->prev = watcher->next->prev;
  492. watcher->next->prev = watcher->prev->next = watcher;
  493. }
  494. watcher->pollset = pollset;
  495. watcher->worker = worker;
  496. watcher->fd = fd;
  497. gpr_mu_unlock(&fd->mu);
  498. return mask;
  499. }
  500. static void fd_end_poll(grpc_exec_ctx *exec_ctx, grpc_fd_watcher *watcher,
  501. int got_read, int got_write,
  502. grpc_pollset *read_notifier_pollset) {
  503. int was_polling = 0;
  504. int kick = 0;
  505. grpc_fd *fd = watcher->fd;
  506. if (fd == NULL) {
  507. return;
  508. }
  509. gpr_mu_lock(&fd->mu);
  510. if (watcher == fd->read_watcher) {
  511. /* remove read watcher, kick if we still need a read */
  512. was_polling = 1;
  513. if (!got_read) {
  514. kick = 1;
  515. }
  516. fd->read_watcher = NULL;
  517. }
  518. if (watcher == fd->write_watcher) {
  519. /* remove write watcher, kick if we still need a write */
  520. was_polling = 1;
  521. if (!got_write) {
  522. kick = 1;
  523. }
  524. fd->write_watcher = NULL;
  525. }
  526. if (!was_polling && watcher->worker != NULL) {
  527. /* remove from inactive list */
  528. watcher->next->prev = watcher->prev;
  529. watcher->prev->next = watcher->next;
  530. }
  531. if (got_read) {
  532. if (set_ready_locked(exec_ctx, fd, &fd->read_closure)) {
  533. kick = 1;
  534. }
  535. if (read_notifier_pollset != NULL) {
  536. set_read_notifier_pollset_locked(exec_ctx, fd, read_notifier_pollset);
  537. }
  538. }
  539. if (got_write) {
  540. if (set_ready_locked(exec_ctx, fd, &fd->write_closure)) {
  541. kick = 1;
  542. }
  543. }
  544. if (kick) {
  545. maybe_wake_one_watcher_locked(fd);
  546. }
  547. if (fd_is_orphaned(fd) && !has_watchers(fd) && !fd->closed) {
  548. close_fd_locked(exec_ctx, fd);
  549. }
  550. gpr_mu_unlock(&fd->mu);
  551. GRPC_FD_UNREF(fd, "poll");
  552. }
  553. /*******************************************************************************
  554. * pollset_posix.c
  555. */
  556. GPR_TLS_DECL(g_current_thread_poller);
  557. GPR_TLS_DECL(g_current_thread_worker);
  558. static void remove_worker(grpc_pollset *p, grpc_pollset_worker *worker) {
  559. worker->prev->next = worker->next;
  560. worker->next->prev = worker->prev;
  561. }
  562. static bool pollset_has_workers(grpc_pollset *p) {
  563. return p->root_worker.next != &p->root_worker;
  564. }
  565. static bool pollset_in_pollset_sets(grpc_pollset *p) {
  566. return p->pollset_set_count;
  567. }
  568. static bool pollset_has_observers(grpc_pollset *p) {
  569. return pollset_has_workers(p) || pollset_in_pollset_sets(p);
  570. }
  571. static grpc_pollset_worker *pop_front_worker(grpc_pollset *p) {
  572. if (pollset_has_workers(p)) {
  573. grpc_pollset_worker *w = p->root_worker.next;
  574. remove_worker(p, w);
  575. return w;
  576. } else {
  577. return NULL;
  578. }
  579. }
  580. static void push_back_worker(grpc_pollset *p, grpc_pollset_worker *worker) {
  581. worker->next = &p->root_worker;
  582. worker->prev = worker->next->prev;
  583. worker->prev->next = worker->next->prev = worker;
  584. }
  585. static void push_front_worker(grpc_pollset *p, grpc_pollset_worker *worker) {
  586. worker->prev = &p->root_worker;
  587. worker->next = worker->prev->next;
  588. worker->prev->next = worker->next->prev = worker;
  589. }
  590. static void kick_append_error(grpc_error **composite, grpc_error *error) {
  591. if (error == GRPC_ERROR_NONE) return;
  592. if (*composite == GRPC_ERROR_NONE) {
  593. *composite = GRPC_ERROR_CREATE_FROM_STATIC_STRING("Kick Failure");
  594. }
  595. *composite = grpc_error_add_child(*composite, error);
  596. }
  597. static grpc_error *pollset_kick_ext(grpc_pollset *p,
  598. grpc_pollset_worker *specific_worker,
  599. uint32_t flags) {
  600. GPR_TIMER_BEGIN("pollset_kick_ext", 0);
  601. grpc_error *error = GRPC_ERROR_NONE;
  602. /* pollset->mu already held */
  603. if (specific_worker != NULL) {
  604. if (specific_worker == GRPC_POLLSET_KICK_BROADCAST) {
  605. GPR_TIMER_BEGIN("pollset_kick_ext.broadcast", 0);
  606. GPR_ASSERT((flags & GRPC_POLLSET_REEVALUATE_POLLING_ON_WAKEUP) == 0);
  607. for (specific_worker = p->root_worker.next;
  608. specific_worker != &p->root_worker;
  609. specific_worker = specific_worker->next) {
  610. kick_append_error(
  611. &error, grpc_wakeup_fd_wakeup(&specific_worker->wakeup_fd->fd));
  612. }
  613. p->kicked_without_pollers = true;
  614. GPR_TIMER_END("pollset_kick_ext.broadcast", 0);
  615. } else if (gpr_tls_get(&g_current_thread_worker) !=
  616. (intptr_t)specific_worker) {
  617. GPR_TIMER_MARK("different_thread_worker", 0);
  618. if ((flags & GRPC_POLLSET_REEVALUATE_POLLING_ON_WAKEUP) != 0) {
  619. specific_worker->reevaluate_polling_on_wakeup = true;
  620. }
  621. specific_worker->kicked_specifically = true;
  622. kick_append_error(&error,
  623. grpc_wakeup_fd_wakeup(&specific_worker->wakeup_fd->fd));
  624. } else if ((flags & GRPC_POLLSET_CAN_KICK_SELF) != 0) {
  625. GPR_TIMER_MARK("kick_yoself", 0);
  626. if ((flags & GRPC_POLLSET_REEVALUATE_POLLING_ON_WAKEUP) != 0) {
  627. specific_worker->reevaluate_polling_on_wakeup = true;
  628. }
  629. specific_worker->kicked_specifically = true;
  630. kick_append_error(&error,
  631. grpc_wakeup_fd_wakeup(&specific_worker->wakeup_fd->fd));
  632. }
  633. } else if (gpr_tls_get(&g_current_thread_poller) != (intptr_t)p) {
  634. GPR_ASSERT((flags & GRPC_POLLSET_REEVALUATE_POLLING_ON_WAKEUP) == 0);
  635. GPR_TIMER_MARK("kick_anonymous", 0);
  636. specific_worker = pop_front_worker(p);
  637. if (specific_worker != NULL) {
  638. if (gpr_tls_get(&g_current_thread_worker) == (intptr_t)specific_worker) {
  639. GPR_TIMER_MARK("kick_anonymous_not_self", 0);
  640. push_back_worker(p, specific_worker);
  641. specific_worker = pop_front_worker(p);
  642. if ((flags & GRPC_POLLSET_CAN_KICK_SELF) == 0 &&
  643. gpr_tls_get(&g_current_thread_worker) ==
  644. (intptr_t)specific_worker) {
  645. push_back_worker(p, specific_worker);
  646. specific_worker = NULL;
  647. }
  648. }
  649. if (specific_worker != NULL) {
  650. GPR_TIMER_MARK("finally_kick", 0);
  651. push_back_worker(p, specific_worker);
  652. kick_append_error(
  653. &error, grpc_wakeup_fd_wakeup(&specific_worker->wakeup_fd->fd));
  654. }
  655. } else {
  656. GPR_TIMER_MARK("kicked_no_pollers", 0);
  657. p->kicked_without_pollers = true;
  658. }
  659. }
  660. GPR_TIMER_END("pollset_kick_ext", 0);
  661. GRPC_LOG_IF_ERROR("pollset_kick_ext", GRPC_ERROR_REF(error));
  662. return error;
  663. }
  664. static grpc_error *pollset_kick(grpc_pollset *p,
  665. grpc_pollset_worker *specific_worker) {
  666. return pollset_kick_ext(p, specific_worker, 0);
  667. }
  668. /* global state management */
  669. static grpc_error *pollset_global_init(void) {
  670. gpr_tls_init(&g_current_thread_poller);
  671. gpr_tls_init(&g_current_thread_worker);
  672. return GRPC_ERROR_NONE;
  673. }
  674. static void pollset_global_shutdown(void) {
  675. gpr_tls_destroy(&g_current_thread_poller);
  676. gpr_tls_destroy(&g_current_thread_worker);
  677. }
  678. /* main interface */
  679. static void pollset_init(grpc_pollset *pollset, gpr_mu **mu) {
  680. gpr_mu_init(&pollset->mu);
  681. *mu = &pollset->mu;
  682. pollset->root_worker.next = pollset->root_worker.prev = &pollset->root_worker;
  683. pollset->shutting_down = 0;
  684. pollset->called_shutdown = 0;
  685. pollset->kicked_without_pollers = 0;
  686. pollset->idle_jobs.head = pollset->idle_jobs.tail = NULL;
  687. pollset->local_wakeup_cache = NULL;
  688. pollset->kicked_without_pollers = 0;
  689. pollset->fd_count = 0;
  690. pollset->fd_capacity = 0;
  691. pollset->fds = NULL;
  692. pollset->pollset_set_count = 0;
  693. }
  694. static void pollset_destroy(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset) {
  695. GPR_ASSERT(!pollset_has_workers(pollset));
  696. GPR_ASSERT(pollset->idle_jobs.head == pollset->idle_jobs.tail);
  697. while (pollset->local_wakeup_cache) {
  698. grpc_cached_wakeup_fd *next = pollset->local_wakeup_cache->next;
  699. grpc_wakeup_fd_destroy(&pollset->local_wakeup_cache->fd);
  700. gpr_free(pollset->local_wakeup_cache);
  701. pollset->local_wakeup_cache = next;
  702. }
  703. gpr_free(pollset->fds);
  704. gpr_mu_destroy(&pollset->mu);
  705. }
  706. static void pollset_add_fd(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset,
  707. grpc_fd *fd) {
  708. gpr_mu_lock(&pollset->mu);
  709. size_t i;
  710. /* TODO(ctiller): this is O(num_fds^2); maybe switch to a hash set here */
  711. for (i = 0; i < pollset->fd_count; i++) {
  712. if (pollset->fds[i] == fd) goto exit;
  713. }
  714. if (pollset->fd_count == pollset->fd_capacity) {
  715. pollset->fd_capacity =
  716. GPR_MAX(pollset->fd_capacity + 8, pollset->fd_count * 3 / 2);
  717. pollset->fds =
  718. gpr_realloc(pollset->fds, sizeof(grpc_fd *) * pollset->fd_capacity);
  719. }
  720. pollset->fds[pollset->fd_count++] = fd;
  721. GRPC_FD_REF(fd, "multipoller");
  722. pollset_kick(pollset, NULL);
  723. exit:
  724. gpr_mu_unlock(&pollset->mu);
  725. }
  726. static void finish_shutdown(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset) {
  727. GPR_ASSERT(grpc_closure_list_empty(pollset->idle_jobs));
  728. size_t i;
  729. for (i = 0; i < pollset->fd_count; i++) {
  730. GRPC_FD_UNREF(pollset->fds[i], "multipoller");
  731. }
  732. pollset->fd_count = 0;
  733. GRPC_CLOSURE_SCHED(exec_ctx, pollset->shutdown_done, GRPC_ERROR_NONE);
  734. }
  735. static void work_combine_error(grpc_error **composite, grpc_error *error) {
  736. if (error == GRPC_ERROR_NONE) return;
  737. if (*composite == GRPC_ERROR_NONE) {
  738. *composite = GRPC_ERROR_CREATE_FROM_STATIC_STRING("pollset_work");
  739. }
  740. *composite = grpc_error_add_child(*composite, error);
  741. }
  742. static grpc_error *pollset_work(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset,
  743. grpc_pollset_worker **worker_hdl,
  744. gpr_timespec now, gpr_timespec deadline) {
  745. grpc_pollset_worker worker;
  746. if (worker_hdl) *worker_hdl = &worker;
  747. grpc_error *error = GRPC_ERROR_NONE;
  748. /* Avoid malloc for small number of elements. */
  749. enum { inline_elements = 96 };
  750. struct pollfd pollfd_space[inline_elements];
  751. struct grpc_fd_watcher watcher_space[inline_elements];
  752. /* pollset->mu already held */
  753. int added_worker = 0;
  754. int locked = 1;
  755. int queued_work = 0;
  756. int keep_polling = 0;
  757. GPR_TIMER_BEGIN("pollset_work", 0);
  758. /* this must happen before we (potentially) drop pollset->mu */
  759. worker.next = worker.prev = NULL;
  760. worker.reevaluate_polling_on_wakeup = 0;
  761. if (pollset->local_wakeup_cache != NULL) {
  762. worker.wakeup_fd = pollset->local_wakeup_cache;
  763. pollset->local_wakeup_cache = worker.wakeup_fd->next;
  764. } else {
  765. worker.wakeup_fd = gpr_malloc(sizeof(*worker.wakeup_fd));
  766. error = grpc_wakeup_fd_init(&worker.wakeup_fd->fd);
  767. if (error != GRPC_ERROR_NONE) {
  768. GRPC_LOG_IF_ERROR("pollset_work", GRPC_ERROR_REF(error));
  769. return error;
  770. }
  771. }
  772. worker.kicked_specifically = 0;
  773. /* If there's work waiting for the pollset to be idle, and the
  774. pollset is idle, then do that work */
  775. if (!pollset_has_workers(pollset) &&
  776. !grpc_closure_list_empty(pollset->idle_jobs)) {
  777. GPR_TIMER_MARK("pollset_work.idle_jobs", 0);
  778. GRPC_CLOSURE_LIST_SCHED(exec_ctx, &pollset->idle_jobs);
  779. goto done;
  780. }
  781. /* If we're shutting down then we don't execute any extended work */
  782. if (pollset->shutting_down) {
  783. GPR_TIMER_MARK("pollset_work.shutting_down", 0);
  784. goto done;
  785. }
  786. /* Start polling, and keep doing so while we're being asked to
  787. re-evaluate our pollers (this allows poll() based pollers to
  788. ensure they don't miss wakeups) */
  789. keep_polling = 1;
  790. gpr_tls_set(&g_current_thread_poller, (intptr_t)pollset);
  791. while (keep_polling) {
  792. keep_polling = 0;
  793. if (!pollset->kicked_without_pollers) {
  794. if (!added_worker) {
  795. push_front_worker(pollset, &worker);
  796. added_worker = 1;
  797. gpr_tls_set(&g_current_thread_worker, (intptr_t)&worker);
  798. }
  799. GPR_TIMER_BEGIN("maybe_work_and_unlock", 0);
  800. #define POLLOUT_CHECK (POLLOUT | POLLHUP | POLLERR)
  801. #define POLLIN_CHECK (POLLIN | POLLHUP | POLLERR)
  802. int timeout;
  803. int r;
  804. size_t i, fd_count;
  805. nfds_t pfd_count;
  806. grpc_fd_watcher *watchers;
  807. struct pollfd *pfds;
  808. timeout = poll_deadline_to_millis_timeout(deadline, now);
  809. if (pollset->fd_count + 2 <= inline_elements) {
  810. pfds = pollfd_space;
  811. watchers = watcher_space;
  812. } else {
  813. /* Allocate one buffer to hold both pfds and watchers arrays */
  814. const size_t pfd_size = sizeof(*pfds) * (pollset->fd_count + 2);
  815. const size_t watch_size = sizeof(*watchers) * (pollset->fd_count + 2);
  816. void *buf = gpr_malloc(pfd_size + watch_size);
  817. pfds = buf;
  818. watchers = (void *)((char *)buf + pfd_size);
  819. }
  820. fd_count = 0;
  821. pfd_count = 1;
  822. pfds[0].fd = GRPC_WAKEUP_FD_GET_READ_FD(&worker.wakeup_fd->fd);
  823. pfds[0].events = POLLIN;
  824. pfds[0].revents = 0;
  825. for (i = 0; i < pollset->fd_count; i++) {
  826. if (fd_is_orphaned(pollset->fds[i])) {
  827. GRPC_FD_UNREF(pollset->fds[i], "multipoller");
  828. } else {
  829. pollset->fds[fd_count++] = pollset->fds[i];
  830. watchers[pfd_count].fd = pollset->fds[i];
  831. GRPC_FD_REF(watchers[pfd_count].fd, "multipoller_start");
  832. pfds[pfd_count].fd = pollset->fds[i]->fd;
  833. pfds[pfd_count].revents = 0;
  834. pfd_count++;
  835. }
  836. }
  837. pollset->fd_count = fd_count;
  838. gpr_mu_unlock(&pollset->mu);
  839. for (i = 1; i < pfd_count; i++) {
  840. grpc_fd *fd = watchers[i].fd;
  841. pfds[i].events = (short)fd_begin_poll(fd, pollset, &worker, POLLIN,
  842. POLLOUT, &watchers[i]);
  843. GRPC_FD_UNREF(fd, "multipoller_start");
  844. }
  845. /* TODO(vpai): Consider first doing a 0 timeout poll here to avoid
  846. even going into the blocking annotation if possible */
  847. GRPC_SCHEDULING_START_BLOCKING_REGION;
  848. r = grpc_poll_function(pfds, pfd_count, timeout);
  849. GRPC_SCHEDULING_END_BLOCKING_REGION;
  850. if (r < 0) {
  851. if (errno != EINTR) {
  852. work_combine_error(&error, GRPC_OS_ERROR(errno, "poll"));
  853. }
  854. for (i = 1; i < pfd_count; i++) {
  855. if (watchers[i].fd == NULL) {
  856. fd_end_poll(exec_ctx, &watchers[i], 0, 0, NULL);
  857. } else {
  858. // Wake up all the file descriptors, if we have an invalid one
  859. // we can identify it on the next pollset_work()
  860. fd_end_poll(exec_ctx, &watchers[i], 1, 1, pollset);
  861. }
  862. }
  863. } else if (r == 0) {
  864. for (i = 1; i < pfd_count; i++) {
  865. fd_end_poll(exec_ctx, &watchers[i], 0, 0, NULL);
  866. }
  867. } else {
  868. if (pfds[0].revents & POLLIN_CHECK) {
  869. work_combine_error(
  870. &error, grpc_wakeup_fd_consume_wakeup(&worker.wakeup_fd->fd));
  871. }
  872. for (i = 1; i < pfd_count; i++) {
  873. if (watchers[i].fd == NULL) {
  874. fd_end_poll(exec_ctx, &watchers[i], 0, 0, NULL);
  875. } else {
  876. fd_end_poll(exec_ctx, &watchers[i], pfds[i].revents & POLLIN_CHECK,
  877. pfds[i].revents & POLLOUT_CHECK, pollset);
  878. }
  879. }
  880. }
  881. if (pfds != pollfd_space) {
  882. /* pfds and watchers are in the same memory block pointed to by pfds */
  883. gpr_free(pfds);
  884. }
  885. GPR_TIMER_END("maybe_work_and_unlock", 0);
  886. locked = 0;
  887. } else {
  888. GPR_TIMER_MARK("pollset_work.kicked_without_pollers", 0);
  889. pollset->kicked_without_pollers = 0;
  890. }
  891. /* Finished execution - start cleaning up.
  892. Note that we may arrive here from outside the enclosing while() loop.
  893. In that case we won't loop though as we haven't added worker to the
  894. worker list, which means nobody could ask us to re-evaluate polling). */
  895. done:
  896. if (!locked) {
  897. queued_work |= grpc_exec_ctx_flush(exec_ctx);
  898. gpr_mu_lock(&pollset->mu);
  899. locked = 1;
  900. }
  901. /* If we're forced to re-evaluate polling (via pollset_kick with
  902. GRPC_POLLSET_REEVALUATE_POLLING_ON_WAKEUP) then we land here and force
  903. a loop */
  904. if (worker.reevaluate_polling_on_wakeup && error == GRPC_ERROR_NONE) {
  905. worker.reevaluate_polling_on_wakeup = 0;
  906. pollset->kicked_without_pollers = 0;
  907. if (queued_work || worker.kicked_specifically) {
  908. /* If there's queued work on the list, then set the deadline to be
  909. immediate so we get back out of the polling loop quickly */
  910. deadline = gpr_inf_past(GPR_CLOCK_MONOTONIC);
  911. }
  912. keep_polling = 1;
  913. }
  914. if (keep_polling) {
  915. now = gpr_now(now.clock_type);
  916. }
  917. }
  918. gpr_tls_set(&g_current_thread_poller, 0);
  919. if (added_worker) {
  920. remove_worker(pollset, &worker);
  921. gpr_tls_set(&g_current_thread_worker, 0);
  922. }
  923. /* release wakeup fd to the local pool */
  924. worker.wakeup_fd->next = pollset->local_wakeup_cache;
  925. pollset->local_wakeup_cache = worker.wakeup_fd;
  926. /* check shutdown conditions */
  927. if (pollset->shutting_down) {
  928. if (pollset_has_workers(pollset)) {
  929. pollset_kick(pollset, NULL);
  930. } else if (!pollset->called_shutdown && !pollset_has_observers(pollset)) {
  931. pollset->called_shutdown = 1;
  932. gpr_mu_unlock(&pollset->mu);
  933. finish_shutdown(exec_ctx, pollset);
  934. grpc_exec_ctx_flush(exec_ctx);
  935. /* Continuing to access pollset here is safe -- it is the caller's
  936. * responsibility to not destroy when it has outstanding calls to
  937. * pollset_work.
  938. * TODO(dklempner): Can we refactor the shutdown logic to avoid this? */
  939. gpr_mu_lock(&pollset->mu);
  940. } else if (!grpc_closure_list_empty(pollset->idle_jobs)) {
  941. GRPC_CLOSURE_LIST_SCHED(exec_ctx, &pollset->idle_jobs);
  942. gpr_mu_unlock(&pollset->mu);
  943. grpc_exec_ctx_flush(exec_ctx);
  944. gpr_mu_lock(&pollset->mu);
  945. }
  946. }
  947. if (worker_hdl) *worker_hdl = NULL;
  948. GPR_TIMER_END("pollset_work", 0);
  949. GRPC_LOG_IF_ERROR("pollset_work", GRPC_ERROR_REF(error));
  950. return error;
  951. }
  952. static void pollset_shutdown(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset,
  953. grpc_closure *closure) {
  954. GPR_ASSERT(!pollset->shutting_down);
  955. pollset->shutting_down = 1;
  956. pollset->shutdown_done = closure;
  957. pollset_kick(pollset, GRPC_POLLSET_KICK_BROADCAST);
  958. if (!pollset_has_workers(pollset)) {
  959. GRPC_CLOSURE_LIST_SCHED(exec_ctx, &pollset->idle_jobs);
  960. }
  961. if (!pollset->called_shutdown && !pollset_has_observers(pollset)) {
  962. pollset->called_shutdown = 1;
  963. finish_shutdown(exec_ctx, pollset);
  964. }
  965. }
  966. static int poll_deadline_to_millis_timeout(gpr_timespec deadline,
  967. gpr_timespec now) {
  968. gpr_timespec timeout;
  969. static const int64_t max_spin_polling_us = 10;
  970. if (gpr_time_cmp(deadline, gpr_inf_future(deadline.clock_type)) == 0) {
  971. return -1;
  972. }
  973. if (gpr_time_cmp(deadline, gpr_time_add(now, gpr_time_from_micros(
  974. max_spin_polling_us,
  975. GPR_TIMESPAN))) <= 0) {
  976. return 0;
  977. }
  978. timeout = gpr_time_sub(deadline, now);
  979. return gpr_time_to_millis(gpr_time_add(
  980. timeout, gpr_time_from_nanos(GPR_NS_PER_MS - 1, GPR_TIMESPAN)));
  981. }
  982. /*******************************************************************************
  983. * pollset_set_posix.c
  984. */
  985. static grpc_pollset_set *pollset_set_create(void) {
  986. grpc_pollset_set *pollset_set = gpr_zalloc(sizeof(*pollset_set));
  987. gpr_mu_init(&pollset_set->mu);
  988. return pollset_set;
  989. }
  990. static void pollset_set_destroy(grpc_exec_ctx *exec_ctx,
  991. grpc_pollset_set *pollset_set) {
  992. size_t i;
  993. gpr_mu_destroy(&pollset_set->mu);
  994. for (i = 0; i < pollset_set->fd_count; i++) {
  995. GRPC_FD_UNREF(pollset_set->fds[i], "pollset_set");
  996. }
  997. for (i = 0; i < pollset_set->pollset_count; i++) {
  998. grpc_pollset *pollset = pollset_set->pollsets[i];
  999. gpr_mu_lock(&pollset->mu);
  1000. pollset->pollset_set_count--;
  1001. /* check shutdown */
  1002. if (pollset->shutting_down && !pollset->called_shutdown &&
  1003. !pollset_has_observers(pollset)) {
  1004. pollset->called_shutdown = 1;
  1005. gpr_mu_unlock(&pollset->mu);
  1006. finish_shutdown(exec_ctx, pollset);
  1007. } else {
  1008. gpr_mu_unlock(&pollset->mu);
  1009. }
  1010. }
  1011. gpr_free(pollset_set->pollsets);
  1012. gpr_free(pollset_set->pollset_sets);
  1013. gpr_free(pollset_set->fds);
  1014. gpr_free(pollset_set);
  1015. }
  1016. static void pollset_set_add_pollset(grpc_exec_ctx *exec_ctx,
  1017. grpc_pollset_set *pollset_set,
  1018. grpc_pollset *pollset) {
  1019. size_t i, j;
  1020. gpr_mu_lock(&pollset->mu);
  1021. pollset->pollset_set_count++;
  1022. gpr_mu_unlock(&pollset->mu);
  1023. gpr_mu_lock(&pollset_set->mu);
  1024. if (pollset_set->pollset_count == pollset_set->pollset_capacity) {
  1025. pollset_set->pollset_capacity =
  1026. GPR_MAX(8, 2 * pollset_set->pollset_capacity);
  1027. pollset_set->pollsets =
  1028. gpr_realloc(pollset_set->pollsets, pollset_set->pollset_capacity *
  1029. sizeof(*pollset_set->pollsets));
  1030. }
  1031. pollset_set->pollsets[pollset_set->pollset_count++] = pollset;
  1032. for (i = 0, j = 0; i < pollset_set->fd_count; i++) {
  1033. if (fd_is_orphaned(pollset_set->fds[i])) {
  1034. GRPC_FD_UNREF(pollset_set->fds[i], "pollset_set");
  1035. } else {
  1036. pollset_add_fd(exec_ctx, pollset, pollset_set->fds[i]);
  1037. pollset_set->fds[j++] = pollset_set->fds[i];
  1038. }
  1039. }
  1040. pollset_set->fd_count = j;
  1041. gpr_mu_unlock(&pollset_set->mu);
  1042. }
  1043. static void pollset_set_del_pollset(grpc_exec_ctx *exec_ctx,
  1044. grpc_pollset_set *pollset_set,
  1045. grpc_pollset *pollset) {
  1046. size_t i;
  1047. gpr_mu_lock(&pollset_set->mu);
  1048. for (i = 0; i < pollset_set->pollset_count; i++) {
  1049. if (pollset_set->pollsets[i] == pollset) {
  1050. pollset_set->pollset_count--;
  1051. GPR_SWAP(grpc_pollset *, pollset_set->pollsets[i],
  1052. pollset_set->pollsets[pollset_set->pollset_count]);
  1053. break;
  1054. }
  1055. }
  1056. gpr_mu_unlock(&pollset_set->mu);
  1057. gpr_mu_lock(&pollset->mu);
  1058. pollset->pollset_set_count--;
  1059. /* check shutdown */
  1060. if (pollset->shutting_down && !pollset->called_shutdown &&
  1061. !pollset_has_observers(pollset)) {
  1062. pollset->called_shutdown = 1;
  1063. gpr_mu_unlock(&pollset->mu);
  1064. finish_shutdown(exec_ctx, pollset);
  1065. } else {
  1066. gpr_mu_unlock(&pollset->mu);
  1067. }
  1068. }
  1069. static void pollset_set_add_pollset_set(grpc_exec_ctx *exec_ctx,
  1070. grpc_pollset_set *bag,
  1071. grpc_pollset_set *item) {
  1072. size_t i, j;
  1073. gpr_mu_lock(&bag->mu);
  1074. if (bag->pollset_set_count == bag->pollset_set_capacity) {
  1075. bag->pollset_set_capacity = GPR_MAX(8, 2 * bag->pollset_set_capacity);
  1076. bag->pollset_sets =
  1077. gpr_realloc(bag->pollset_sets,
  1078. bag->pollset_set_capacity * sizeof(*bag->pollset_sets));
  1079. }
  1080. bag->pollset_sets[bag->pollset_set_count++] = item;
  1081. for (i = 0, j = 0; i < bag->fd_count; i++) {
  1082. if (fd_is_orphaned(bag->fds[i])) {
  1083. GRPC_FD_UNREF(bag->fds[i], "pollset_set");
  1084. } else {
  1085. pollset_set_add_fd(exec_ctx, item, bag->fds[i]);
  1086. bag->fds[j++] = bag->fds[i];
  1087. }
  1088. }
  1089. bag->fd_count = j;
  1090. gpr_mu_unlock(&bag->mu);
  1091. }
  1092. static void pollset_set_del_pollset_set(grpc_exec_ctx *exec_ctx,
  1093. grpc_pollset_set *bag,
  1094. grpc_pollset_set *item) {
  1095. size_t i;
  1096. gpr_mu_lock(&bag->mu);
  1097. for (i = 0; i < bag->pollset_set_count; i++) {
  1098. if (bag->pollset_sets[i] == item) {
  1099. bag->pollset_set_count--;
  1100. GPR_SWAP(grpc_pollset_set *, bag->pollset_sets[i],
  1101. bag->pollset_sets[bag->pollset_set_count]);
  1102. break;
  1103. }
  1104. }
  1105. gpr_mu_unlock(&bag->mu);
  1106. }
  1107. static void pollset_set_add_fd(grpc_exec_ctx *exec_ctx,
  1108. grpc_pollset_set *pollset_set, grpc_fd *fd) {
  1109. size_t i;
  1110. gpr_mu_lock(&pollset_set->mu);
  1111. if (pollset_set->fd_count == pollset_set->fd_capacity) {
  1112. pollset_set->fd_capacity = GPR_MAX(8, 2 * pollset_set->fd_capacity);
  1113. pollset_set->fds = gpr_realloc(
  1114. pollset_set->fds, pollset_set->fd_capacity * sizeof(*pollset_set->fds));
  1115. }
  1116. GRPC_FD_REF(fd, "pollset_set");
  1117. pollset_set->fds[pollset_set->fd_count++] = fd;
  1118. for (i = 0; i < pollset_set->pollset_count; i++) {
  1119. pollset_add_fd(exec_ctx, pollset_set->pollsets[i], fd);
  1120. }
  1121. for (i = 0; i < pollset_set->pollset_set_count; i++) {
  1122. pollset_set_add_fd(exec_ctx, pollset_set->pollset_sets[i], fd);
  1123. }
  1124. gpr_mu_unlock(&pollset_set->mu);
  1125. }
  1126. static void pollset_set_del_fd(grpc_exec_ctx *exec_ctx,
  1127. grpc_pollset_set *pollset_set, grpc_fd *fd) {
  1128. size_t i;
  1129. gpr_mu_lock(&pollset_set->mu);
  1130. for (i = 0; i < pollset_set->fd_count; i++) {
  1131. if (pollset_set->fds[i] == fd) {
  1132. pollset_set->fd_count--;
  1133. GPR_SWAP(grpc_fd *, pollset_set->fds[i],
  1134. pollset_set->fds[pollset_set->fd_count]);
  1135. GRPC_FD_UNREF(fd, "pollset_set");
  1136. break;
  1137. }
  1138. }
  1139. for (i = 0; i < pollset_set->pollset_set_count; i++) {
  1140. pollset_set_del_fd(exec_ctx, pollset_set->pollset_sets[i], fd);
  1141. }
  1142. gpr_mu_unlock(&pollset_set->mu);
  1143. }
  1144. /*******************************************************************************
  1145. * Condition Variable polling extensions
  1146. */
  1147. static void decref_poll_args(poll_args *args) {
  1148. if (gpr_unref(&args->refcount)) {
  1149. gpr_free(args->fds);
  1150. gpr_cv_destroy(args->cv);
  1151. gpr_free(args->cv);
  1152. gpr_free(args);
  1153. }
  1154. }
  1155. // Poll in a background thread
  1156. static void run_poll(void *arg) {
  1157. int timeout, retval;
  1158. poll_args *pargs = (poll_args *)arg;
  1159. while (gpr_atm_no_barrier_load(&pargs->status) == INPROGRESS) {
  1160. if (pargs->timeout < 0) {
  1161. timeout = CV_POLL_PERIOD_MS;
  1162. } else {
  1163. timeout = GPR_MIN(CV_POLL_PERIOD_MS, pargs->timeout);
  1164. pargs->timeout -= timeout;
  1165. }
  1166. retval = g_cvfds.poll(pargs->fds, pargs->nfds, timeout);
  1167. if (retval != 0 || pargs->timeout == 0) {
  1168. pargs->retval = retval;
  1169. pargs->err = errno;
  1170. break;
  1171. }
  1172. }
  1173. gpr_mu_lock(&g_cvfds.mu);
  1174. if (gpr_atm_no_barrier_load(&pargs->status) == INPROGRESS) {
  1175. // Signal main thread that the poll completed
  1176. gpr_atm_no_barrier_store(&pargs->status, COMPLETED);
  1177. gpr_cv_signal(pargs->cv);
  1178. }
  1179. decref_poll_args(pargs);
  1180. g_cvfds.pollcount--;
  1181. if (g_cvfds.shutdown && g_cvfds.pollcount == 0) {
  1182. gpr_cv_signal(&g_cvfds.shutdown_complete);
  1183. }
  1184. gpr_mu_unlock(&g_cvfds.mu);
  1185. }
  1186. // This function overrides poll() to handle condition variable wakeup fds
  1187. static int cvfd_poll(struct pollfd *fds, nfds_t nfds, int timeout) {
  1188. unsigned int i;
  1189. int res, idx;
  1190. gpr_cv *pollcv;
  1191. cv_node *cvn, *prev;
  1192. int skip_poll = 0;
  1193. nfds_t nsockfds = 0;
  1194. gpr_thd_id t_id;
  1195. gpr_thd_options opt;
  1196. poll_args *pargs = NULL;
  1197. gpr_mu_lock(&g_cvfds.mu);
  1198. pollcv = gpr_malloc(sizeof(gpr_cv));
  1199. gpr_cv_init(pollcv);
  1200. for (i = 0; i < nfds; i++) {
  1201. fds[i].revents = 0;
  1202. if (fds[i].fd < 0 && (fds[i].events & POLLIN)) {
  1203. idx = FD_TO_IDX(fds[i].fd);
  1204. cvn = gpr_malloc(sizeof(cv_node));
  1205. cvn->cv = pollcv;
  1206. cvn->next = g_cvfds.cvfds[idx].cvs;
  1207. g_cvfds.cvfds[idx].cvs = cvn;
  1208. // Don't bother polling if a wakeup fd is ready
  1209. if (g_cvfds.cvfds[idx].is_set) {
  1210. skip_poll = 1;
  1211. }
  1212. } else if (fds[i].fd >= 0) {
  1213. nsockfds++;
  1214. }
  1215. }
  1216. res = 0;
  1217. if (!skip_poll && nsockfds > 0) {
  1218. pargs = gpr_malloc(sizeof(struct poll_args));
  1219. // Both the main thread and calling thread get a reference
  1220. gpr_ref_init(&pargs->refcount, 2);
  1221. pargs->cv = pollcv;
  1222. pargs->fds = gpr_malloc(sizeof(struct pollfd) * nsockfds);
  1223. pargs->nfds = nsockfds;
  1224. pargs->timeout = timeout;
  1225. pargs->retval = 0;
  1226. pargs->err = 0;
  1227. gpr_atm_no_barrier_store(&pargs->status, INPROGRESS);
  1228. idx = 0;
  1229. for (i = 0; i < nfds; i++) {
  1230. if (fds[i].fd >= 0) {
  1231. pargs->fds[idx].fd = fds[i].fd;
  1232. pargs->fds[idx].events = fds[i].events;
  1233. pargs->fds[idx].revents = 0;
  1234. idx++;
  1235. }
  1236. }
  1237. g_cvfds.pollcount++;
  1238. opt = gpr_thd_options_default();
  1239. gpr_thd_options_set_detached(&opt);
  1240. GPR_ASSERT(gpr_thd_new(&t_id, &run_poll, pargs, &opt));
  1241. // We want the poll() thread to trigger the deadline, so wait forever here
  1242. gpr_cv_wait(pollcv, &g_cvfds.mu, gpr_inf_future(GPR_CLOCK_MONOTONIC));
  1243. if (gpr_atm_no_barrier_load(&pargs->status) == COMPLETED) {
  1244. res = pargs->retval;
  1245. errno = pargs->err;
  1246. } else {
  1247. errno = 0;
  1248. gpr_atm_no_barrier_store(&pargs->status, CANCELLED);
  1249. }
  1250. } else if (!skip_poll) {
  1251. gpr_timespec deadline = gpr_now(GPR_CLOCK_REALTIME);
  1252. deadline =
  1253. gpr_time_add(deadline, gpr_time_from_millis(timeout, GPR_TIMESPAN));
  1254. gpr_cv_wait(pollcv, &g_cvfds.mu, deadline);
  1255. }
  1256. idx = 0;
  1257. for (i = 0; i < nfds; i++) {
  1258. if (fds[i].fd < 0 && (fds[i].events & POLLIN)) {
  1259. cvn = g_cvfds.cvfds[FD_TO_IDX(fds[i].fd)].cvs;
  1260. prev = NULL;
  1261. while (cvn->cv != pollcv) {
  1262. prev = cvn;
  1263. cvn = cvn->next;
  1264. GPR_ASSERT(cvn);
  1265. }
  1266. if (!prev) {
  1267. g_cvfds.cvfds[FD_TO_IDX(fds[i].fd)].cvs = cvn->next;
  1268. } else {
  1269. prev->next = cvn->next;
  1270. }
  1271. gpr_free(cvn);
  1272. if (g_cvfds.cvfds[FD_TO_IDX(fds[i].fd)].is_set) {
  1273. fds[i].revents = POLLIN;
  1274. if (res >= 0) res++;
  1275. }
  1276. } else if (!skip_poll && fds[i].fd >= 0 &&
  1277. gpr_atm_no_barrier_load(&pargs->status) == COMPLETED) {
  1278. fds[i].revents = pargs->fds[idx].revents;
  1279. idx++;
  1280. }
  1281. }
  1282. if (pargs) {
  1283. decref_poll_args(pargs);
  1284. } else {
  1285. gpr_cv_destroy(pollcv);
  1286. gpr_free(pollcv);
  1287. }
  1288. gpr_mu_unlock(&g_cvfds.mu);
  1289. return res;
  1290. }
  1291. static void global_cv_fd_table_init() {
  1292. gpr_mu_init(&g_cvfds.mu);
  1293. gpr_mu_lock(&g_cvfds.mu);
  1294. gpr_cv_init(&g_cvfds.shutdown_complete);
  1295. g_cvfds.shutdown = 0;
  1296. g_cvfds.pollcount = 0;
  1297. g_cvfds.size = CV_DEFAULT_TABLE_SIZE;
  1298. g_cvfds.cvfds = gpr_malloc(sizeof(fd_node) * CV_DEFAULT_TABLE_SIZE);
  1299. g_cvfds.free_fds = NULL;
  1300. for (int i = 0; i < CV_DEFAULT_TABLE_SIZE; i++) {
  1301. g_cvfds.cvfds[i].is_set = 0;
  1302. g_cvfds.cvfds[i].cvs = NULL;
  1303. g_cvfds.cvfds[i].next_free = g_cvfds.free_fds;
  1304. g_cvfds.free_fds = &g_cvfds.cvfds[i];
  1305. }
  1306. // Override the poll function with one that supports cvfds
  1307. g_cvfds.poll = grpc_poll_function;
  1308. grpc_poll_function = &cvfd_poll;
  1309. gpr_mu_unlock(&g_cvfds.mu);
  1310. }
  1311. static void global_cv_fd_table_shutdown() {
  1312. gpr_mu_lock(&g_cvfds.mu);
  1313. g_cvfds.shutdown = 1;
  1314. // Attempt to wait for all abandoned poll() threads to terminate
  1315. // Not doing so will result in reported memory leaks
  1316. if (g_cvfds.pollcount > 0) {
  1317. int res = gpr_cv_wait(&g_cvfds.shutdown_complete, &g_cvfds.mu,
  1318. gpr_time_add(gpr_now(GPR_CLOCK_REALTIME),
  1319. gpr_time_from_seconds(3, GPR_TIMESPAN)));
  1320. GPR_ASSERT(res == 0);
  1321. }
  1322. gpr_cv_destroy(&g_cvfds.shutdown_complete);
  1323. grpc_poll_function = g_cvfds.poll;
  1324. gpr_free(g_cvfds.cvfds);
  1325. gpr_mu_unlock(&g_cvfds.mu);
  1326. gpr_mu_destroy(&g_cvfds.mu);
  1327. }
  1328. /*******************************************************************************
  1329. * event engine binding
  1330. */
  1331. static void shutdown_engine(void) {
  1332. pollset_global_shutdown();
  1333. if (grpc_cv_wakeup_fds_enabled()) {
  1334. global_cv_fd_table_shutdown();
  1335. }
  1336. }
  1337. static const grpc_event_engine_vtable vtable = {
  1338. .pollset_size = sizeof(grpc_pollset),
  1339. .fd_create = fd_create,
  1340. .fd_wrapped_fd = fd_wrapped_fd,
  1341. .fd_orphan = fd_orphan,
  1342. .fd_shutdown = fd_shutdown,
  1343. .fd_is_shutdown = fd_is_shutdown,
  1344. .fd_notify_on_read = fd_notify_on_read,
  1345. .fd_notify_on_write = fd_notify_on_write,
  1346. .fd_get_read_notifier_pollset = fd_get_read_notifier_pollset,
  1347. .pollset_init = pollset_init,
  1348. .pollset_shutdown = pollset_shutdown,
  1349. .pollset_destroy = pollset_destroy,
  1350. .pollset_work = pollset_work,
  1351. .pollset_kick = pollset_kick,
  1352. .pollset_add_fd = pollset_add_fd,
  1353. .pollset_set_create = pollset_set_create,
  1354. .pollset_set_destroy = pollset_set_destroy,
  1355. .pollset_set_add_pollset = pollset_set_add_pollset,
  1356. .pollset_set_del_pollset = pollset_set_del_pollset,
  1357. .pollset_set_add_pollset_set = pollset_set_add_pollset_set,
  1358. .pollset_set_del_pollset_set = pollset_set_del_pollset_set,
  1359. .pollset_set_add_fd = pollset_set_add_fd,
  1360. .pollset_set_del_fd = pollset_set_del_fd,
  1361. .shutdown_engine = shutdown_engine,
  1362. };
  1363. const grpc_event_engine_vtable *grpc_init_poll_posix(bool explicit_request) {
  1364. if (!grpc_has_wakeup_fd()) {
  1365. return NULL;
  1366. }
  1367. if (!GRPC_LOG_IF_ERROR("pollset_global_init", pollset_global_init())) {
  1368. return NULL;
  1369. }
  1370. return &vtable;
  1371. }
  1372. const grpc_event_engine_vtable *grpc_init_poll_cv_posix(bool explicit_request) {
  1373. global_cv_fd_table_init();
  1374. grpc_enable_cv_wakeup_fds(1);
  1375. if (!GRPC_LOG_IF_ERROR("pollset_global_init", pollset_global_init())) {
  1376. global_cv_fd_table_shutdown();
  1377. grpc_enable_cv_wakeup_fds(0);
  1378. return NULL;
  1379. }
  1380. return &vtable;
  1381. }
  1382. #endif