kqueue_reactor.ipp 17 KB

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