epoll_reactor.ipp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818
  1. //
  2. // detail/impl/epoll_reactor.ipp
  3. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  4. //
  5. // Copyright (c) 2003-2022 Christopher M. Kohlhoff (chris at kohlhoff dot com)
  6. //
  7. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  8. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  9. //
  10. #ifndef ASIO_DETAIL_IMPL_EPOLL_REACTOR_IPP
  11. #define ASIO_DETAIL_IMPL_EPOLL_REACTOR_IPP
  12. #if defined(_MSC_VER) && (_MSC_VER >= 1200)
  13. # pragma once
  14. #endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
  15. #include "asio/detail/config.hpp"
  16. #if defined(ASIO_HAS_EPOLL)
  17. #include <cstddef>
  18. #include <sys/epoll.h>
  19. #include "asio/detail/epoll_reactor.hpp"
  20. #include "asio/detail/scheduler.hpp"
  21. #include "asio/detail/throw_error.hpp"
  22. #include "asio/error.hpp"
  23. #if defined(ASIO_HAS_TIMERFD)
  24. # include <sys/timerfd.h>
  25. #endif // defined(ASIO_HAS_TIMERFD)
  26. #include "asio/detail/push_options.hpp"
  27. namespace asio {
  28. namespace detail {
  29. epoll_reactor::epoll_reactor(asio::execution_context& ctx)
  30. : execution_context_service_base<epoll_reactor>(ctx),
  31. scheduler_(use_service<scheduler>(ctx)),
  32. mutex_(ASIO_CONCURRENCY_HINT_IS_LOCKING(
  33. REACTOR_REGISTRATION, scheduler_.concurrency_hint())),
  34. interrupter_(),
  35. epoll_fd_(do_epoll_create()),
  36. timer_fd_(do_timerfd_create()),
  37. shutdown_(false),
  38. registered_descriptors_mutex_(mutex_.enabled())
  39. {
  40. // Add the interrupter's descriptor to epoll.
  41. epoll_event ev = { 0, { 0 } };
  42. ev.events = EPOLLIN | EPOLLERR | EPOLLET;
  43. ev.data.ptr = &interrupter_;
  44. epoll_ctl(epoll_fd_, EPOLL_CTL_ADD, interrupter_.read_descriptor(), &ev);
  45. interrupter_.interrupt();
  46. // Add the timer descriptor to epoll.
  47. if (timer_fd_ != -1)
  48. {
  49. ev.events = EPOLLIN | EPOLLERR;
  50. ev.data.ptr = &timer_fd_;
  51. epoll_ctl(epoll_fd_, EPOLL_CTL_ADD, timer_fd_, &ev);
  52. }
  53. }
  54. epoll_reactor::~epoll_reactor()
  55. {
  56. if (epoll_fd_ != -1)
  57. close(epoll_fd_);
  58. if (timer_fd_ != -1)
  59. close(timer_fd_);
  60. }
  61. void epoll_reactor::shutdown()
  62. {
  63. mutex::scoped_lock lock(mutex_);
  64. shutdown_ = true;
  65. lock.unlock();
  66. op_queue<operation> ops;
  67. while (descriptor_state* state = registered_descriptors_.first())
  68. {
  69. for (int i = 0; i < max_ops; ++i)
  70. ops.push(state->op_queue_[i]);
  71. state->shutdown_ = true;
  72. registered_descriptors_.free(state);
  73. }
  74. timer_queues_.get_all_timers(ops);
  75. scheduler_.abandon_operations(ops);
  76. }
  77. void epoll_reactor::notify_fork(
  78. asio::execution_context::fork_event fork_ev)
  79. {
  80. if (fork_ev == asio::execution_context::fork_child)
  81. {
  82. if (epoll_fd_ != -1)
  83. ::close(epoll_fd_);
  84. epoll_fd_ = -1;
  85. epoll_fd_ = do_epoll_create();
  86. if (timer_fd_ != -1)
  87. ::close(timer_fd_);
  88. timer_fd_ = -1;
  89. timer_fd_ = do_timerfd_create();
  90. interrupter_.recreate();
  91. // Add the interrupter's descriptor to epoll.
  92. epoll_event ev = { 0, { 0 } };
  93. ev.events = EPOLLIN | EPOLLERR | EPOLLET;
  94. ev.data.ptr = &interrupter_;
  95. epoll_ctl(epoll_fd_, EPOLL_CTL_ADD, interrupter_.read_descriptor(), &ev);
  96. interrupter_.interrupt();
  97. // Add the timer descriptor to epoll.
  98. if (timer_fd_ != -1)
  99. {
  100. ev.events = EPOLLIN | EPOLLERR;
  101. ev.data.ptr = &timer_fd_;
  102. epoll_ctl(epoll_fd_, EPOLL_CTL_ADD, timer_fd_, &ev);
  103. }
  104. update_timeout();
  105. // Re-register all descriptors with epoll.
  106. mutex::scoped_lock descriptors_lock(registered_descriptors_mutex_);
  107. for (descriptor_state* state = registered_descriptors_.first();
  108. state != 0; state = state->next_)
  109. {
  110. ev.events = state->registered_events_;
  111. ev.data.ptr = state;
  112. int result = epoll_ctl(epoll_fd_, EPOLL_CTL_ADD, state->descriptor_, &ev);
  113. if (result != 0)
  114. {
  115. asio::error_code ec(errno,
  116. asio::error::get_system_category());
  117. asio::detail::throw_error(ec, "epoll re-registration");
  118. }
  119. }
  120. }
  121. }
  122. void epoll_reactor::init_task()
  123. {
  124. scheduler_.init_task();
  125. }
  126. int epoll_reactor::register_descriptor(socket_type descriptor,
  127. epoll_reactor::per_descriptor_data& descriptor_data)
  128. {
  129. descriptor_data = allocate_descriptor_state();
  130. ASIO_HANDLER_REACTOR_REGISTRATION((
  131. context(), static_cast<uintmax_t>(descriptor),
  132. reinterpret_cast<uintmax_t>(descriptor_data)));
  133. {
  134. mutex::scoped_lock descriptor_lock(descriptor_data->mutex_);
  135. descriptor_data->reactor_ = this;
  136. descriptor_data->descriptor_ = descriptor;
  137. descriptor_data->shutdown_ = false;
  138. for (int i = 0; i < max_ops; ++i)
  139. descriptor_data->try_speculative_[i] = true;
  140. }
  141. epoll_event ev = { 0, { 0 } };
  142. ev.events = EPOLLIN | EPOLLERR | EPOLLHUP | EPOLLPRI | EPOLLET;
  143. descriptor_data->registered_events_ = ev.events;
  144. ev.data.ptr = descriptor_data;
  145. int result = epoll_ctl(epoll_fd_, EPOLL_CTL_ADD, descriptor, &ev);
  146. if (result != 0)
  147. {
  148. if (errno == EPERM)
  149. {
  150. // This file descriptor type is not supported by epoll. However, if it is
  151. // a regular file then operations on it will not block. We will allow
  152. // this descriptor to be used and fail later if an operation on it would
  153. // otherwise require a trip through the reactor.
  154. descriptor_data->registered_events_ = 0;
  155. return 0;
  156. }
  157. return errno;
  158. }
  159. return 0;
  160. }
  161. int epoll_reactor::register_internal_descriptor(
  162. int op_type, socket_type descriptor,
  163. epoll_reactor::per_descriptor_data& descriptor_data, reactor_op* op)
  164. {
  165. descriptor_data = allocate_descriptor_state();
  166. ASIO_HANDLER_REACTOR_REGISTRATION((
  167. context(), static_cast<uintmax_t>(descriptor),
  168. reinterpret_cast<uintmax_t>(descriptor_data)));
  169. {
  170. mutex::scoped_lock descriptor_lock(descriptor_data->mutex_);
  171. descriptor_data->reactor_ = this;
  172. descriptor_data->descriptor_ = descriptor;
  173. descriptor_data->shutdown_ = false;
  174. descriptor_data->op_queue_[op_type].push(op);
  175. for (int i = 0; i < max_ops; ++i)
  176. descriptor_data->try_speculative_[i] = true;
  177. }
  178. epoll_event ev = { 0, { 0 } };
  179. ev.events = EPOLLIN | EPOLLERR | EPOLLHUP | EPOLLPRI | EPOLLET;
  180. descriptor_data->registered_events_ = ev.events;
  181. ev.data.ptr = descriptor_data;
  182. int result = epoll_ctl(epoll_fd_, EPOLL_CTL_ADD, descriptor, &ev);
  183. if (result != 0)
  184. return errno;
  185. return 0;
  186. }
  187. void epoll_reactor::move_descriptor(socket_type,
  188. epoll_reactor::per_descriptor_data& target_descriptor_data,
  189. epoll_reactor::per_descriptor_data& source_descriptor_data)
  190. {
  191. target_descriptor_data = source_descriptor_data;
  192. source_descriptor_data = 0;
  193. }
  194. void epoll_reactor::start_op(int op_type, socket_type descriptor,
  195. epoll_reactor::per_descriptor_data& descriptor_data, reactor_op* op,
  196. bool is_continuation, bool allow_speculative)
  197. {
  198. if (!descriptor_data)
  199. {
  200. op->ec_ = asio::error::bad_descriptor;
  201. post_immediate_completion(op, is_continuation);
  202. return;
  203. }
  204. mutex::scoped_lock descriptor_lock(descriptor_data->mutex_);
  205. if (descriptor_data->shutdown_)
  206. {
  207. post_immediate_completion(op, is_continuation);
  208. return;
  209. }
  210. if (descriptor_data->op_queue_[op_type].empty())
  211. {
  212. if (allow_speculative
  213. && (op_type != read_op
  214. || descriptor_data->op_queue_[except_op].empty()))
  215. {
  216. if (descriptor_data->try_speculative_[op_type])
  217. {
  218. if (reactor_op::status status = op->perform())
  219. {
  220. if (status == reactor_op::done_and_exhausted)
  221. if (descriptor_data->registered_events_ != 0)
  222. descriptor_data->try_speculative_[op_type] = false;
  223. descriptor_lock.unlock();
  224. scheduler_.post_immediate_completion(op, is_continuation);
  225. return;
  226. }
  227. }
  228. if (descriptor_data->registered_events_ == 0)
  229. {
  230. op->ec_ = asio::error::operation_not_supported;
  231. scheduler_.post_immediate_completion(op, is_continuation);
  232. return;
  233. }
  234. if (op_type == write_op)
  235. {
  236. if ((descriptor_data->registered_events_ & EPOLLOUT) == 0)
  237. {
  238. epoll_event ev = { 0, { 0 } };
  239. ev.events = descriptor_data->registered_events_ | EPOLLOUT;
  240. ev.data.ptr = descriptor_data;
  241. if (epoll_ctl(epoll_fd_, EPOLL_CTL_MOD, descriptor, &ev) == 0)
  242. {
  243. descriptor_data->registered_events_ |= ev.events;
  244. }
  245. else
  246. {
  247. op->ec_ = asio::error_code(errno,
  248. asio::error::get_system_category());
  249. scheduler_.post_immediate_completion(op, is_continuation);
  250. return;
  251. }
  252. }
  253. }
  254. }
  255. else if (descriptor_data->registered_events_ == 0)
  256. {
  257. op->ec_ = asio::error::operation_not_supported;
  258. scheduler_.post_immediate_completion(op, is_continuation);
  259. return;
  260. }
  261. else
  262. {
  263. if (op_type == write_op)
  264. {
  265. descriptor_data->registered_events_ |= EPOLLOUT;
  266. }
  267. epoll_event ev = { 0, { 0 } };
  268. ev.events = descriptor_data->registered_events_;
  269. ev.data.ptr = descriptor_data;
  270. epoll_ctl(epoll_fd_, EPOLL_CTL_MOD, descriptor, &ev);
  271. }
  272. }
  273. descriptor_data->op_queue_[op_type].push(op);
  274. scheduler_.work_started();
  275. }
  276. void epoll_reactor::cancel_ops(socket_type,
  277. epoll_reactor::per_descriptor_data& descriptor_data)
  278. {
  279. if (!descriptor_data)
  280. return;
  281. mutex::scoped_lock descriptor_lock(descriptor_data->mutex_);
  282. op_queue<operation> ops;
  283. for (int i = 0; i < max_ops; ++i)
  284. {
  285. while (reactor_op* op = descriptor_data->op_queue_[i].front())
  286. {
  287. op->ec_ = asio::error::operation_aborted;
  288. descriptor_data->op_queue_[i].pop();
  289. ops.push(op);
  290. }
  291. }
  292. descriptor_lock.unlock();
  293. scheduler_.post_deferred_completions(ops);
  294. }
  295. void epoll_reactor::cancel_ops_by_key(socket_type,
  296. epoll_reactor::per_descriptor_data& descriptor_data,
  297. int op_type, void* cancellation_key)
  298. {
  299. if (!descriptor_data)
  300. return;
  301. mutex::scoped_lock descriptor_lock(descriptor_data->mutex_);
  302. op_queue<operation> ops;
  303. op_queue<reactor_op> other_ops;
  304. while (reactor_op* op = descriptor_data->op_queue_[op_type].front())
  305. {
  306. descriptor_data->op_queue_[op_type].pop();
  307. if (op->cancellation_key_ == cancellation_key)
  308. {
  309. op->ec_ = asio::error::operation_aborted;
  310. ops.push(op);
  311. }
  312. else
  313. other_ops.push(op);
  314. }
  315. descriptor_data->op_queue_[op_type].push(other_ops);
  316. descriptor_lock.unlock();
  317. scheduler_.post_deferred_completions(ops);
  318. }
  319. void epoll_reactor::deregister_descriptor(socket_type descriptor,
  320. epoll_reactor::per_descriptor_data& descriptor_data, bool closing)
  321. {
  322. if (!descriptor_data)
  323. return;
  324. mutex::scoped_lock descriptor_lock(descriptor_data->mutex_);
  325. if (!descriptor_data->shutdown_)
  326. {
  327. if (closing)
  328. {
  329. // The descriptor will be automatically removed from the epoll set when
  330. // it is closed.
  331. }
  332. else if (descriptor_data->registered_events_ != 0)
  333. {
  334. epoll_event ev = { 0, { 0 } };
  335. epoll_ctl(epoll_fd_, EPOLL_CTL_DEL, descriptor, &ev);
  336. }
  337. op_queue<operation> ops;
  338. for (int i = 0; i < max_ops; ++i)
  339. {
  340. while (reactor_op* op = descriptor_data->op_queue_[i].front())
  341. {
  342. op->ec_ = asio::error::operation_aborted;
  343. descriptor_data->op_queue_[i].pop();
  344. ops.push(op);
  345. }
  346. }
  347. descriptor_data->descriptor_ = -1;
  348. descriptor_data->shutdown_ = true;
  349. descriptor_lock.unlock();
  350. ASIO_HANDLER_REACTOR_DEREGISTRATION((
  351. context(), static_cast<uintmax_t>(descriptor),
  352. reinterpret_cast<uintmax_t>(descriptor_data)));
  353. scheduler_.post_deferred_completions(ops);
  354. // Leave descriptor_data set so that it will be freed by the subsequent
  355. // call to cleanup_descriptor_data.
  356. }
  357. else
  358. {
  359. // We are shutting down, so prevent cleanup_descriptor_data from freeing
  360. // the descriptor_data object and let the destructor free it instead.
  361. descriptor_data = 0;
  362. }
  363. }
  364. void epoll_reactor::deregister_internal_descriptor(socket_type descriptor,
  365. epoll_reactor::per_descriptor_data& descriptor_data)
  366. {
  367. if (!descriptor_data)
  368. return;
  369. mutex::scoped_lock descriptor_lock(descriptor_data->mutex_);
  370. if (!descriptor_data->shutdown_)
  371. {
  372. epoll_event ev = { 0, { 0 } };
  373. epoll_ctl(epoll_fd_, EPOLL_CTL_DEL, descriptor, &ev);
  374. op_queue<operation> ops;
  375. for (int i = 0; i < max_ops; ++i)
  376. ops.push(descriptor_data->op_queue_[i]);
  377. descriptor_data->descriptor_ = -1;
  378. descriptor_data->shutdown_ = true;
  379. descriptor_lock.unlock();
  380. ASIO_HANDLER_REACTOR_DEREGISTRATION((
  381. context(), static_cast<uintmax_t>(descriptor),
  382. reinterpret_cast<uintmax_t>(descriptor_data)));
  383. // Leave descriptor_data set so that it will be freed by the subsequent
  384. // call to cleanup_descriptor_data.
  385. }
  386. else
  387. {
  388. // We are shutting down, so prevent cleanup_descriptor_data from freeing
  389. // the descriptor_data object and let the destructor free it instead.
  390. descriptor_data = 0;
  391. }
  392. }
  393. void epoll_reactor::cleanup_descriptor_data(
  394. per_descriptor_data& descriptor_data)
  395. {
  396. if (descriptor_data)
  397. {
  398. free_descriptor_state(descriptor_data);
  399. descriptor_data = 0;
  400. }
  401. }
  402. void epoll_reactor::run(long usec, op_queue<operation>& ops)
  403. {
  404. // This code relies on the fact that the scheduler queues the reactor task
  405. // behind all descriptor operations generated by this function. This means,
  406. // that by the time we reach this point, any previously returned descriptor
  407. // operations have already been dequeued. Therefore it is now safe for us to
  408. // reuse and return them for the scheduler to queue again.
  409. // Calculate timeout. Check the timer queues only if timerfd is not in use.
  410. int timeout;
  411. if (usec == 0)
  412. timeout = 0;
  413. else
  414. {
  415. timeout = (usec < 0) ? -1 : ((usec - 1) / 1000 + 1);
  416. if (timer_fd_ == -1)
  417. {
  418. mutex::scoped_lock lock(mutex_);
  419. timeout = get_timeout(timeout);
  420. }
  421. }
  422. // Block on the epoll descriptor.
  423. epoll_event events[128];
  424. int num_events = epoll_wait(epoll_fd_, events, 128, timeout);
  425. #if defined(ASIO_ENABLE_HANDLER_TRACKING)
  426. // Trace the waiting events.
  427. for (int i = 0; i < num_events; ++i)
  428. {
  429. void* ptr = events[i].data.ptr;
  430. if (ptr == &interrupter_)
  431. {
  432. // Ignore.
  433. }
  434. # if defined(ASIO_HAS_TIMERFD)
  435. else if (ptr == &timer_fd_)
  436. {
  437. // Ignore.
  438. }
  439. # endif // defined(ASIO_HAS_TIMERFD)
  440. else
  441. {
  442. unsigned event_mask = 0;
  443. if ((events[i].events & EPOLLIN) != 0)
  444. event_mask |= ASIO_HANDLER_REACTOR_READ_EVENT;
  445. if ((events[i].events & EPOLLOUT))
  446. event_mask |= ASIO_HANDLER_REACTOR_WRITE_EVENT;
  447. if ((events[i].events & (EPOLLERR | EPOLLHUP)) != 0)
  448. event_mask |= ASIO_HANDLER_REACTOR_ERROR_EVENT;
  449. ASIO_HANDLER_REACTOR_EVENTS((context(),
  450. reinterpret_cast<uintmax_t>(ptr), event_mask));
  451. }
  452. }
  453. #endif // defined(ASIO_ENABLE_HANDLER_TRACKING)
  454. #if defined(ASIO_HAS_TIMERFD)
  455. bool check_timers = (timer_fd_ == -1);
  456. #else // defined(ASIO_HAS_TIMERFD)
  457. bool check_timers = true;
  458. #endif // defined(ASIO_HAS_TIMERFD)
  459. // Dispatch the waiting events.
  460. for (int i = 0; i < num_events; ++i)
  461. {
  462. void* ptr = events[i].data.ptr;
  463. if (ptr == &interrupter_)
  464. {
  465. // No need to reset the interrupter since we're leaving the descriptor
  466. // in a ready-to-read state and relying on edge-triggered notifications
  467. // to make it so that we only get woken up when the descriptor's epoll
  468. // registration is updated.
  469. #if defined(ASIO_HAS_TIMERFD)
  470. if (timer_fd_ == -1)
  471. check_timers = true;
  472. #else // defined(ASIO_HAS_TIMERFD)
  473. check_timers = true;
  474. #endif // defined(ASIO_HAS_TIMERFD)
  475. }
  476. #if defined(ASIO_HAS_TIMERFD)
  477. else if (ptr == &timer_fd_)
  478. {
  479. check_timers = true;
  480. }
  481. #endif // defined(ASIO_HAS_TIMERFD)
  482. else
  483. {
  484. // The descriptor operation doesn't count as work in and of itself, so we
  485. // don't call work_started() here. This still allows the scheduler to
  486. // stop if the only remaining operations are descriptor operations.
  487. descriptor_state* descriptor_data = static_cast<descriptor_state*>(ptr);
  488. if (!ops.is_enqueued(descriptor_data))
  489. {
  490. descriptor_data->set_ready_events(events[i].events);
  491. ops.push(descriptor_data);
  492. }
  493. else
  494. {
  495. descriptor_data->add_ready_events(events[i].events);
  496. }
  497. }
  498. }
  499. if (check_timers)
  500. {
  501. mutex::scoped_lock common_lock(mutex_);
  502. timer_queues_.get_ready_timers(ops);
  503. #if defined(ASIO_HAS_TIMERFD)
  504. if (timer_fd_ != -1)
  505. {
  506. itimerspec new_timeout;
  507. itimerspec old_timeout;
  508. int flags = get_timeout(new_timeout);
  509. timerfd_settime(timer_fd_, flags, &new_timeout, &old_timeout);
  510. }
  511. #endif // defined(ASIO_HAS_TIMERFD)
  512. }
  513. }
  514. void epoll_reactor::interrupt()
  515. {
  516. epoll_event ev = { 0, { 0 } };
  517. ev.events = EPOLLIN | EPOLLERR | EPOLLET;
  518. ev.data.ptr = &interrupter_;
  519. epoll_ctl(epoll_fd_, EPOLL_CTL_MOD, interrupter_.read_descriptor(), &ev);
  520. }
  521. int epoll_reactor::do_epoll_create()
  522. {
  523. #if defined(EPOLL_CLOEXEC)
  524. int fd = epoll_create1(EPOLL_CLOEXEC);
  525. #else // defined(EPOLL_CLOEXEC)
  526. int fd = -1;
  527. errno = EINVAL;
  528. #endif // defined(EPOLL_CLOEXEC)
  529. if (fd == -1 && (errno == EINVAL || errno == ENOSYS))
  530. {
  531. fd = epoll_create(epoll_size);
  532. if (fd != -1)
  533. ::fcntl(fd, F_SETFD, FD_CLOEXEC);
  534. }
  535. if (fd == -1)
  536. {
  537. asio::error_code ec(errno,
  538. asio::error::get_system_category());
  539. asio::detail::throw_error(ec, "epoll");
  540. }
  541. return fd;
  542. }
  543. int epoll_reactor::do_timerfd_create()
  544. {
  545. #if defined(ASIO_HAS_TIMERFD)
  546. # if defined(TFD_CLOEXEC)
  547. int fd = timerfd_create(CLOCK_MONOTONIC, TFD_CLOEXEC);
  548. # else // defined(TFD_CLOEXEC)
  549. int fd = -1;
  550. errno = EINVAL;
  551. # endif // defined(TFD_CLOEXEC)
  552. if (fd == -1 && errno == EINVAL)
  553. {
  554. fd = timerfd_create(CLOCK_MONOTONIC, 0);
  555. if (fd != -1)
  556. ::fcntl(fd, F_SETFD, FD_CLOEXEC);
  557. }
  558. return fd;
  559. #else // defined(ASIO_HAS_TIMERFD)
  560. return -1;
  561. #endif // defined(ASIO_HAS_TIMERFD)
  562. }
  563. epoll_reactor::descriptor_state* epoll_reactor::allocate_descriptor_state()
  564. {
  565. mutex::scoped_lock descriptors_lock(registered_descriptors_mutex_);
  566. return registered_descriptors_.alloc(ASIO_CONCURRENCY_HINT_IS_LOCKING(
  567. REACTOR_IO, scheduler_.concurrency_hint()));
  568. }
  569. void epoll_reactor::free_descriptor_state(epoll_reactor::descriptor_state* s)
  570. {
  571. mutex::scoped_lock descriptors_lock(registered_descriptors_mutex_);
  572. registered_descriptors_.free(s);
  573. }
  574. void epoll_reactor::do_add_timer_queue(timer_queue_base& queue)
  575. {
  576. mutex::scoped_lock lock(mutex_);
  577. timer_queues_.insert(&queue);
  578. }
  579. void epoll_reactor::do_remove_timer_queue(timer_queue_base& queue)
  580. {
  581. mutex::scoped_lock lock(mutex_);
  582. timer_queues_.erase(&queue);
  583. }
  584. void epoll_reactor::update_timeout()
  585. {
  586. #if defined(ASIO_HAS_TIMERFD)
  587. if (timer_fd_ != -1)
  588. {
  589. itimerspec new_timeout;
  590. itimerspec old_timeout;
  591. int flags = get_timeout(new_timeout);
  592. timerfd_settime(timer_fd_, flags, &new_timeout, &old_timeout);
  593. return;
  594. }
  595. #endif // defined(ASIO_HAS_TIMERFD)
  596. interrupt();
  597. }
  598. int epoll_reactor::get_timeout(int msec)
  599. {
  600. // By default we will wait no longer than 5 minutes. This will ensure that
  601. // any changes to the system clock are detected after no longer than this.
  602. const int max_msec = 5 * 60 * 1000;
  603. return timer_queues_.wait_duration_msec(
  604. (msec < 0 || max_msec < msec) ? max_msec : msec);
  605. }
  606. #if defined(ASIO_HAS_TIMERFD)
  607. int epoll_reactor::get_timeout(itimerspec& ts)
  608. {
  609. ts.it_interval.tv_sec = 0;
  610. ts.it_interval.tv_nsec = 0;
  611. long usec = timer_queues_.wait_duration_usec(5 * 60 * 1000 * 1000);
  612. ts.it_value.tv_sec = usec / 1000000;
  613. ts.it_value.tv_nsec = usec ? (usec % 1000000) * 1000 : 1;
  614. return usec ? 0 : TFD_TIMER_ABSTIME;
  615. }
  616. #endif // defined(ASIO_HAS_TIMERFD)
  617. struct epoll_reactor::perform_io_cleanup_on_block_exit
  618. {
  619. explicit perform_io_cleanup_on_block_exit(epoll_reactor* r)
  620. : reactor_(r), first_op_(0)
  621. {
  622. }
  623. ~perform_io_cleanup_on_block_exit()
  624. {
  625. if (first_op_)
  626. {
  627. // Post the remaining completed operations for invocation.
  628. if (!ops_.empty())
  629. reactor_->scheduler_.post_deferred_completions(ops_);
  630. // A user-initiated operation has completed, but there's no need to
  631. // explicitly call work_finished() here. Instead, we'll take advantage of
  632. // the fact that the scheduler will call work_finished() once we return.
  633. }
  634. else
  635. {
  636. // No user-initiated operations have completed, so we need to compensate
  637. // for the work_finished() call that the scheduler will make once this
  638. // operation returns.
  639. reactor_->scheduler_.compensating_work_started();
  640. }
  641. }
  642. epoll_reactor* reactor_;
  643. op_queue<operation> ops_;
  644. operation* first_op_;
  645. };
  646. epoll_reactor::descriptor_state::descriptor_state(bool locking)
  647. : operation(&epoll_reactor::descriptor_state::do_complete),
  648. mutex_(locking)
  649. {
  650. }
  651. operation* epoll_reactor::descriptor_state::perform_io(uint32_t events)
  652. {
  653. mutex_.lock();
  654. perform_io_cleanup_on_block_exit io_cleanup(reactor_);
  655. mutex::scoped_lock descriptor_lock(mutex_, mutex::scoped_lock::adopt_lock);
  656. // Exception operations must be processed first to ensure that any
  657. // out-of-band data is read before normal data.
  658. static const int flag[max_ops] = { EPOLLIN, EPOLLOUT, EPOLLPRI };
  659. for (int j = max_ops - 1; j >= 0; --j)
  660. {
  661. if (events & (flag[j] | EPOLLERR | EPOLLHUP))
  662. {
  663. try_speculative_[j] = true;
  664. while (reactor_op* op = op_queue_[j].front())
  665. {
  666. if (reactor_op::status status = op->perform())
  667. {
  668. op_queue_[j].pop();
  669. io_cleanup.ops_.push(op);
  670. if (status == reactor_op::done_and_exhausted)
  671. {
  672. try_speculative_[j] = false;
  673. break;
  674. }
  675. }
  676. else
  677. break;
  678. }
  679. }
  680. }
  681. // The first operation will be returned for completion now. The others will
  682. // be posted for later by the io_cleanup object's destructor.
  683. io_cleanup.first_op_ = io_cleanup.ops_.front();
  684. io_cleanup.ops_.pop();
  685. return io_cleanup.first_op_;
  686. }
  687. void epoll_reactor::descriptor_state::do_complete(
  688. void* owner, operation* base,
  689. const asio::error_code& ec, std::size_t bytes_transferred)
  690. {
  691. if (owner)
  692. {
  693. descriptor_state* descriptor_data = static_cast<descriptor_state*>(base);
  694. uint32_t events = static_cast<uint32_t>(bytes_transferred);
  695. if (operation* op = descriptor_data->perform_io(events))
  696. {
  697. op->complete(owner, ec, 0);
  698. }
  699. }
  700. }
  701. } // namespace detail
  702. } // namespace asio
  703. #include "asio/detail/pop_options.hpp"
  704. #endif // defined(ASIO_HAS_EPOLL)
  705. #endif // ASIO_DETAIL_IMPL_EPOLL_REACTOR_IPP