win_iocp_io_context.ipp 16 KB

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