win_iocp_io_context.ipp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616
  1. //
  2. // detail/impl/win_iocp_io_context.ipp
  3. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  4. //
  5. // Copyright (c) 2003-2024 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 BOOST_ASIO_DETAIL_IMPL_WIN_IOCP_IO_CONTEXT_IPP
  11. #define BOOST_ASIO_DETAIL_IMPL_WIN_IOCP_IO_CONTEXT_IPP
  12. #if defined(_MSC_VER) && (_MSC_VER >= 1200)
  13. # pragma once
  14. #endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
  15. #include <boost/asio/detail/config.hpp>
  16. #if defined(BOOST_ASIO_HAS_IOCP)
  17. #include <boost/asio/error.hpp>
  18. #include <boost/asio/detail/cstdint.hpp>
  19. #include <boost/asio/detail/handler_alloc_helpers.hpp>
  20. #include <boost/asio/detail/limits.hpp>
  21. #include <boost/asio/detail/thread.hpp>
  22. #include <boost/asio/detail/throw_error.hpp>
  23. #include <boost/asio/detail/win_iocp_io_context.hpp>
  24. #include <boost/asio/detail/push_options.hpp>
  25. namespace boost {
  26. namespace asio {
  27. namespace detail {
  28. struct win_iocp_io_context::thread_function
  29. {
  30. explicit thread_function(win_iocp_io_context* s)
  31. : this_(s)
  32. {
  33. }
  34. void operator()()
  35. {
  36. boost::system::error_code ec;
  37. this_->run(ec);
  38. }
  39. win_iocp_io_context* this_;
  40. };
  41. struct win_iocp_io_context::work_finished_on_block_exit
  42. {
  43. ~work_finished_on_block_exit() noexcept(false)
  44. {
  45. io_context_->work_finished();
  46. }
  47. win_iocp_io_context* io_context_;
  48. };
  49. struct win_iocp_io_context::timer_thread_function
  50. {
  51. void operator()()
  52. {
  53. while (::InterlockedExchangeAdd(&io_context_->shutdown_, 0) == 0)
  54. {
  55. if (::WaitForSingleObject(io_context_->waitable_timer_.handle,
  56. INFINITE) == WAIT_OBJECT_0)
  57. {
  58. ::InterlockedExchange(&io_context_->dispatch_required_, 1);
  59. ::PostQueuedCompletionStatus(io_context_->iocp_.handle,
  60. 0, wake_for_dispatch, 0);
  61. }
  62. }
  63. }
  64. win_iocp_io_context* io_context_;
  65. };
  66. win_iocp_io_context::win_iocp_io_context(
  67. boost::asio::execution_context& ctx, int concurrency_hint, bool own_thread)
  68. : execution_context_service_base<win_iocp_io_context>(ctx),
  69. iocp_(),
  70. outstanding_work_(0),
  71. stopped_(0),
  72. stop_event_posted_(0),
  73. shutdown_(0),
  74. gqcs_timeout_(get_gqcs_timeout()),
  75. dispatch_required_(0),
  76. concurrency_hint_(concurrency_hint)
  77. {
  78. BOOST_ASIO_HANDLER_TRACKING_INIT;
  79. iocp_.handle = ::CreateIoCompletionPort(INVALID_HANDLE_VALUE, 0, 0,
  80. static_cast<DWORD>(concurrency_hint >= 0 ? concurrency_hint : DWORD(~0)));
  81. if (!iocp_.handle)
  82. {
  83. DWORD last_error = ::GetLastError();
  84. boost::system::error_code ec(last_error,
  85. boost::asio::error::get_system_category());
  86. boost::asio::detail::throw_error(ec, "iocp");
  87. }
  88. if (own_thread)
  89. {
  90. ::InterlockedIncrement(&outstanding_work_);
  91. thread_.reset(new boost::asio::detail::thread(thread_function(this)));
  92. }
  93. }
  94. win_iocp_io_context::~win_iocp_io_context()
  95. {
  96. if (thread_.get())
  97. {
  98. stop();
  99. thread_->join();
  100. thread_.reset();
  101. }
  102. }
  103. void win_iocp_io_context::shutdown()
  104. {
  105. ::InterlockedExchange(&shutdown_, 1);
  106. if (timer_thread_.get())
  107. {
  108. LARGE_INTEGER timeout;
  109. timeout.QuadPart = 1;
  110. ::SetWaitableTimer(waitable_timer_.handle, &timeout, 1, 0, 0, FALSE);
  111. }
  112. if (thread_.get())
  113. {
  114. stop();
  115. thread_->join();
  116. thread_.reset();
  117. ::InterlockedDecrement(&outstanding_work_);
  118. }
  119. while (::InterlockedExchangeAdd(&outstanding_work_, 0) > 0)
  120. {
  121. op_queue<win_iocp_operation> ops;
  122. timer_queues_.get_all_timers(ops);
  123. ops.push(completed_ops_);
  124. if (!ops.empty())
  125. {
  126. while (win_iocp_operation* op = ops.front())
  127. {
  128. ops.pop();
  129. ::InterlockedDecrement(&outstanding_work_);
  130. op->destroy();
  131. }
  132. }
  133. else
  134. {
  135. DWORD bytes_transferred = 0;
  136. dword_ptr_t completion_key = 0;
  137. LPOVERLAPPED overlapped = 0;
  138. ::GetQueuedCompletionStatus(iocp_.handle, &bytes_transferred,
  139. &completion_key, &overlapped, gqcs_timeout_);
  140. if (overlapped)
  141. {
  142. ::InterlockedDecrement(&outstanding_work_);
  143. static_cast<win_iocp_operation*>(overlapped)->destroy();
  144. }
  145. }
  146. }
  147. if (timer_thread_.get())
  148. {
  149. timer_thread_->join();
  150. timer_thread_.reset();
  151. }
  152. }
  153. boost::system::error_code win_iocp_io_context::register_handle(
  154. HANDLE handle, boost::system::error_code& ec)
  155. {
  156. if (::CreateIoCompletionPort(handle, iocp_.handle, 0, 0) == 0)
  157. {
  158. DWORD last_error = ::GetLastError();
  159. ec = boost::system::error_code(last_error,
  160. boost::asio::error::get_system_category());
  161. }
  162. else
  163. {
  164. ec = boost::system::error_code();
  165. }
  166. return ec;
  167. }
  168. size_t win_iocp_io_context::run(boost::system::error_code& ec)
  169. {
  170. if (::InterlockedExchangeAdd(&outstanding_work_, 0) == 0)
  171. {
  172. stop();
  173. ec = boost::system::error_code();
  174. return 0;
  175. }
  176. win_iocp_thread_info this_thread;
  177. thread_call_stack::context ctx(this, this_thread);
  178. size_t n = 0;
  179. while (do_one(INFINITE, this_thread, ec))
  180. if (n != (std::numeric_limits<size_t>::max)())
  181. ++n;
  182. return n;
  183. }
  184. size_t win_iocp_io_context::run_one(boost::system::error_code& ec)
  185. {
  186. if (::InterlockedExchangeAdd(&outstanding_work_, 0) == 0)
  187. {
  188. stop();
  189. ec = boost::system::error_code();
  190. return 0;
  191. }
  192. win_iocp_thread_info this_thread;
  193. thread_call_stack::context ctx(this, this_thread);
  194. return do_one(INFINITE, this_thread, ec);
  195. }
  196. size_t win_iocp_io_context::wait_one(long usec, boost::system::error_code& ec)
  197. {
  198. if (::InterlockedExchangeAdd(&outstanding_work_, 0) == 0)
  199. {
  200. stop();
  201. ec = boost::system::error_code();
  202. return 0;
  203. }
  204. win_iocp_thread_info this_thread;
  205. thread_call_stack::context ctx(this, this_thread);
  206. return do_one(usec < 0 ? INFINITE : ((usec - 1) / 1000 + 1), this_thread, ec);
  207. }
  208. size_t win_iocp_io_context::poll(boost::system::error_code& ec)
  209. {
  210. if (::InterlockedExchangeAdd(&outstanding_work_, 0) == 0)
  211. {
  212. stop();
  213. ec = boost::system::error_code();
  214. return 0;
  215. }
  216. win_iocp_thread_info this_thread;
  217. thread_call_stack::context ctx(this, this_thread);
  218. size_t n = 0;
  219. while (do_one(0, this_thread, ec))
  220. if (n != (std::numeric_limits<size_t>::max)())
  221. ++n;
  222. return n;
  223. }
  224. size_t win_iocp_io_context::poll_one(boost::system::error_code& ec)
  225. {
  226. if (::InterlockedExchangeAdd(&outstanding_work_, 0) == 0)
  227. {
  228. stop();
  229. ec = boost::system::error_code();
  230. return 0;
  231. }
  232. win_iocp_thread_info this_thread;
  233. thread_call_stack::context ctx(this, this_thread);
  234. return do_one(0, this_thread, ec);
  235. }
  236. void win_iocp_io_context::stop()
  237. {
  238. if (::InterlockedExchange(&stopped_, 1) == 0)
  239. {
  240. if (::InterlockedExchange(&stop_event_posted_, 1) == 0)
  241. {
  242. if (!::PostQueuedCompletionStatus(iocp_.handle, 0, 0, 0))
  243. {
  244. DWORD last_error = ::GetLastError();
  245. boost::system::error_code ec(last_error,
  246. boost::asio::error::get_system_category());
  247. boost::asio::detail::throw_error(ec, "pqcs");
  248. }
  249. }
  250. }
  251. }
  252. bool win_iocp_io_context::can_dispatch()
  253. {
  254. return thread_call_stack::contains(this) != 0;
  255. }
  256. void win_iocp_io_context::capture_current_exception()
  257. {
  258. if (thread_info_base* this_thread = thread_call_stack::contains(this))
  259. this_thread->capture_current_exception();
  260. }
  261. void win_iocp_io_context::post_deferred_completion(win_iocp_operation* op)
  262. {
  263. // Flag the operation as ready.
  264. op->ready_ = 1;
  265. // Enqueue the operation on the I/O completion port.
  266. if (!::PostQueuedCompletionStatus(iocp_.handle, 0, 0, op))
  267. {
  268. // Out of resources. Put on completed queue instead.
  269. mutex::scoped_lock lock(dispatch_mutex_);
  270. completed_ops_.push(op);
  271. ::InterlockedExchange(&dispatch_required_, 1);
  272. }
  273. }
  274. void win_iocp_io_context::post_deferred_completions(
  275. op_queue<win_iocp_operation>& ops)
  276. {
  277. while (win_iocp_operation* op = ops.front())
  278. {
  279. ops.pop();
  280. // Flag the operation as ready.
  281. op->ready_ = 1;
  282. // Enqueue the operation on the I/O completion port.
  283. if (!::PostQueuedCompletionStatus(iocp_.handle, 0, 0, op))
  284. {
  285. // Out of resources. Put on completed queue instead.
  286. mutex::scoped_lock lock(dispatch_mutex_);
  287. completed_ops_.push(op);
  288. completed_ops_.push(ops);
  289. ::InterlockedExchange(&dispatch_required_, 1);
  290. }
  291. }
  292. }
  293. void win_iocp_io_context::abandon_operations(
  294. op_queue<win_iocp_operation>& ops)
  295. {
  296. while (win_iocp_operation* op = ops.front())
  297. {
  298. ops.pop();
  299. ::InterlockedDecrement(&outstanding_work_);
  300. op->destroy();
  301. }
  302. }
  303. void win_iocp_io_context::on_pending(win_iocp_operation* op)
  304. {
  305. if (::InterlockedCompareExchange(&op->ready_, 1, 0) == 1)
  306. {
  307. // Enqueue the operation on the I/O completion port.
  308. if (!::PostQueuedCompletionStatus(iocp_.handle,
  309. 0, overlapped_contains_result, op))
  310. {
  311. // Out of resources. Put on completed queue instead.
  312. mutex::scoped_lock lock(dispatch_mutex_);
  313. completed_ops_.push(op);
  314. ::InterlockedExchange(&dispatch_required_, 1);
  315. }
  316. }
  317. }
  318. void win_iocp_io_context::on_completion(win_iocp_operation* op,
  319. DWORD last_error, DWORD bytes_transferred)
  320. {
  321. // Flag that the operation is ready for invocation.
  322. op->ready_ = 1;
  323. // Store results in the OVERLAPPED structure.
  324. op->Internal = reinterpret_cast<ulong_ptr_t>(
  325. &boost::asio::error::get_system_category());
  326. op->Offset = last_error;
  327. op->OffsetHigh = bytes_transferred;
  328. // Enqueue the operation on the I/O completion port.
  329. if (!::PostQueuedCompletionStatus(iocp_.handle,
  330. 0, overlapped_contains_result, op))
  331. {
  332. // Out of resources. Put on completed queue instead.
  333. mutex::scoped_lock lock(dispatch_mutex_);
  334. completed_ops_.push(op);
  335. ::InterlockedExchange(&dispatch_required_, 1);
  336. }
  337. }
  338. void win_iocp_io_context::on_completion(win_iocp_operation* op,
  339. const boost::system::error_code& ec, DWORD bytes_transferred)
  340. {
  341. // Flag that the operation is ready for invocation.
  342. op->ready_ = 1;
  343. // Store results in the OVERLAPPED structure.
  344. op->Internal = reinterpret_cast<ulong_ptr_t>(&ec.category());
  345. op->Offset = ec.value();
  346. op->OffsetHigh = bytes_transferred;
  347. // Enqueue the operation on the I/O completion port.
  348. if (!::PostQueuedCompletionStatus(iocp_.handle,
  349. 0, overlapped_contains_result, op))
  350. {
  351. // Out of resources. Put on completed queue instead.
  352. mutex::scoped_lock lock(dispatch_mutex_);
  353. completed_ops_.push(op);
  354. ::InterlockedExchange(&dispatch_required_, 1);
  355. }
  356. }
  357. size_t win_iocp_io_context::do_one(DWORD msec,
  358. win_iocp_thread_info& this_thread, boost::system::error_code& ec)
  359. {
  360. for (;;)
  361. {
  362. // Try to acquire responsibility for dispatching timers and completed ops.
  363. if (::InterlockedCompareExchange(&dispatch_required_, 0, 1) == 1)
  364. {
  365. mutex::scoped_lock lock(dispatch_mutex_);
  366. // Dispatch pending timers and operations.
  367. op_queue<win_iocp_operation> ops;
  368. ops.push(completed_ops_);
  369. timer_queues_.get_ready_timers(ops);
  370. post_deferred_completions(ops);
  371. update_timeout();
  372. }
  373. // Get the next operation from the queue.
  374. DWORD bytes_transferred = 0;
  375. dword_ptr_t completion_key = 0;
  376. LPOVERLAPPED overlapped = 0;
  377. ::SetLastError(0);
  378. BOOL ok = ::GetQueuedCompletionStatus(iocp_.handle,
  379. &bytes_transferred, &completion_key, &overlapped,
  380. msec < gqcs_timeout_ ? msec : gqcs_timeout_);
  381. DWORD last_error = ::GetLastError();
  382. if (overlapped)
  383. {
  384. win_iocp_operation* op = static_cast<win_iocp_operation*>(overlapped);
  385. boost::system::error_code result_ec(last_error,
  386. boost::asio::error::get_system_category());
  387. // We may have been passed the last_error and bytes_transferred in the
  388. // OVERLAPPED structure itself.
  389. if (completion_key == overlapped_contains_result)
  390. {
  391. result_ec = boost::system::error_code(static_cast<int>(op->Offset),
  392. *reinterpret_cast<boost::system::error_category*>(op->Internal));
  393. bytes_transferred = op->OffsetHigh;
  394. }
  395. // Otherwise ensure any result has been saved into the OVERLAPPED
  396. // structure.
  397. else
  398. {
  399. op->Internal = reinterpret_cast<ulong_ptr_t>(&result_ec.category());
  400. op->Offset = result_ec.value();
  401. op->OffsetHigh = bytes_transferred;
  402. }
  403. // Dispatch the operation only if ready. The operation may not be ready
  404. // if the initiating function (e.g. a call to WSARecv) has not yet
  405. // returned. This is because the initiating function still wants access
  406. // to the operation's OVERLAPPED structure.
  407. if (::InterlockedCompareExchange(&op->ready_, 1, 0) == 1)
  408. {
  409. // Ensure the count of outstanding work is decremented on block exit.
  410. work_finished_on_block_exit on_exit = { this };
  411. (void)on_exit;
  412. op->complete(this, result_ec, bytes_transferred);
  413. this_thread.rethrow_pending_exception();
  414. ec = boost::system::error_code();
  415. return 1;
  416. }
  417. }
  418. else if (!ok)
  419. {
  420. if (last_error != WAIT_TIMEOUT)
  421. {
  422. ec = boost::system::error_code(last_error,
  423. boost::asio::error::get_system_category());
  424. return 0;
  425. }
  426. // If we're waiting indefinitely we need to keep going until we get a
  427. // real handler.
  428. if (msec == INFINITE)
  429. continue;
  430. ec = boost::system::error_code();
  431. return 0;
  432. }
  433. else if (completion_key == wake_for_dispatch)
  434. {
  435. // We have been woken up to try to acquire responsibility for dispatching
  436. // timers and completed operations.
  437. }
  438. else
  439. {
  440. // Indicate that there is no longer an in-flight stop event.
  441. ::InterlockedExchange(&stop_event_posted_, 0);
  442. // The stopped_ flag is always checked to ensure that any leftover
  443. // stop events from a previous run invocation are ignored.
  444. if (::InterlockedExchangeAdd(&stopped_, 0) != 0)
  445. {
  446. // Wake up next thread that is blocked on GetQueuedCompletionStatus.
  447. if (::InterlockedExchange(&stop_event_posted_, 1) == 0)
  448. {
  449. if (!::PostQueuedCompletionStatus(iocp_.handle, 0, 0, 0))
  450. {
  451. last_error = ::GetLastError();
  452. ec = boost::system::error_code(last_error,
  453. boost::asio::error::get_system_category());
  454. return 0;
  455. }
  456. }
  457. ec = boost::system::error_code();
  458. return 0;
  459. }
  460. }
  461. }
  462. }
  463. DWORD win_iocp_io_context::get_gqcs_timeout()
  464. {
  465. #if !defined(_WIN32_WINNT) || (_WIN32_WINNT < 0x0600)
  466. OSVERSIONINFOEX osvi;
  467. ZeroMemory(&osvi, sizeof(osvi));
  468. osvi.dwOSVersionInfoSize = sizeof(osvi);
  469. osvi.dwMajorVersion = 6ul;
  470. const uint64_t condition_mask = ::VerSetConditionMask(
  471. 0, VER_MAJORVERSION, VER_GREATER_EQUAL);
  472. if (!!::VerifyVersionInfo(&osvi, VER_MAJORVERSION, condition_mask))
  473. return INFINITE;
  474. return default_gqcs_timeout;
  475. #else // !defined(_WIN32_WINNT) || (_WIN32_WINNT < 0x0600)
  476. return INFINITE;
  477. #endif // !defined(_WIN32_WINNT) || (_WIN32_WINNT < 0x0600)
  478. }
  479. void win_iocp_io_context::do_add_timer_queue(timer_queue_base& queue)
  480. {
  481. mutex::scoped_lock lock(dispatch_mutex_);
  482. timer_queues_.insert(&queue);
  483. if (!waitable_timer_.handle)
  484. {
  485. waitable_timer_.handle = ::CreateWaitableTimer(0, FALSE, 0);
  486. if (waitable_timer_.handle == 0)
  487. {
  488. DWORD last_error = ::GetLastError();
  489. boost::system::error_code ec(last_error,
  490. boost::asio::error::get_system_category());
  491. boost::asio::detail::throw_error(ec, "timer");
  492. }
  493. LARGE_INTEGER timeout;
  494. timeout.QuadPart = -max_timeout_usec;
  495. timeout.QuadPart *= 10;
  496. ::SetWaitableTimer(waitable_timer_.handle,
  497. &timeout, max_timeout_msec, 0, 0, FALSE);
  498. }
  499. if (!timer_thread_.get())
  500. {
  501. timer_thread_function thread_function = { this };
  502. timer_thread_.reset(new thread(thread_function, 65536));
  503. }
  504. }
  505. void win_iocp_io_context::do_remove_timer_queue(timer_queue_base& queue)
  506. {
  507. mutex::scoped_lock lock(dispatch_mutex_);
  508. timer_queues_.erase(&queue);
  509. }
  510. void win_iocp_io_context::update_timeout()
  511. {
  512. if (timer_thread_.get())
  513. {
  514. // There's no point updating the waitable timer if the new timeout period
  515. // exceeds the maximum timeout. In that case, we might as well wait for the
  516. // existing period of the timer to expire.
  517. long timeout_usec = timer_queues_.wait_duration_usec(max_timeout_usec);
  518. if (timeout_usec < max_timeout_usec)
  519. {
  520. LARGE_INTEGER timeout;
  521. timeout.QuadPart = -timeout_usec;
  522. timeout.QuadPart *= 10;
  523. ::SetWaitableTimer(waitable_timer_.handle,
  524. &timeout, max_timeout_msec, 0, 0, FALSE);
  525. }
  526. }
  527. }
  528. } // namespace detail
  529. } // namespace asio
  530. } // namespace boost
  531. #include <boost/asio/detail/pop_options.hpp>
  532. #endif // defined(BOOST_ASIO_HAS_IOCP)
  533. #endif // BOOST_ASIO_DETAIL_IMPL_WIN_IOCP_IO_CONTEXT_IPP