kqueue_reactor.ipp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  1. //
  2. // detail/impl/kqueue_reactor.ipp
  3. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  4. //
  5. // Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com)
  6. // Copyright (c) 2005 Stefan Arentz (stefan at soze dot com)
  7. //
  8. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  9. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  10. //
  11. #ifndef BOOST_ASIO_DETAIL_IMPL_KQUEUE_REACTOR_IPP
  12. #define BOOST_ASIO_DETAIL_IMPL_KQUEUE_REACTOR_IPP
  13. #if defined(_MSC_VER) && (_MSC_VER >= 1200)
  14. # pragma once
  15. #endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
  16. #include <boost/asio/detail/config.hpp>
  17. #if defined(BOOST_ASIO_HAS_KQUEUE)
  18. #include <boost/asio/detail/kqueue_reactor.hpp>
  19. #include <boost/asio/detail/scheduler.hpp>
  20. #include <boost/asio/detail/throw_error.hpp>
  21. #include <boost/asio/error.hpp>
  22. #include <boost/asio/detail/push_options.hpp>
  23. #if defined(__NetBSD__)
  24. # define BOOST_ASIO_KQUEUE_EV_SET(ev, ident, filt, flags, fflags, data, udata) \
  25. EV_SET(ev, ident, filt, flags, fflags, data, \
  26. reinterpret_cast<intptr_t>(static_cast<void*>(udata)))
  27. #else
  28. # define BOOST_ASIO_KQUEUE_EV_SET(ev, ident, filt, flags, fflags, data, udata) \
  29. EV_SET(ev, ident, filt, flags, fflags, data, udata)
  30. #endif
  31. namespace boost {
  32. namespace asio {
  33. namespace detail {
  34. kqueue_reactor::kqueue_reactor(boost::asio::execution_context& ctx)
  35. : execution_context_service_base<kqueue_reactor>(ctx),
  36. scheduler_(use_service<scheduler>(ctx)),
  37. mutex_(BOOST_ASIO_CONCURRENCY_HINT_IS_LOCKING(
  38. REACTOR_REGISTRATION, scheduler_.concurrency_hint())),
  39. kqueue_fd_(do_kqueue_create()),
  40. interrupter_(),
  41. shutdown_(false),
  42. registered_descriptors_mutex_(mutex_.enabled())
  43. {
  44. struct kevent events[1];
  45. BOOST_ASIO_KQUEUE_EV_SET(&events[0], interrupter_.read_descriptor(),
  46. EVFILT_READ, EV_ADD, 0, 0, &interrupter_);
  47. if (::kevent(kqueue_fd_, events, 1, 0, 0, 0) == -1)
  48. {
  49. boost::system::error_code error(errno,
  50. boost::asio::error::get_system_category());
  51. boost::asio::detail::throw_error(error);
  52. }
  53. }
  54. kqueue_reactor::~kqueue_reactor()
  55. {
  56. close(kqueue_fd_);
  57. }
  58. void kqueue_reactor::shutdown()
  59. {
  60. mutex::scoped_lock lock(mutex_);
  61. shutdown_ = true;
  62. lock.unlock();
  63. op_queue<operation> ops;
  64. while (descriptor_state* state = registered_descriptors_.first())
  65. {
  66. for (int i = 0; i < max_ops; ++i)
  67. ops.push(state->op_queue_[i]);
  68. state->shutdown_ = true;
  69. registered_descriptors_.free(state);
  70. }
  71. timer_queues_.get_all_timers(ops);
  72. scheduler_.abandon_operations(ops);
  73. }
  74. void kqueue_reactor::notify_fork(
  75. boost::asio::execution_context::fork_event fork_ev)
  76. {
  77. if (fork_ev == boost::asio::execution_context::fork_child)
  78. {
  79. // The kqueue descriptor is automatically closed in the child.
  80. kqueue_fd_ = -1;
  81. kqueue_fd_ = do_kqueue_create();
  82. interrupter_.recreate();
  83. struct kevent events[2];
  84. BOOST_ASIO_KQUEUE_EV_SET(&events[0], interrupter_.read_descriptor(),
  85. EVFILT_READ, EV_ADD, 0, 0, &interrupter_);
  86. if (::kevent(kqueue_fd_, events, 1, 0, 0, 0) == -1)
  87. {
  88. boost::system::error_code ec(errno,
  89. boost::asio::error::get_system_category());
  90. boost::asio::detail::throw_error(ec, "kqueue interrupter registration");
  91. }
  92. // Re-register all descriptors with kqueue.
  93. mutex::scoped_lock descriptors_lock(registered_descriptors_mutex_);
  94. for (descriptor_state* state = registered_descriptors_.first();
  95. state != 0; state = state->next_)
  96. {
  97. if (state->num_kevents_ > 0)
  98. {
  99. BOOST_ASIO_KQUEUE_EV_SET(&events[0], state->descriptor_,
  100. EVFILT_READ, EV_ADD | EV_CLEAR, 0, 0, state);
  101. BOOST_ASIO_KQUEUE_EV_SET(&events[1], state->descriptor_,
  102. EVFILT_WRITE, EV_ADD | EV_CLEAR, 0, 0, state);
  103. if (::kevent(kqueue_fd_, events, state->num_kevents_, 0, 0, 0) == -1)
  104. {
  105. boost::system::error_code ec(errno,
  106. boost::asio::error::get_system_category());
  107. boost::asio::detail::throw_error(ec, "kqueue re-registration");
  108. }
  109. }
  110. }
  111. }
  112. }
  113. void kqueue_reactor::init_task()
  114. {
  115. scheduler_.init_task();
  116. }
  117. int kqueue_reactor::register_descriptor(socket_type descriptor,
  118. kqueue_reactor::per_descriptor_data& descriptor_data)
  119. {
  120. descriptor_data = allocate_descriptor_state();
  121. BOOST_ASIO_HANDLER_REACTOR_REGISTRATION((
  122. context(), static_cast<uintmax_t>(descriptor),
  123. reinterpret_cast<uintmax_t>(descriptor_data)));
  124. mutex::scoped_lock lock(descriptor_data->mutex_);
  125. descriptor_data->descriptor_ = descriptor;
  126. descriptor_data->num_kevents_ = 0;
  127. descriptor_data->shutdown_ = false;
  128. return 0;
  129. }
  130. int kqueue_reactor::register_internal_descriptor(
  131. int op_type, socket_type descriptor,
  132. kqueue_reactor::per_descriptor_data& descriptor_data, reactor_op* op)
  133. {
  134. descriptor_data = allocate_descriptor_state();
  135. BOOST_ASIO_HANDLER_REACTOR_REGISTRATION((
  136. context(), static_cast<uintmax_t>(descriptor),
  137. reinterpret_cast<uintmax_t>(descriptor_data)));
  138. mutex::scoped_lock lock(descriptor_data->mutex_);
  139. descriptor_data->descriptor_ = descriptor;
  140. descriptor_data->num_kevents_ = 1;
  141. descriptor_data->shutdown_ = false;
  142. descriptor_data->op_queue_[op_type].push(op);
  143. struct kevent events[1];
  144. BOOST_ASIO_KQUEUE_EV_SET(&events[0], descriptor, EVFILT_READ,
  145. EV_ADD | EV_CLEAR, 0, 0, descriptor_data);
  146. if (::kevent(kqueue_fd_, events, 1, 0, 0, 0) == -1)
  147. return errno;
  148. return 0;
  149. }
  150. void kqueue_reactor::move_descriptor(socket_type,
  151. kqueue_reactor::per_descriptor_data& target_descriptor_data,
  152. kqueue_reactor::per_descriptor_data& source_descriptor_data)
  153. {
  154. target_descriptor_data = source_descriptor_data;
  155. source_descriptor_data = 0;
  156. }
  157. void kqueue_reactor::start_op(int op_type, socket_type descriptor,
  158. kqueue_reactor::per_descriptor_data& descriptor_data, reactor_op* op,
  159. bool is_continuation, bool allow_speculative)
  160. {
  161. if (!descriptor_data)
  162. {
  163. op->ec_ = boost::asio::error::bad_descriptor;
  164. post_immediate_completion(op, is_continuation);
  165. return;
  166. }
  167. mutex::scoped_lock descriptor_lock(descriptor_data->mutex_);
  168. if (descriptor_data->shutdown_)
  169. {
  170. post_immediate_completion(op, is_continuation);
  171. return;
  172. }
  173. if (descriptor_data->op_queue_[op_type].empty())
  174. {
  175. static const int num_kevents[max_ops] = { 1, 2, 1 };
  176. if (allow_speculative
  177. && (op_type != read_op
  178. || descriptor_data->op_queue_[except_op].empty()))
  179. {
  180. if (op->perform())
  181. {
  182. descriptor_lock.unlock();
  183. scheduler_.post_immediate_completion(op, is_continuation);
  184. return;
  185. }
  186. if (descriptor_data->num_kevents_ < num_kevents[op_type])
  187. {
  188. struct kevent events[2];
  189. BOOST_ASIO_KQUEUE_EV_SET(&events[0], descriptor, EVFILT_READ,
  190. EV_ADD | EV_CLEAR, 0, 0, descriptor_data);
  191. BOOST_ASIO_KQUEUE_EV_SET(&events[1], descriptor, EVFILT_WRITE,
  192. EV_ADD | EV_CLEAR, 0, 0, descriptor_data);
  193. if (::kevent(kqueue_fd_, events, num_kevents[op_type], 0, 0, 0) != -1)
  194. {
  195. descriptor_data->num_kevents_ = num_kevents[op_type];
  196. }
  197. else
  198. {
  199. op->ec_ = boost::system::error_code(errno,
  200. boost::asio::error::get_system_category());
  201. scheduler_.post_immediate_completion(op, is_continuation);
  202. return;
  203. }
  204. }
  205. }
  206. else
  207. {
  208. if (descriptor_data->num_kevents_ < num_kevents[op_type])
  209. descriptor_data->num_kevents_ = num_kevents[op_type];
  210. struct kevent events[2];
  211. BOOST_ASIO_KQUEUE_EV_SET(&events[0], descriptor, EVFILT_READ,
  212. EV_ADD | EV_CLEAR, 0, 0, descriptor_data);
  213. BOOST_ASIO_KQUEUE_EV_SET(&events[1], descriptor, EVFILT_WRITE,
  214. EV_ADD | EV_CLEAR, 0, 0, descriptor_data);
  215. ::kevent(kqueue_fd_, events, descriptor_data->num_kevents_, 0, 0, 0);
  216. }
  217. }
  218. descriptor_data->op_queue_[op_type].push(op);
  219. scheduler_.work_started();
  220. }
  221. void kqueue_reactor::cancel_ops(socket_type,
  222. kqueue_reactor::per_descriptor_data& descriptor_data)
  223. {
  224. if (!descriptor_data)
  225. return;
  226. mutex::scoped_lock descriptor_lock(descriptor_data->mutex_);
  227. op_queue<operation> ops;
  228. for (int i = 0; i < max_ops; ++i)
  229. {
  230. while (reactor_op* op = descriptor_data->op_queue_[i].front())
  231. {
  232. op->ec_ = boost::asio::error::operation_aborted;
  233. descriptor_data->op_queue_[i].pop();
  234. ops.push(op);
  235. }
  236. }
  237. descriptor_lock.unlock();
  238. scheduler_.post_deferred_completions(ops);
  239. }
  240. void kqueue_reactor::deregister_descriptor(socket_type descriptor,
  241. kqueue_reactor::per_descriptor_data& descriptor_data, bool closing)
  242. {
  243. if (!descriptor_data)
  244. return;
  245. mutex::scoped_lock descriptor_lock(descriptor_data->mutex_);
  246. if (!descriptor_data->shutdown_)
  247. {
  248. if (closing)
  249. {
  250. // The descriptor will be automatically removed from the kqueue when it
  251. // is closed.
  252. }
  253. else
  254. {
  255. struct kevent events[2];
  256. BOOST_ASIO_KQUEUE_EV_SET(&events[0], descriptor,
  257. EVFILT_READ, EV_DELETE, 0, 0, 0);
  258. BOOST_ASIO_KQUEUE_EV_SET(&events[1], descriptor,
  259. EVFILT_WRITE, EV_DELETE, 0, 0, 0);
  260. ::kevent(kqueue_fd_, events, descriptor_data->num_kevents_, 0, 0, 0);
  261. }
  262. op_queue<operation> ops;
  263. for (int i = 0; i < max_ops; ++i)
  264. {
  265. while (reactor_op* op = descriptor_data->op_queue_[i].front())
  266. {
  267. op->ec_ = boost::asio::error::operation_aborted;
  268. descriptor_data->op_queue_[i].pop();
  269. ops.push(op);
  270. }
  271. }
  272. descriptor_data->descriptor_ = -1;
  273. descriptor_data->shutdown_ = true;
  274. descriptor_lock.unlock();
  275. BOOST_ASIO_HANDLER_REACTOR_DEREGISTRATION((
  276. context(), static_cast<uintmax_t>(descriptor),
  277. reinterpret_cast<uintmax_t>(descriptor_data)));
  278. scheduler_.post_deferred_completions(ops);
  279. // Leave descriptor_data set so that it will be freed by the subsequent
  280. // call to cleanup_descriptor_data.
  281. }
  282. else
  283. {
  284. // We are shutting down, so prevent cleanup_descriptor_data from freeing
  285. // the descriptor_data object and let the destructor free it instead.
  286. descriptor_data = 0;
  287. }
  288. }
  289. void kqueue_reactor::deregister_internal_descriptor(socket_type descriptor,
  290. kqueue_reactor::per_descriptor_data& descriptor_data)
  291. {
  292. if (!descriptor_data)
  293. return;
  294. mutex::scoped_lock descriptor_lock(descriptor_data->mutex_);
  295. if (!descriptor_data->shutdown_)
  296. {
  297. struct kevent events[2];
  298. BOOST_ASIO_KQUEUE_EV_SET(&events[0], descriptor,
  299. EVFILT_READ, EV_DELETE, 0, 0, 0);
  300. BOOST_ASIO_KQUEUE_EV_SET(&events[1], descriptor,
  301. EVFILT_WRITE, EV_DELETE, 0, 0, 0);
  302. ::kevent(kqueue_fd_, events, descriptor_data->num_kevents_, 0, 0, 0);
  303. op_queue<operation> ops;
  304. for (int i = 0; i < max_ops; ++i)
  305. ops.push(descriptor_data->op_queue_[i]);
  306. descriptor_data->descriptor_ = -1;
  307. descriptor_data->shutdown_ = true;
  308. descriptor_lock.unlock();
  309. BOOST_ASIO_HANDLER_REACTOR_DEREGISTRATION((
  310. context(), static_cast<uintmax_t>(descriptor),
  311. reinterpret_cast<uintmax_t>(descriptor_data)));
  312. // Leave descriptor_data set so that it will be freed by the subsequent
  313. // call to cleanup_descriptor_data.
  314. }
  315. else
  316. {
  317. // We are shutting down, so prevent cleanup_descriptor_data from freeing
  318. // the descriptor_data object and let the destructor free it instead.
  319. descriptor_data = 0;
  320. }
  321. }
  322. void kqueue_reactor::cleanup_descriptor_data(
  323. per_descriptor_data& descriptor_data)
  324. {
  325. if (descriptor_data)
  326. {
  327. free_descriptor_state(descriptor_data);
  328. descriptor_data = 0;
  329. }
  330. }
  331. void kqueue_reactor::run(long usec, op_queue<operation>& ops)
  332. {
  333. mutex::scoped_lock lock(mutex_);
  334. // Determine how long to block while waiting for events.
  335. timespec timeout_buf = { 0, 0 };
  336. timespec* timeout = usec ? get_timeout(usec, timeout_buf) : &timeout_buf;
  337. lock.unlock();
  338. // Block on the kqueue descriptor.
  339. struct kevent events[128];
  340. int num_events = kevent(kqueue_fd_, 0, 0, events, 128, timeout);
  341. #if defined(BOOST_ASIO_ENABLE_HANDLER_TRACKING)
  342. // Trace the waiting events.
  343. for (int i = 0; i < num_events; ++i)
  344. {
  345. void* ptr = reinterpret_cast<void*>(events[i].udata);
  346. if (ptr != &interrupter_)
  347. {
  348. unsigned event_mask = 0;
  349. switch (events[i].filter)
  350. {
  351. case EVFILT_READ:
  352. event_mask |= BOOST_ASIO_HANDLER_REACTOR_READ_EVENT;
  353. break;
  354. case EVFILT_WRITE:
  355. event_mask |= BOOST_ASIO_HANDLER_REACTOR_WRITE_EVENT;
  356. break;
  357. }
  358. if ((events[i].flags & (EV_ERROR | EV_OOBAND)) != 0)
  359. event_mask |= BOOST_ASIO_HANDLER_REACTOR_ERROR_EVENT;
  360. BOOST_ASIO_HANDLER_REACTOR_EVENTS((context(),
  361. reinterpret_cast<uintmax_t>(ptr), event_mask));
  362. }
  363. }
  364. #endif // defined(BOOST_ASIO_ENABLE_HANDLER_TRACKING)
  365. // Dispatch the waiting events.
  366. for (int i = 0; i < num_events; ++i)
  367. {
  368. void* ptr = reinterpret_cast<void*>(events[i].udata);
  369. if (ptr == &interrupter_)
  370. {
  371. interrupter_.reset();
  372. }
  373. else
  374. {
  375. descriptor_state* descriptor_data = static_cast<descriptor_state*>(ptr);
  376. mutex::scoped_lock descriptor_lock(descriptor_data->mutex_);
  377. if (events[i].filter == EVFILT_WRITE
  378. && descriptor_data->num_kevents_ == 2
  379. && descriptor_data->op_queue_[write_op].empty())
  380. {
  381. // Some descriptor types, like serial ports, don't seem to support
  382. // EV_CLEAR with EVFILT_WRITE. Since we have no pending write
  383. // operations we'll remove the EVFILT_WRITE registration here so that
  384. // we don't end up in a tight spin.
  385. struct kevent delete_events[1];
  386. BOOST_ASIO_KQUEUE_EV_SET(&delete_events[0],
  387. descriptor_data->descriptor_, EVFILT_WRITE, EV_DELETE, 0, 0, 0);
  388. ::kevent(kqueue_fd_, delete_events, 1, 0, 0, 0);
  389. descriptor_data->num_kevents_ = 1;
  390. }
  391. // Exception operations must be processed first to ensure that any
  392. // out-of-band data is read before normal data.
  393. #if defined(__NetBSD__)
  394. static const unsigned int filter[max_ops] =
  395. #else
  396. static const int filter[max_ops] =
  397. #endif
  398. { EVFILT_READ, EVFILT_WRITE, EVFILT_READ };
  399. for (int j = max_ops - 1; j >= 0; --j)
  400. {
  401. if (events[i].filter == filter[j])
  402. {
  403. if (j != except_op || events[i].flags & EV_OOBAND)
  404. {
  405. while (reactor_op* op = descriptor_data->op_queue_[j].front())
  406. {
  407. if (events[i].flags & EV_ERROR)
  408. {
  409. op->ec_ = boost::system::error_code(
  410. static_cast<int>(events[i].data),
  411. boost::asio::error::get_system_category());
  412. descriptor_data->op_queue_[j].pop();
  413. ops.push(op);
  414. }
  415. if (op->perform())
  416. {
  417. descriptor_data->op_queue_[j].pop();
  418. ops.push(op);
  419. }
  420. else
  421. break;
  422. }
  423. }
  424. }
  425. }
  426. }
  427. }
  428. lock.lock();
  429. timer_queues_.get_ready_timers(ops);
  430. }
  431. void kqueue_reactor::interrupt()
  432. {
  433. interrupter_.interrupt();
  434. }
  435. int kqueue_reactor::do_kqueue_create()
  436. {
  437. int fd = ::kqueue();
  438. if (fd == -1)
  439. {
  440. boost::system::error_code ec(errno,
  441. boost::asio::error::get_system_category());
  442. boost::asio::detail::throw_error(ec, "kqueue");
  443. }
  444. return fd;
  445. }
  446. kqueue_reactor::descriptor_state* kqueue_reactor::allocate_descriptor_state()
  447. {
  448. mutex::scoped_lock descriptors_lock(registered_descriptors_mutex_);
  449. return registered_descriptors_.alloc(BOOST_ASIO_CONCURRENCY_HINT_IS_LOCKING(
  450. REACTOR_IO, scheduler_.concurrency_hint()));
  451. }
  452. void kqueue_reactor::free_descriptor_state(kqueue_reactor::descriptor_state* s)
  453. {
  454. mutex::scoped_lock descriptors_lock(registered_descriptors_mutex_);
  455. registered_descriptors_.free(s);
  456. }
  457. void kqueue_reactor::do_add_timer_queue(timer_queue_base& queue)
  458. {
  459. mutex::scoped_lock lock(mutex_);
  460. timer_queues_.insert(&queue);
  461. }
  462. void kqueue_reactor::do_remove_timer_queue(timer_queue_base& queue)
  463. {
  464. mutex::scoped_lock lock(mutex_);
  465. timer_queues_.erase(&queue);
  466. }
  467. timespec* kqueue_reactor::get_timeout(long usec, timespec& ts)
  468. {
  469. // By default we will wait no longer than 5 minutes. This will ensure that
  470. // any changes to the system clock are detected after no longer than this.
  471. const long max_usec = 5 * 60 * 1000 * 1000;
  472. usec = timer_queues_.wait_duration_usec(
  473. (usec < 0 || max_usec < usec) ? max_usec : usec);
  474. ts.tv_sec = usec / 1000000;
  475. ts.tv_nsec = (usec % 1000000) * 1000;
  476. return &ts;
  477. }
  478. } // namespace detail
  479. } // namespace asio
  480. } // namespace boost
  481. #undef BOOST_ASIO_KQUEUE_EV_SET
  482. #include <boost/asio/detail/pop_options.hpp>
  483. #endif // defined(BOOST_ASIO_HAS_KQUEUE)
  484. #endif // BOOST_ASIO_DETAIL_IMPL_KQUEUE_REACTOR_IPP