kqueue_reactor.ipp 17 KB

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