dev_poll_reactor.hpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  1. //
  2. // dev_poll_reactor.hpp
  3. // ~~~~~~~~~~~~~~~~~~~~
  4. //
  5. // Copyright (c) 2003-2010 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 ASIO_DETAIL_DEV_POLL_REACTOR_HPP
  11. #define ASIO_DETAIL_DEV_POLL_REACTOR_HPP
  12. #if defined(_MSC_VER) && (_MSC_VER >= 1200)
  13. # pragma once
  14. #endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
  15. #include "asio/detail/push_options.hpp"
  16. #include "asio/detail/dev_poll_reactor_fwd.hpp"
  17. #if defined(ASIO_HAS_DEV_POLL)
  18. #include "asio/detail/push_options.hpp"
  19. #include <cstddef>
  20. #include <vector>
  21. #include <boost/config.hpp>
  22. #include <boost/date_time/posix_time/posix_time_types.hpp>
  23. #include <boost/throw_exception.hpp>
  24. #include <sys/devpoll.h>
  25. #include "asio/detail/pop_options.hpp"
  26. #include "asio/error.hpp"
  27. #include "asio/io_service.hpp"
  28. #include "asio/system_error.hpp"
  29. #include "asio/detail/hash_map.hpp"
  30. #include "asio/detail/mutex.hpp"
  31. #include "asio/detail/op_queue.hpp"
  32. #include "asio/detail/reactor_op.hpp"
  33. #include "asio/detail/reactor_op_queue.hpp"
  34. #include "asio/detail/select_interrupter.hpp"
  35. #include "asio/detail/service_base.hpp"
  36. #include "asio/detail/socket_types.hpp"
  37. #include "asio/detail/timer_op.hpp"
  38. #include "asio/detail/timer_queue_base.hpp"
  39. #include "asio/detail/timer_queue_fwd.hpp"
  40. #include "asio/detail/timer_queue_set.hpp"
  41. namespace asio {
  42. namespace detail {
  43. class dev_poll_reactor
  44. : public asio::detail::service_base<dev_poll_reactor>
  45. {
  46. public:
  47. enum { read_op = 0, write_op = 1,
  48. connect_op = 1, except_op = 2, max_ops = 3 };
  49. // Per-descriptor data.
  50. struct per_descriptor_data
  51. {
  52. };
  53. // Constructor.
  54. dev_poll_reactor(asio::io_service& io_service)
  55. : asio::detail::service_base<dev_poll_reactor>(io_service),
  56. io_service_(use_service<io_service_impl>(io_service)),
  57. mutex_(),
  58. dev_poll_fd_(do_dev_poll_create()),
  59. interrupter_(),
  60. shutdown_(false)
  61. {
  62. // Add the interrupter's descriptor to /dev/poll.
  63. ::pollfd ev = { 0 };
  64. ev.fd = interrupter_.read_descriptor();
  65. ev.events = POLLIN | POLLERR;
  66. ev.revents = 0;
  67. ::write(dev_poll_fd_, &ev, sizeof(ev));
  68. }
  69. // Destructor.
  70. ~dev_poll_reactor()
  71. {
  72. shutdown_service();
  73. ::close(dev_poll_fd_);
  74. }
  75. // Destroy all user-defined handler objects owned by the service.
  76. void shutdown_service()
  77. {
  78. asio::detail::mutex::scoped_lock lock(mutex_);
  79. shutdown_ = true;
  80. lock.unlock();
  81. op_queue<operation> ops;
  82. for (int i = 0; i < max_ops; ++i)
  83. op_queue_[i].get_all_operations(ops);
  84. timer_queues_.get_all_timers(ops);
  85. }
  86. // Initialise the task.
  87. void init_task()
  88. {
  89. io_service_.init_task();
  90. }
  91. // Register a socket with the reactor. Returns 0 on success, system error
  92. // code on failure.
  93. int register_descriptor(socket_type, per_descriptor_data&)
  94. {
  95. return 0;
  96. }
  97. // Start a new operation. The reactor operation will be performed when the
  98. // given descriptor is flagged as ready, or an error has occurred.
  99. void start_op(int op_type, socket_type descriptor,
  100. per_descriptor_data&, reactor_op* op, bool allow_speculative)
  101. {
  102. asio::detail::mutex::scoped_lock lock(mutex_);
  103. if (shutdown_)
  104. return;
  105. if (allow_speculative)
  106. {
  107. if (op_type != read_op || !op_queue_[except_op].has_operation(descriptor))
  108. {
  109. if (!op_queue_[op_type].has_operation(descriptor))
  110. {
  111. if (op->perform())
  112. {
  113. lock.unlock();
  114. io_service_.post_immediate_completion(op);
  115. return;
  116. }
  117. }
  118. }
  119. }
  120. bool first = op_queue_[op_type].enqueue_operation(descriptor, op);
  121. io_service_.work_started();
  122. if (first)
  123. {
  124. ::pollfd& ev = add_pending_event_change(descriptor);
  125. ev.events = POLLERR | POLLHUP;
  126. if (op_type == read_op
  127. || op_queue_[read_op].has_operation(descriptor))
  128. ev.events |= POLLIN;
  129. if (op_type == write_op
  130. || op_queue_[write_op].has_operation(descriptor))
  131. ev.events |= POLLOUT;
  132. if (op_type == except_op
  133. || op_queue_[except_op].has_operation(descriptor))
  134. ev.events |= POLLPRI;
  135. interrupter_.interrupt();
  136. }
  137. }
  138. // Cancel all operations associated with the given descriptor. The
  139. // handlers associated with the descriptor will be invoked with the
  140. // operation_aborted error.
  141. void cancel_ops(socket_type descriptor, per_descriptor_data&)
  142. {
  143. asio::detail::mutex::scoped_lock lock(mutex_);
  144. cancel_ops_unlocked(descriptor, asio::error::operation_aborted);
  145. }
  146. // Cancel any operations that are running against the descriptor and remove
  147. // its registration from the reactor.
  148. void close_descriptor(socket_type descriptor, per_descriptor_data&)
  149. {
  150. asio::detail::mutex::scoped_lock lock(mutex_);
  151. // Remove the descriptor from /dev/poll.
  152. ::pollfd& ev = add_pending_event_change(descriptor);
  153. ev.events = POLLREMOVE;
  154. interrupter_.interrupt();
  155. // Cancel any outstanding operations associated with the descriptor.
  156. cancel_ops_unlocked(descriptor, asio::error::operation_aborted);
  157. }
  158. // Add a new timer queue to the reactor.
  159. template <typename Time_Traits>
  160. void add_timer_queue(timer_queue<Time_Traits>& timer_queue)
  161. {
  162. asio::detail::mutex::scoped_lock lock(mutex_);
  163. timer_queues_.insert(&timer_queue);
  164. }
  165. // Remove a timer queue from the reactor.
  166. template <typename Time_Traits>
  167. void remove_timer_queue(timer_queue<Time_Traits>& timer_queue)
  168. {
  169. asio::detail::mutex::scoped_lock lock(mutex_);
  170. timer_queues_.erase(&timer_queue);
  171. }
  172. // Schedule a new operation in the given timer queue to expire at the
  173. // specified absolute time.
  174. template <typename Time_Traits>
  175. void schedule_timer(timer_queue<Time_Traits>& timer_queue,
  176. const typename Time_Traits::time_type& time, timer_op* op, void* token)
  177. {
  178. asio::detail::mutex::scoped_lock lock(mutex_);
  179. if (!shutdown_)
  180. {
  181. bool earliest = timer_queue.enqueue_timer(time, op, token);
  182. io_service_.work_started();
  183. if (earliest)
  184. interrupter_.interrupt();
  185. }
  186. }
  187. // Cancel the timer operations associated with the given token. Returns the
  188. // number of operations that have been posted or dispatched.
  189. template <typename Time_Traits>
  190. std::size_t cancel_timer(timer_queue<Time_Traits>& timer_queue, void* token)
  191. {
  192. asio::detail::mutex::scoped_lock lock(mutex_);
  193. op_queue<operation> ops;
  194. std::size_t n = timer_queue.cancel_timer(token, ops);
  195. lock.unlock();
  196. io_service_.post_deferred_completions(ops);
  197. return n;
  198. }
  199. // Run /dev/poll once until interrupted or events are ready to be dispatched.
  200. void run(bool block, op_queue<operation>& ops)
  201. {
  202. asio::detail::mutex::scoped_lock lock(mutex_);
  203. // We can return immediately if there's no work to do and the reactor is
  204. // not supposed to block.
  205. if (!block && op_queue_[read_op].empty() && op_queue_[write_op].empty()
  206. && op_queue_[except_op].empty() && timer_queues_.all_empty())
  207. return;
  208. // Write the pending event registration changes to the /dev/poll descriptor.
  209. std::size_t events_size = sizeof(::pollfd) * pending_event_changes_.size();
  210. if (events_size > 0)
  211. {
  212. errno = 0;
  213. int result = ::write(dev_poll_fd_,
  214. &pending_event_changes_[0], events_size);
  215. if (result != static_cast<int>(events_size))
  216. {
  217. asio::error_code ec = asio::error_code(
  218. errno, asio::error::get_system_category());
  219. for (std::size_t i = 0; i < pending_event_changes_.size(); ++i)
  220. {
  221. int descriptor = pending_event_changes_[i].fd;
  222. for (int j = 0; j < max_ops; ++j)
  223. op_queue_[j].cancel_operations(descriptor, ops, ec);
  224. }
  225. }
  226. pending_event_changes_.clear();
  227. pending_event_change_index_.clear();
  228. }
  229. int timeout = block ? get_timeout() : 0;
  230. lock.unlock();
  231. // Block on the /dev/poll descriptor.
  232. ::pollfd events[128] = { { 0 } };
  233. ::dvpoll dp = { 0 };
  234. dp.dp_fds = events;
  235. dp.dp_nfds = 128;
  236. dp.dp_timeout = timeout;
  237. int num_events = ::ioctl(dev_poll_fd_, DP_POLL, &dp);
  238. lock.lock();
  239. // Dispatch the waiting events.
  240. for (int i = 0; i < num_events; ++i)
  241. {
  242. int descriptor = events[i].fd;
  243. if (descriptor == interrupter_.read_descriptor())
  244. {
  245. interrupter_.reset();
  246. }
  247. else
  248. {
  249. bool more_reads = false;
  250. bool more_writes = false;
  251. bool more_except = false;
  252. // Exception operations must be processed first to ensure that any
  253. // out-of-band data is read before normal data.
  254. if (events[i].events & (POLLPRI | POLLERR | POLLHUP))
  255. more_except =
  256. op_queue_[except_op].perform_operations(descriptor, ops);
  257. else
  258. more_except = op_queue_[except_op].has_operation(descriptor);
  259. if (events[i].events & (POLLIN | POLLERR | POLLHUP))
  260. more_reads = op_queue_[read_op].perform_operations(descriptor, ops);
  261. else
  262. more_reads = op_queue_[read_op].has_operation(descriptor);
  263. if (events[i].events & (POLLOUT | POLLERR | POLLHUP))
  264. more_writes = op_queue_[write_op].perform_operations(descriptor, ops);
  265. else
  266. more_writes = op_queue_[write_op].has_operation(descriptor);
  267. if ((events[i].events & (POLLERR | POLLHUP)) != 0
  268. && !more_except && !more_reads && !more_writes)
  269. {
  270. // If we have an event and no operations associated with the
  271. // descriptor then we need to delete the descriptor from /dev/poll.
  272. // The poll operation can produce POLLHUP or POLLERR events when there
  273. // is no operation pending, so if we do not remove the descriptor we
  274. // can end up in a tight polling loop.
  275. ::pollfd ev = { 0 };
  276. ev.fd = descriptor;
  277. ev.events = POLLREMOVE;
  278. ev.revents = 0;
  279. ::write(dev_poll_fd_, &ev, sizeof(ev));
  280. }
  281. else
  282. {
  283. ::pollfd ev = { 0 };
  284. ev.fd = descriptor;
  285. ev.events = POLLERR | POLLHUP;
  286. if (more_reads)
  287. ev.events |= POLLIN;
  288. if (more_writes)
  289. ev.events |= POLLOUT;
  290. if (more_except)
  291. ev.events |= POLLPRI;
  292. ev.revents = 0;
  293. int result = ::write(dev_poll_fd_, &ev, sizeof(ev));
  294. if (result != sizeof(ev))
  295. {
  296. asio::error_code ec(errno,
  297. asio::error::get_system_category());
  298. for (int j = 0; j < max_ops; ++j)
  299. op_queue_[j].cancel_operations(descriptor, ops, ec);
  300. }
  301. }
  302. }
  303. }
  304. timer_queues_.get_ready_timers(ops);
  305. }
  306. // Interrupt the select loop.
  307. void interrupt()
  308. {
  309. interrupter_.interrupt();
  310. }
  311. private:
  312. // Create the /dev/poll file descriptor. Throws an exception if the descriptor
  313. // cannot be created.
  314. static int do_dev_poll_create()
  315. {
  316. int fd = ::open("/dev/poll", O_RDWR);
  317. if (fd == -1)
  318. {
  319. boost::throw_exception(
  320. asio::system_error(
  321. asio::error_code(errno,
  322. asio::error::get_system_category()),
  323. "/dev/poll"));
  324. }
  325. return fd;
  326. }
  327. // Get the timeout value for the /dev/poll DP_POLL operation. The timeout
  328. // value is returned as a number of milliseconds. A return value of -1
  329. // indicates that the poll should block indefinitely.
  330. int get_timeout()
  331. {
  332. // By default we will wait no longer than 5 minutes. This will ensure that
  333. // any changes to the system clock are detected after no longer than this.
  334. return timer_queues_.wait_duration_msec(5 * 60 * 1000);
  335. }
  336. // Cancel all operations associated with the given descriptor. The do_cancel
  337. // function of the handler objects will be invoked. This function does not
  338. // acquire the dev_poll_reactor's mutex.
  339. void cancel_ops_unlocked(socket_type descriptor,
  340. const asio::error_code& ec)
  341. {
  342. bool need_interrupt = false;
  343. op_queue<operation> ops;
  344. for (int i = 0; i < max_ops; ++i)
  345. need_interrupt = op_queue_[i].cancel_operations(
  346. descriptor, ops, ec) || need_interrupt;
  347. io_service_.post_deferred_completions(ops);
  348. if (need_interrupt)
  349. interrupter_.interrupt();
  350. }
  351. // Add a pending event entry for the given descriptor.
  352. ::pollfd& add_pending_event_change(int descriptor)
  353. {
  354. hash_map<int, std::size_t>::iterator iter
  355. = pending_event_change_index_.find(descriptor);
  356. if (iter == pending_event_change_index_.end())
  357. {
  358. std::size_t index = pending_event_changes_.size();
  359. pending_event_changes_.reserve(pending_event_changes_.size() + 1);
  360. pending_event_change_index_.insert(std::make_pair(descriptor, index));
  361. pending_event_changes_.push_back(::pollfd());
  362. pending_event_changes_[index].fd = descriptor;
  363. pending_event_changes_[index].revents = 0;
  364. return pending_event_changes_[index];
  365. }
  366. else
  367. {
  368. return pending_event_changes_[iter->second];
  369. }
  370. }
  371. // The io_service implementation used to post completions.
  372. io_service_impl& io_service_;
  373. // Mutex to protect access to internal data.
  374. asio::detail::mutex mutex_;
  375. // The /dev/poll file descriptor.
  376. int dev_poll_fd_;
  377. // Vector of /dev/poll events waiting to be written to the descriptor.
  378. std::vector< ::pollfd> pending_event_changes_;
  379. // Hash map to associate a descriptor with a pending event change index.
  380. hash_map<int, std::size_t> pending_event_change_index_;
  381. // The interrupter is used to break a blocking DP_POLL operation.
  382. select_interrupter interrupter_;
  383. // The queues of read, write and except operations.
  384. reactor_op_queue<socket_type> op_queue_[max_ops];
  385. // The timer queues.
  386. timer_queue_set timer_queues_;
  387. // Whether the service has been shut down.
  388. bool shutdown_;
  389. };
  390. } // namespace detail
  391. } // namespace asio
  392. #endif // defined(ASIO_HAS_DEV_POLL)
  393. #include "asio/detail/pop_options.hpp"
  394. #endif // ASIO_DETAIL_DEV_POLL_REACTOR_HPP