1 //
2 // detail/win_iocp_io_service.hpp
3 // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4 //
5 // Copyright (c) 2003-2015 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 
11 #ifndef BOOST_ASIO_DETAIL_WIN_IOCP_IO_SERVICE_HPP
12 #define BOOST_ASIO_DETAIL_WIN_IOCP_IO_SERVICE_HPP
13 
14 #if defined(_MSC_VER) && (_MSC_VER >= 1200)
15 # pragma once
16 #endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
17 
18 #include <boost/asio/detail/config.hpp>
19 
20 #if defined(BOOST_ASIO_HAS_IOCP)
21 
22 #include <boost/asio/io_service.hpp>
23 #include <boost/asio/detail/call_stack.hpp>
24 #include <boost/asio/detail/limits.hpp>
25 #include <boost/asio/detail/mutex.hpp>
26 #include <boost/asio/detail/op_queue.hpp>
27 #include <boost/asio/detail/scoped_ptr.hpp>
28 #include <boost/asio/detail/socket_types.hpp>
29 #include <boost/asio/detail/thread.hpp>
30 #include <boost/asio/detail/timer_queue_base.hpp>
31 #include <boost/asio/detail/timer_queue_set.hpp>
32 #include <boost/asio/detail/wait_op.hpp>
33 #include <boost/asio/detail/win_iocp_operation.hpp>
34 #include <boost/asio/detail/win_iocp_thread_info.hpp>
35 
36 #include <boost/asio/detail/push_options.hpp>
37 
38 namespace boost {
39 namespace asio {
40 namespace detail {
41 
42 class wait_op;
43 
44 class win_iocp_io_service
45   : public boost::asio::detail::service_base<win_iocp_io_service>
46 {
47 public:
48 
49   // Constructor. Specifies a concurrency hint that is passed through to the
50   // underlying I/O completion port.
51   BOOST_ASIO_DECL win_iocp_io_service(boost::asio::io_service& io_service,
52       size_t concurrency_hint = 0);
53 
54   // Destroy all user-defined handler objects owned by the service.
55   BOOST_ASIO_DECL void shutdown_service();
56 
57   // Initialise the task. Nothing to do here.
init_task()58   void init_task()
59   {
60   }
61 
62   // Register a handle with the IO completion port.
63   BOOST_ASIO_DECL boost::system::error_code register_handle(
64       HANDLE handle, boost::system::error_code& ec);
65 
66   // Run the event loop until stopped or no more work.
67   BOOST_ASIO_DECL size_t run(boost::system::error_code& ec);
68 
69   // Run until stopped or one operation is performed.
70   BOOST_ASIO_DECL size_t run_one(boost::system::error_code& ec);
71 
72   // Poll for operations without blocking.
73   BOOST_ASIO_DECL size_t poll(boost::system::error_code& ec);
74 
75   // Poll for one operation without blocking.
76   BOOST_ASIO_DECL size_t poll_one(boost::system::error_code& ec);
77 
78   // Stop the event processing loop.
79   BOOST_ASIO_DECL void stop();
80 
81   // Determine whether the io_service is stopped.
stopped() const82   bool stopped() const
83   {
84     return ::InterlockedExchangeAdd(&stopped_, 0) != 0;
85   }
86 
87   // Reset in preparation for a subsequent run invocation.
reset()88   void reset()
89   {
90     ::InterlockedExchange(&stopped_, 0);
91   }
92 
93   // Notify that some work has started.
work_started()94   void work_started()
95   {
96     ::InterlockedIncrement(&outstanding_work_);
97   }
98 
99   // Notify that some work has finished.
work_finished()100   void work_finished()
101   {
102     if (::InterlockedDecrement(&outstanding_work_) == 0)
103       stop();
104   }
105 
106   // Return whether a handler can be dispatched immediately.
can_dispatch()107   bool can_dispatch()
108   {
109     return thread_call_stack::contains(this) != 0;
110   }
111 
112   // Request invocation of the given handler.
113   template <typename Handler>
114   void dispatch(Handler& handler);
115 
116   // Request invocation of the given handler and return immediately.
117   template <typename Handler>
118   void post(Handler& handler);
119 
120   // Request invocation of the given operation and return immediately. Assumes
121   // that work_started() has not yet been called for the operation.
post_immediate_completion(win_iocp_operation * op,bool)122   void post_immediate_completion(win_iocp_operation* op, bool)
123   {
124     work_started();
125     post_deferred_completion(op);
126   }
127 
128   // Request invocation of the given operation and return immediately. Assumes
129   // that work_started() was previously called for the operation.
130   BOOST_ASIO_DECL void post_deferred_completion(win_iocp_operation* op);
131 
132   // Request invocation of the given operation and return immediately. Assumes
133   // that work_started() was previously called for the operations.
134   BOOST_ASIO_DECL void post_deferred_completions(
135       op_queue<win_iocp_operation>& ops);
136 
137   // Request invocation of the given operation using the thread-private queue
138   // and return immediately. Assumes that work_started() has not yet been
139   // called for the operation.
post_private_immediate_completion(win_iocp_operation * op)140   void post_private_immediate_completion(win_iocp_operation* op)
141   {
142     post_immediate_completion(op, false);
143   }
144 
145   // Request invocation of the given operation using the thread-private queue
146   // and return immediately. Assumes that work_started() was previously called
147   // for the operation.
post_private_deferred_completion(win_iocp_operation * op)148   void post_private_deferred_completion(win_iocp_operation* op)
149   {
150     post_deferred_completion(op);
151   }
152 
153   // Process unfinished operations as part of a shutdown_service operation.
154   // Assumes that work_started() was previously called for the operations.
155   BOOST_ASIO_DECL void abandon_operations(op_queue<operation>& ops);
156 
157   // Called after starting an overlapped I/O operation that did not complete
158   // immediately. The caller must have already called work_started() prior to
159   // starting the operation.
160   BOOST_ASIO_DECL void on_pending(win_iocp_operation* op);
161 
162   // Called after starting an overlapped I/O operation that completed
163   // immediately. The caller must have already called work_started() prior to
164   // starting the operation.
165   BOOST_ASIO_DECL void on_completion(win_iocp_operation* op,
166       DWORD last_error = 0, DWORD bytes_transferred = 0);
167 
168   // Called after starting an overlapped I/O operation that completed
169   // immediately. The caller must have already called work_started() prior to
170   // starting the operation.
171   BOOST_ASIO_DECL void on_completion(win_iocp_operation* op,
172       const boost::system::error_code& ec, DWORD bytes_transferred = 0);
173 
174   // Add a new timer queue to the service.
175   template <typename Time_Traits>
176   void add_timer_queue(timer_queue<Time_Traits>& timer_queue);
177 
178   // Remove a timer queue from the service.
179   template <typename Time_Traits>
180   void remove_timer_queue(timer_queue<Time_Traits>& timer_queue);
181 
182   // Schedule a new operation in the given timer queue to expire at the
183   // specified absolute time.
184   template <typename Time_Traits>
185   void schedule_timer(timer_queue<Time_Traits>& queue,
186       const typename Time_Traits::time_type& time,
187       typename timer_queue<Time_Traits>::per_timer_data& timer, wait_op* op);
188 
189   // Cancel the timer associated with the given token. Returns the number of
190   // handlers that have been posted or dispatched.
191   template <typename Time_Traits>
192   std::size_t cancel_timer(timer_queue<Time_Traits>& queue,
193       typename timer_queue<Time_Traits>::per_timer_data& timer,
194       std::size_t max_cancelled = (std::numeric_limits<std::size_t>::max)());
195 
196 private:
197 #if defined(WINVER) && (WINVER < 0x0500)
198   typedef DWORD dword_ptr_t;
199   typedef ULONG ulong_ptr_t;
200 #else // defined(WINVER) && (WINVER < 0x0500)
201   typedef DWORD_PTR dword_ptr_t;
202   typedef ULONG_PTR ulong_ptr_t;
203 #endif // defined(WINVER) && (WINVER < 0x0500)
204 
205   // Dequeues at most one operation from the I/O completion port, and then
206   // executes it. Returns the number of operations that were dequeued (i.e.
207   // either 0 or 1).
208   BOOST_ASIO_DECL size_t do_one(bool block, boost::system::error_code& ec);
209 
210   // Helper to calculate the GetQueuedCompletionStatus timeout.
211   BOOST_ASIO_DECL static DWORD get_gqcs_timeout();
212 
213   // Helper function to add a new timer queue.
214   BOOST_ASIO_DECL void do_add_timer_queue(timer_queue_base& queue);
215 
216   // Helper function to remove a timer queue.
217   BOOST_ASIO_DECL void do_remove_timer_queue(timer_queue_base& queue);
218 
219   // Called to recalculate and update the timeout.
220   BOOST_ASIO_DECL void update_timeout();
221 
222   // Helper class to call work_finished() on block exit.
223   struct work_finished_on_block_exit;
224 
225   // Helper class for managing a HANDLE.
226   struct auto_handle
227   {
228     HANDLE handle;
auto_handleboost::asio::detail::win_iocp_io_service::auto_handle229     auto_handle() : handle(0) {}
~auto_handleboost::asio::detail::win_iocp_io_service::auto_handle230     ~auto_handle() { if (handle) ::CloseHandle(handle); }
231   };
232 
233   // The IO completion port used for queueing operations.
234   auto_handle iocp_;
235 
236   // The count of unfinished work.
237   long outstanding_work_;
238 
239   // Flag to indicate whether the event loop has been stopped.
240   mutable long stopped_;
241 
242   // Flag to indicate whether there is an in-flight stop event. Every event
243   // posted using PostQueuedCompletionStatus consumes non-paged pool, so to
244   // avoid exhausting this resouce we limit the number of outstanding events.
245   long stop_event_posted_;
246 
247   // Flag to indicate whether the service has been shut down.
248   long shutdown_;
249 
250   enum
251   {
252     // Timeout to use with GetQueuedCompletionStatus on older versions of
253     // Windows. Some versions of windows have a "bug" where a call to
254     // GetQueuedCompletionStatus can appear stuck even though there are events
255     // waiting on the queue. Using a timeout helps to work around the issue.
256     default_gqcs_timeout = 500,
257 
258     // Maximum waitable timer timeout, in milliseconds.
259     max_timeout_msec = 5 * 60 * 1000,
260 
261     // Maximum waitable timer timeout, in microseconds.
262     max_timeout_usec = max_timeout_msec * 1000,
263 
264     // Completion key value used to wake up a thread to dispatch timers or
265     // completed operations.
266     wake_for_dispatch = 1,
267 
268     // Completion key value to indicate that an operation has posted with the
269     // original last_error and bytes_transferred values stored in the fields of
270     // the OVERLAPPED structure.
271     overlapped_contains_result = 2
272   };
273 
274   // Timeout to use with GetQueuedCompletionStatus.
275   const DWORD gqcs_timeout_;
276 
277   // Function object for processing timeouts in a background thread.
278   struct timer_thread_function;
279   friend struct timer_thread_function;
280 
281   // Background thread used for processing timeouts.
282   scoped_ptr<thread> timer_thread_;
283 
284   // A waitable timer object used for waiting for timeouts.
285   auto_handle waitable_timer_;
286 
287   // Non-zero if timers or completed operations need to be dispatched.
288   long dispatch_required_;
289 
290   // Mutex for protecting access to the timer queues and completed operations.
291   mutex dispatch_mutex_;
292 
293   // The timer queues.
294   timer_queue_set timer_queues_;
295 
296   // The operations that are ready to dispatch.
297   op_queue<win_iocp_operation> completed_ops_;
298 
299   // Per-thread call stack to track the state of each thread in the io_service.
300   typedef call_stack<win_iocp_io_service,
301       win_iocp_thread_info> thread_call_stack;
302 };
303 
304 } // namespace detail
305 } // namespace asio
306 } // namespace boost
307 
308 #include <boost/asio/detail/pop_options.hpp>
309 
310 #include <boost/asio/detail/impl/win_iocp_io_service.hpp>
311 #if defined(BOOST_ASIO_HEADER_ONLY)
312 # include <boost/asio/detail/impl/win_iocp_io_service.ipp>
313 #endif // defined(BOOST_ASIO_HEADER_ONLY)
314 
315 #endif // defined(BOOST_ASIO_HAS_IOCP)
316 
317 #endif // BOOST_ASIO_DETAIL_WIN_IOCP_IO_SERVICE_HPP
318