2 // detail/impl/win_iocp_io_context.ipp
3 // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
5 // Copyright (c) 2003-2017 Christopher M. Kohlhoff (chris at kohlhoff dot com)
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)
11 #ifndef BOOST_ASIO_DETAIL_IMPL_WIN_IOCP_IO_CONTEXT_IPP
12 #define BOOST_ASIO_DETAIL_IMPL_WIN_IOCP_IO_CONTEXT_IPP
14 #if defined(_MSC_VER) && (_MSC_VER >= 1200)
16 #endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
18 #include <boost/asio/detail/config.hpp>
20 #if defined(BOOST_ASIO_HAS_IOCP)
22 #include <boost/asio/error.hpp>
23 #include <boost/asio/detail/cstdint.hpp>
24 #include <boost/asio/detail/handler_alloc_helpers.hpp>
25 #include <boost/asio/detail/handler_invoke_helpers.hpp>
26 #include <boost/asio/detail/limits.hpp>
27 #include <boost/asio/detail/throw_error.hpp>
28 #include <boost/asio/detail/win_iocp_io_context.hpp>
30 #include <boost/asio/detail/push_options.hpp>
36 struct win_iocp_io_context::work_finished_on_block_exit
38 ~work_finished_on_block_exit()
40 io_context_->work_finished();
43 win_iocp_io_context* io_context_;
46 struct win_iocp_io_context::timer_thread_function
50 while (::InterlockedExchangeAdd(&io_context_->shutdown_, 0) == 0)
52 if (::WaitForSingleObject(io_context_->waitable_timer_.handle,
53 INFINITE) == WAIT_OBJECT_0)
55 ::InterlockedExchange(&io_context_->dispatch_required_, 1);
56 ::PostQueuedCompletionStatus(io_context_->iocp_.handle,
57 0, wake_for_dispatch, 0);
62 win_iocp_io_context* io_context_;
65 win_iocp_io_context::win_iocp_io_context(
66 boost::asio::execution_context& ctx, int concurrency_hint)
67 : execution_context_service_base<win_iocp_io_context>(ctx),
71 stop_event_posted_(0),
73 gqcs_timeout_(get_gqcs_timeout()),
74 dispatch_required_(0),
75 concurrency_hint_(concurrency_hint)
77 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)));
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");
90 void win_iocp_io_context::shutdown()
92 ::InterlockedExchange(&shutdown_, 1);
94 if (timer_thread_.get())
96 LARGE_INTEGER timeout;
98 ::SetWaitableTimer(waitable_timer_.handle, &timeout, 1, 0, 0, FALSE);
101 while (::InterlockedExchangeAdd(&outstanding_work_, 0) > 0)
103 op_queue<win_iocp_operation> ops;
104 timer_queues_.get_all_timers(ops);
105 ops.push(completed_ops_);
108 while (win_iocp_operation* op = ops.front())
111 ::InterlockedDecrement(&outstanding_work_);
117 DWORD bytes_transferred = 0;
118 dword_ptr_t completion_key = 0;
119 LPOVERLAPPED overlapped = 0;
120 ::GetQueuedCompletionStatus(iocp_.handle, &bytes_transferred,
121 &completion_key, &overlapped, gqcs_timeout_);
124 ::InterlockedDecrement(&outstanding_work_);
125 static_cast<win_iocp_operation*>(overlapped)->destroy();
130 if (timer_thread_.get())
131 timer_thread_->join();
134 boost::system::error_code win_iocp_io_context::register_handle(
135 HANDLE handle, boost::system::error_code& ec)
137 if (::CreateIoCompletionPort(handle, iocp_.handle, 0, 0) == 0)
139 DWORD last_error = ::GetLastError();
140 ec = boost::system::error_code(last_error,
141 boost::asio::error::get_system_category());
145 ec = boost::system::error_code();
150 size_t win_iocp_io_context::run(boost::system::error_code& ec)
152 if (::InterlockedExchangeAdd(&outstanding_work_, 0) == 0)
155 ec = boost::system::error_code();
159 win_iocp_thread_info this_thread;
160 thread_call_stack::context ctx(this, this_thread);
163 while (do_one(INFINITE, ec))
164 if (n != (std::numeric_limits<size_t>::max)())
169 size_t win_iocp_io_context::run_one(boost::system::error_code& ec)
171 if (::InterlockedExchangeAdd(&outstanding_work_, 0) == 0)
174 ec = boost::system::error_code();
178 win_iocp_thread_info this_thread;
179 thread_call_stack::context ctx(this, this_thread);
181 return do_one(INFINITE, ec);
184 size_t win_iocp_io_context::wait_one(long usec, boost::system::error_code& ec)
186 if (::InterlockedExchangeAdd(&outstanding_work_, 0) == 0)
189 ec = boost::system::error_code();
193 win_iocp_thread_info this_thread;
194 thread_call_stack::context ctx(this, this_thread);
196 return do_one(usec < 0 ? INFINITE : ((usec - 1) / 1000 + 1), ec);
199 size_t win_iocp_io_context::poll(boost::system::error_code& ec)
201 if (::InterlockedExchangeAdd(&outstanding_work_, 0) == 0)
204 ec = boost::system::error_code();
208 win_iocp_thread_info this_thread;
209 thread_call_stack::context ctx(this, this_thread);
212 while (do_one(0, ec))
213 if (n != (std::numeric_limits<size_t>::max)())
218 size_t win_iocp_io_context::poll_one(boost::system::error_code& ec)
220 if (::InterlockedExchangeAdd(&outstanding_work_, 0) == 0)
223 ec = boost::system::error_code();
227 win_iocp_thread_info this_thread;
228 thread_call_stack::context ctx(this, this_thread);
230 return do_one(0, ec);
233 void win_iocp_io_context::stop()
235 if (::InterlockedExchange(&stopped_, 1) == 0)
237 if (::InterlockedExchange(&stop_event_posted_, 1) == 0)
239 if (!::PostQueuedCompletionStatus(iocp_.handle, 0, 0, 0))
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");
250 void win_iocp_io_context::post_deferred_completion(win_iocp_operation* op)
252 // Flag the operation as ready.
255 // Enqueue the operation on the I/O completion port.
256 if (!::PostQueuedCompletionStatus(iocp_.handle, 0, 0, op))
258 // Out of resources. Put on completed queue instead.
259 mutex::scoped_lock lock(dispatch_mutex_);
260 completed_ops_.push(op);
261 ::InterlockedExchange(&dispatch_required_, 1);
265 void win_iocp_io_context::post_deferred_completions(
266 op_queue<win_iocp_operation>& ops)
268 while (win_iocp_operation* op = ops.front())
272 // Flag the operation as ready.
275 // Enqueue the operation on the I/O completion port.
276 if (!::PostQueuedCompletionStatus(iocp_.handle, 0, 0, op))
278 // Out of resources. Put on completed queue instead.
279 mutex::scoped_lock lock(dispatch_mutex_);
280 completed_ops_.push(op);
281 completed_ops_.push(ops);
282 ::InterlockedExchange(&dispatch_required_, 1);
287 void win_iocp_io_context::abandon_operations(
288 op_queue<win_iocp_operation>& ops)
290 while (win_iocp_operation* op = ops.front())
293 ::InterlockedDecrement(&outstanding_work_);
298 void win_iocp_io_context::on_pending(win_iocp_operation* op)
300 if (::InterlockedCompareExchange(&op->ready_, 1, 0) == 1)
302 // Enqueue the operation on the I/O completion port.
303 if (!::PostQueuedCompletionStatus(iocp_.handle,
304 0, overlapped_contains_result, op))
306 // Out of resources. Put on completed queue instead.
307 mutex::scoped_lock lock(dispatch_mutex_);
308 completed_ops_.push(op);
309 ::InterlockedExchange(&dispatch_required_, 1);
314 void win_iocp_io_context::on_completion(win_iocp_operation* op,
315 DWORD last_error, DWORD bytes_transferred)
317 // Flag that the operation is ready for invocation.
320 // Store results in the OVERLAPPED structure.
321 op->Internal = reinterpret_cast<ulong_ptr_t>(
322 &boost::asio::error::get_system_category());
323 op->Offset = last_error;
324 op->OffsetHigh = bytes_transferred;
326 // Enqueue the operation on the I/O completion port.
327 if (!::PostQueuedCompletionStatus(iocp_.handle,
328 0, overlapped_contains_result, op))
330 // Out of resources. Put on completed queue instead.
331 mutex::scoped_lock lock(dispatch_mutex_);
332 completed_ops_.push(op);
333 ::InterlockedExchange(&dispatch_required_, 1);
337 void win_iocp_io_context::on_completion(win_iocp_operation* op,
338 const boost::system::error_code& ec, DWORD bytes_transferred)
340 // Flag that the operation is ready for invocation.
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;
348 // Enqueue the operation on the I/O completion port.
349 if (!::PostQueuedCompletionStatus(iocp_.handle,
350 0, overlapped_contains_result, op))
352 // Out of resources. Put on completed queue instead.
353 mutex::scoped_lock lock(dispatch_mutex_);
354 completed_ops_.push(op);
355 ::InterlockedExchange(&dispatch_required_, 1);
359 size_t win_iocp_io_context::do_one(DWORD msec, boost::system::error_code& ec)
363 // Try to acquire responsibility for dispatching timers and completed ops.
364 if (::InterlockedCompareExchange(&dispatch_required_, 0, 1) == 1)
366 mutex::scoped_lock lock(dispatch_mutex_);
368 // Dispatch pending timers and operations.
369 op_queue<win_iocp_operation> ops;
370 ops.push(completed_ops_);
371 timer_queues_.get_ready_timers(ops);
372 post_deferred_completions(ops);
376 // Get the next operation from the queue.
377 DWORD bytes_transferred = 0;
378 dword_ptr_t completion_key = 0;
379 LPOVERLAPPED overlapped = 0;
381 BOOL ok = ::GetQueuedCompletionStatus(iocp_.handle,
382 &bytes_transferred, &completion_key, &overlapped,
383 msec < gqcs_timeout_ ? msec : gqcs_timeout_);
384 DWORD last_error = ::GetLastError();
388 win_iocp_operation* op = static_cast<win_iocp_operation*>(overlapped);
389 boost::system::error_code result_ec(last_error,
390 boost::asio::error::get_system_category());
392 // We may have been passed the last_error and bytes_transferred in the
393 // OVERLAPPED structure itself.
394 if (completion_key == overlapped_contains_result)
396 result_ec = boost::system::error_code(static_cast<int>(op->Offset),
397 *reinterpret_cast<boost::system::error_category*>(op->Internal));
398 bytes_transferred = op->OffsetHigh;
401 // Otherwise ensure any result has been saved into the OVERLAPPED
405 op->Internal = reinterpret_cast<ulong_ptr_t>(&result_ec.category());
406 op->Offset = result_ec.value();
407 op->OffsetHigh = bytes_transferred;
410 // Dispatch the operation only if ready. The operation may not be ready
411 // if the initiating function (e.g. a call to WSARecv) has not yet
412 // returned. This is because the initiating function still wants access
413 // to the operation's OVERLAPPED structure.
414 if (::InterlockedCompareExchange(&op->ready_, 1, 0) == 1)
416 // Ensure the count of outstanding work is decremented on block exit.
417 work_finished_on_block_exit on_exit = { this };
420 op->complete(this, result_ec, bytes_transferred);
421 ec = boost::system::error_code();
427 if (last_error != WAIT_TIMEOUT)
429 ec = boost::system::error_code(last_error,
430 boost::asio::error::get_system_category());
434 // If we're waiting indefinitely we need to keep going until we get a
436 if (msec == INFINITE)
439 ec = boost::system::error_code();
442 else if (completion_key == wake_for_dispatch)
444 // We have been woken up to try to acquire responsibility for dispatching
445 // timers and completed operations.
449 // Indicate that there is no longer an in-flight stop event.
450 ::InterlockedExchange(&stop_event_posted_, 0);
452 // The stopped_ flag is always checked to ensure that any leftover
453 // stop events from a previous run invocation are ignored.
454 if (::InterlockedExchangeAdd(&stopped_, 0) != 0)
456 // Wake up next thread that is blocked on GetQueuedCompletionStatus.
457 if (::InterlockedExchange(&stop_event_posted_, 1) == 0)
459 if (!::PostQueuedCompletionStatus(iocp_.handle, 0, 0, 0))
461 last_error = ::GetLastError();
462 ec = boost::system::error_code(last_error,
463 boost::asio::error::get_system_category());
468 ec = boost::system::error_code();
475 DWORD win_iocp_io_context::get_gqcs_timeout()
477 OSVERSIONINFOEX osvi;
478 ZeroMemory(&osvi, sizeof(osvi));
479 osvi.dwOSVersionInfoSize = sizeof(osvi);
480 osvi.dwMajorVersion = 6ul;
482 const uint64_t condition_mask = ::VerSetConditionMask(
483 0, VER_MAJORVERSION, VER_GREATER_EQUAL);
485 if (!!::VerifyVersionInfo(&osvi, VER_MAJORVERSION, condition_mask))
488 return default_gqcs_timeout;
491 void win_iocp_io_context::do_add_timer_queue(timer_queue_base& queue)
493 mutex::scoped_lock lock(dispatch_mutex_);
495 timer_queues_.insert(&queue);
497 if (!waitable_timer_.handle)
499 waitable_timer_.handle = ::CreateWaitableTimer(0, FALSE, 0);
500 if (waitable_timer_.handle == 0)
502 DWORD last_error = ::GetLastError();
503 boost::system::error_code ec(last_error,
504 boost::asio::error::get_system_category());
505 boost::asio::detail::throw_error(ec, "timer");
508 LARGE_INTEGER timeout;
509 timeout.QuadPart = -max_timeout_usec;
510 timeout.QuadPart *= 10;
511 ::SetWaitableTimer(waitable_timer_.handle,
512 &timeout, max_timeout_msec, 0, 0, FALSE);
515 if (!timer_thread_.get())
517 timer_thread_function thread_function = { this };
518 timer_thread_.reset(new thread(thread_function, 65536));
522 void win_iocp_io_context::do_remove_timer_queue(timer_queue_base& queue)
524 mutex::scoped_lock lock(dispatch_mutex_);
526 timer_queues_.erase(&queue);
529 void win_iocp_io_context::update_timeout()
531 if (timer_thread_.get())
533 // There's no point updating the waitable timer if the new timeout period
534 // exceeds the maximum timeout. In that case, we might as well wait for the
535 // existing period of the timer to expire.
536 long timeout_usec = timer_queues_.wait_duration_usec(max_timeout_usec);
537 if (timeout_usec < max_timeout_usec)
539 LARGE_INTEGER timeout;
540 timeout.QuadPart = -timeout_usec;
541 timeout.QuadPart *= 10;
542 ::SetWaitableTimer(waitable_timer_.handle,
543 &timeout, max_timeout_msec, 0, 0, FALSE);
548 } // namespace detail
552 #include <boost/asio/detail/pop_options.hpp>
554 #endif // defined(BOOST_ASIO_HAS_IOCP)
556 #endif // BOOST_ASIO_DETAIL_IMPL_WIN_IOCP_IO_CONTEXT_IPP