win_iocp_io_context.ipp 16 KB

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