97.81% Lines (179/183) 100.00% Functions (14/14)
TLA Baseline Branch
Line Hits Code Line Hits Code
1   // 1   //
2   // Copyright (c) 2026 Steve Gerbino 2   // Copyright (c) 2026 Steve Gerbino
3   // Copyright (c) 2026 Michael Vandeberg 3   // Copyright (c) 2026 Michael Vandeberg
4   // 4   //
5   // Distributed under the Boost Software License, Version 1.0. (See accompanying 5   // Distributed under the Boost Software License, Version 1.0. (See accompanying
6   // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) 6   // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
7   // 7   //
8   // Official repository: https://github.com/cppalliance/corosio 8   // Official repository: https://github.com/cppalliance/corosio
9   // 9   //
10   10  
11   #ifndef BOOST_COROSIO_NATIVE_DETAIL_EPOLL_EPOLL_SCHEDULER_HPP 11   #ifndef BOOST_COROSIO_NATIVE_DETAIL_EPOLL_EPOLL_SCHEDULER_HPP
12   #define BOOST_COROSIO_NATIVE_DETAIL_EPOLL_EPOLL_SCHEDULER_HPP 12   #define BOOST_COROSIO_NATIVE_DETAIL_EPOLL_EPOLL_SCHEDULER_HPP
13   13  
14   #include <boost/corosio/detail/platform.hpp> 14   #include <boost/corosio/detail/platform.hpp>
15   15  
16   #if BOOST_COROSIO_HAS_EPOLL 16   #if BOOST_COROSIO_HAS_EPOLL
17   17  
18   #include <boost/corosio/detail/config.hpp> 18   #include <boost/corosio/detail/config.hpp>
19   #include <boost/capy/ex/execution_context.hpp> 19   #include <boost/capy/ex/execution_context.hpp>
20   20  
21   #include <boost/corosio/native/detail/reactor/reactor_scheduler.hpp> 21   #include <boost/corosio/native/detail/reactor/reactor_scheduler.hpp>
22   #include <boost/corosio/native/detail/reactor/reactor_signal_pipe.hpp> 22   #include <boost/corosio/native/detail/reactor/reactor_signal_pipe.hpp>
23   23  
24   #include <boost/corosio/native/detail/epoll/epoll_traits.hpp> 24   #include <boost/corosio/native/detail/epoll/epoll_traits.hpp>
25   #include <boost/corosio/detail/timer_service.hpp> 25   #include <boost/corosio/detail/timer_service.hpp>
26   #include <boost/corosio/native/detail/make_err.hpp> 26   #include <boost/corosio/native/detail/make_err.hpp>
27   27  
28   #include <boost/corosio/detail/except.hpp> 28   #include <boost/corosio/detail/except.hpp>
29   29  
30   #include <atomic> 30   #include <atomic>
31   #include <chrono> 31   #include <chrono>
32   #include <cstdint> 32   #include <cstdint>
33   #include <limits> 33   #include <limits>
34   #include <mutex> 34   #include <mutex>
35   #include <vector> 35   #include <vector>
36   36  
37   #include <errno.h> 37   #include <errno.h>
38   #include <sys/epoll.h> 38   #include <sys/epoll.h>
39   #include <sys/eventfd.h> 39   #include <sys/eventfd.h>
40   #include <sys/timerfd.h> 40   #include <sys/timerfd.h>
41   #include <unistd.h> 41   #include <unistd.h>
42   42  
43   namespace boost::corosio::detail { 43   namespace boost::corosio::detail {
44   44  
45   /** Linux scheduler using epoll for I/O multiplexing. 45   /** Linux scheduler using epoll for I/O multiplexing.
46   46  
47   This scheduler implements the scheduler interface using Linux epoll 47   This scheduler implements the scheduler interface using Linux epoll
48   for efficient I/O event notification. It uses a single reactor model 48   for efficient I/O event notification. It uses a single reactor model
49   where one thread runs epoll_wait while other threads 49   where one thread runs epoll_wait while other threads
50   wait on a condition variable for handler work. This design provides: 50   wait on a condition variable for handler work. This design provides:
51   51  
52   - Handler parallelism: N posted handlers can execute on N threads 52   - Handler parallelism: N posted handlers can execute on N threads
53   - No thundering herd: condition_variable wakes exactly one thread 53   - No thundering herd: condition_variable wakes exactly one thread
54   - IOCP parity: Behavior matches Windows I/O completion port semantics 54   - IOCP parity: Behavior matches Windows I/O completion port semantics
55   55  
56   When threads call run(), they first try to execute queued handlers. 56   When threads call run(), they first try to execute queued handlers.
57   If the queue is empty and no reactor is running, one thread becomes 57   If the queue is empty and no reactor is running, one thread becomes
58   the reactor and runs epoll_wait. Other threads wait on a condition 58   the reactor and runs epoll_wait. Other threads wait on a condition
59   variable until handlers are available. 59   variable until handlers are available.
60   60  
61   @par Thread Safety 61   @par Thread Safety
62   All public member functions are thread-safe. 62   All public member functions are thread-safe.
63   */ 63   */
64   class BOOST_COROSIO_DECL epoll_scheduler final : public reactor_scheduler 64   class BOOST_COROSIO_DECL epoll_scheduler final : public reactor_scheduler
65   { 65   {
66   public: 66   public:
67   /** Construct the scheduler. 67   /** Construct the scheduler.
68   68  
69   Creates an epoll instance and an eventfd for reactor 69   Creates an epoll instance and an eventfd for reactor
70   interruption. The timerfd for timer expiry is created with the 70   interruption. The timerfd for timer expiry is created with the
71   context's first timer. 71   context's first timer.
72   72  
73   @param ctx Reference to the owning execution_context. 73   @param ctx Reference to the owning execution_context.
74   @param concurrency_hint Hint for expected thread count (unused). 74   @param concurrency_hint Hint for expected thread count (unused).
75   */ 75   */
76   epoll_scheduler(capy::execution_context& ctx, int concurrency_hint = -1); 76   epoll_scheduler(capy::execution_context& ctx, int concurrency_hint = -1);
77   77  
78   /// Destroy the scheduler. 78   /// Destroy the scheduler.
79   ~epoll_scheduler() override; 79   ~epoll_scheduler() override;
80   80  
81   epoll_scheduler(epoll_scheduler const&) = delete; 81   epoll_scheduler(epoll_scheduler const&) = delete;
82   epoll_scheduler& operator=(epoll_scheduler const&) = delete; 82   epoll_scheduler& operator=(epoll_scheduler const&) = delete;
83   83  
84   /// Shut down the scheduler, draining pending operations. 84   /// Shut down the scheduler, draining pending operations.
85   void shutdown() override; 85   void shutdown() override;
86   86  
87   /// Apply runtime configuration, resizing the event buffer. 87   /// Apply runtime configuration, resizing the event buffer.
88   void configure_reactor( 88   void configure_reactor(
89   unsigned max_events, 89   unsigned max_events,
90   unsigned budget_init, 90   unsigned budget_init,
91   unsigned budget_max, 91   unsigned budget_max,
92   unsigned unassisted) override; 92   unsigned unassisted) override;
93   93  
94   /** Return the epoll file descriptor. 94   /** Return the epoll file descriptor.
95   95  
96   Used by socket services to register file descriptors 96   Used by socket services to register file descriptors
97   for I/O event notification. 97   for I/O event notification.
98   98  
99   @return The epoll file descriptor. 99   @return The epoll file descriptor.
100   */ 100   */
101   int epoll_fd() const noexcept 101   int epoll_fd() const noexcept
102   { 102   {
103   return epoll_fd_; 103   return epoll_fd_;
104   } 104   }
105   105  
106   /** Register a descriptor for persistent monitoring. 106   /** Register a descriptor for persistent monitoring.
107   107  
108   The fd is registered once and stays registered until explicitly 108   The fd is registered once and stays registered until explicitly
109   deregistered. Events are dispatched via reactor_descriptor_state which 109   deregistered. Events are dispatched via reactor_descriptor_state which
110   tracks pending read/write/connect operations. 110   tracks pending read/write/connect operations.
111   111  
112   @param fd The file descriptor to register. 112   @param fd The file descriptor to register.
113   @param desc Pointer to descriptor data (stored in epoll_event.data.ptr). 113   @param desc Pointer to descriptor data (stored in epoll_event.data.ptr).
114   114  
115   @return The error if registration fails, otherwise a default 115   @return The error if registration fails, otherwise a default
116   constructed error code. 116   constructed error code.
117   */ 117   */
118   std::error_code 118   std::error_code
119   register_descriptor(int fd, reactor_descriptor_state* desc) const; 119   register_descriptor(int fd, reactor_descriptor_state* desc) const;
120   120  
121   /// No-op: write readiness is watched from registration on. 121   /// No-op: write readiness is watched from registration on.
122   std::error_code 122   std::error_code
HITCBC 123   5507 ensure_write_registered(int, reactor_descriptor_state*) const noexcept 123   5572 ensure_write_registered(int, reactor_descriptor_state*) const noexcept
124   { 124   {
HITCBC 125   5507 return {}; 125   5572 return {};
126   } 126   }
127   127  
128   /** Deregister a persistently registered descriptor. 128   /** Deregister a persistently registered descriptor.
129   129  
130   @param fd The file descriptor to deregister. 130   @param fd The file descriptor to deregister.
131   */ 131   */
132   void deregister_descriptor(int fd) const; 132   void deregister_descriptor(int fd) const;
133   133  
134   /// Watch the read end of the POSIX signal self-pipe (see scheduler.hpp). 134   /// Watch the read end of the POSIX signal self-pipe (see scheduler.hpp).
HITCBC 135   287 [[nodiscard]] std::error_code register_signal_reader(int read_fd) override 135   287 [[nodiscard]] std::error_code register_signal_reader(int read_fd) override
136   { 136   {
HITCBC 137   287 return register_descriptor(read_fd, signal_pipe_reader_.arm()); 137   287 return register_descriptor(read_fd, signal_pipe_reader_.arm());
138   } 138   }
139   139  
140   private: 140   private:
141   void run_task(lock_type& lock, context_type& ctx, long timeout_us) override; 141   void run_task(lock_type& lock, context_type& ctx, long timeout_us) override;
142   void interrupt_reactor() const override; 142   void interrupt_reactor() const override;
143   void update_timerfd() const; 143   void update_timerfd() const;
144   static int timer_timeout_ms(timer_service& svc, int timeout_ms) noexcept; 144   static int timer_timeout_ms(timer_service& svc, int timeout_ms) noexcept;
145   void on_timer_service_attached(timer_service& svc) override; 145   void on_timer_service_attached(timer_service& svc) override;
146   146  
147   int epoll_fd_; 147   int epoll_fd_;
148   int event_fd_; 148   int event_fd_;
149   int timer_fd_; 149   int timer_fd_;
150   150  
151   // Watches the global signal self-pipe's read end (armed lazily by 151   // Watches the global signal self-pipe's read end (armed lazily by
152   // register_signal_reader on the first signal registration). 152   // register_signal_reader on the first signal registration).
153   reactor_signal_pipe_reader signal_pipe_reader_; 153   reactor_signal_pipe_reader signal_pipe_reader_;
154   154  
155   // Edge-triggered eventfd state 155   // Edge-triggered eventfd state
156   mutable std::atomic<bool> eventfd_armed_{false}; 156   mutable std::atomic<bool> eventfd_armed_{false};
157   157  
158   // Set when the earliest timer changes; flushed before epoll_wait 158   // Set when the earliest timer changes; flushed before epoll_wait
159   mutable std::atomic<bool> timerfd_stale_{false}; 159   mutable std::atomic<bool> timerfd_stale_{false};
160   160  
161   // Event buffer sized from max_events_per_poll_ (set at construction, 161   // Event buffer sized from max_events_per_poll_ (set at construction,
162   // resized by configure_reactor via io_context_options). 162   // resized by configure_reactor via io_context_options).
163   std::vector<epoll_event> event_buffer_; 163   std::vector<epoll_event> event_buffer_;
164   }; 164   };
165   165  
HITCBC 166   2618 inline epoll_scheduler::epoll_scheduler(capy::execution_context&, int) 166   2618 inline epoll_scheduler::epoll_scheduler(capy::execution_context&, int)
HITCBC 167   2618 : epoll_fd_(-1) 167   2618 : epoll_fd_(-1)
HITCBC 168   2618 , event_fd_(-1) 168   2618 , event_fd_(-1)
HITCBC 169   2618 , timer_fd_(-1) 169   2618 , timer_fd_(-1)
HITCBC 170   5236 , event_buffer_(max_events_per_poll_) 170   5236 , event_buffer_(max_events_per_poll_)
171   { 171   {
HITCBC 172   2618 epoll_fd_ = ::epoll_create1(EPOLL_CLOEXEC); 172   2618 epoll_fd_ = ::epoll_create1(EPOLL_CLOEXEC);
HITCBC 173   2618 if (epoll_fd_ < 0) 173   2618 if (epoll_fd_ < 0)
HITCBC 174   3 detail::throw_system_error(make_err(errno), "epoll_create1"); 174   3 detail::throw_system_error(make_err(errno), "epoll_create1");
175   175  
HITCBC 176   2615 event_fd_ = ::eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC); 176   2615 event_fd_ = ::eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC);
HITCBC 177   2615 if (event_fd_ < 0) 177   2615 if (event_fd_ < 0)
178   { 178   {
HITCBC 179   3 int errn = errno; 179   3 int errn = errno;
HITCBC 180   3 ::close(epoll_fd_); 180   3 ::close(epoll_fd_);
HITCBC 181   3 detail::throw_system_error(make_err(errn), "eventfd"); 181   3 detail::throw_system_error(make_err(errn), "eventfd");
182   } 182   }
183   183  
HITCBC 184   2612 epoll_event ev{}; 184   2612 epoll_event ev{};
HITCBC 185   2612 ev.events = EPOLLIN | EPOLLET; 185   2612 ev.events = EPOLLIN | EPOLLET;
HITCBC 186   2612 ev.data.ptr = nullptr; 186   2612 ev.data.ptr = nullptr;
HITCBC 187   2612 if (::epoll_ctl(epoll_fd_, EPOLL_CTL_ADD, event_fd_, &ev) < 0) 187   2612 if (::epoll_ctl(epoll_fd_, EPOLL_CTL_ADD, event_fd_, &ev) < 0)
188   { 188   {
HITCBC 189   3 int errn = errno; 189   3 int errn = errno;
HITCBC 190   3 ::close(event_fd_); 190   3 ::close(event_fd_);
HITCBC 191   3 ::close(epoll_fd_); 191   3 ::close(epoll_fd_);
HITCBC 192   3 detail::throw_system_error(make_err(errn), "epoll_ctl"); 192   3 detail::throw_system_error(make_err(errn), "epoll_ctl");
193   } 193   }
194   194  
HITCBC 195   2609 completed_ops_.push(&task_op_); 195   2609 completed_ops_.push(&task_op_);
HITCBC 196   2636 } 196   2636 }
197   197  
198   inline void 198   inline void
HITCBC 199   549 epoll_scheduler::on_timer_service_attached(timer_service& svc) 199   549 epoll_scheduler::on_timer_service_attached(timer_service& svc)
200   { 200   {
201   // Without a timerfd the epoll_wait timeout drives the timers: the 201   // Without a timerfd the epoll_wait timeout drives the timers: the
202   // first timer is often made where a throw can only terminate. 202   // first timer is often made where a throw can only terminate.
HITCBC 203   549 int fd = ::timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK | TFD_CLOEXEC); 203   549 int fd = ::timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK | TFD_CLOEXEC);
HITCBC 204   549 if (fd >= 0) 204   549 if (fd >= 0)
205   { 205   {
206   // Set before registration, which orders it for every thread 206   // Set before registration, which orders it for every thread
207   // the timerfd's events can wake. 207   // the timerfd's events can wake.
HITCBC 208   548 timer_fd_ = fd; 208   548 timer_fd_ = fd;
HITCBC 209   548 epoll_event timer_ev{}; 209   548 epoll_event timer_ev{};
HITCBC 210   548 timer_ev.events = EPOLLIN | EPOLLERR; 210   548 timer_ev.events = EPOLLIN | EPOLLERR;
HITCBC 211   548 timer_ev.data.ptr = &timer_fd_; 211   548 timer_ev.data.ptr = &timer_fd_;
HITCBC 212   548 if (::epoll_ctl(epoll_fd_, EPOLL_CTL_ADD, fd, &timer_ev) < 0) 212   548 if (::epoll_ctl(epoll_fd_, EPOLL_CTL_ADD, fd, &timer_ev) < 0)
213   { 213   {
HITCBC 214   1 ::close(fd); 214   1 ::close(fd);
HITCBC 215   1 timer_fd_ = -1; 215   1 timer_fd_ = -1;
216   } 216   }
217   } 217   }
HITCBC 218   549 svc.set_on_earliest_changed(timer_service::callback(this, [](void* p) { 218   549 svc.set_on_earliest_changed(timer_service::callback(this, [](void* p) {
HITCBC 219   5188 auto* self = static_cast<epoll_scheduler*>(p); 219   4757 auto* self = static_cast<epoll_scheduler*>(p);
HITCBC 220   5188 self->timerfd_stale_.store(true, std::memory_order_release); 220   4757 self->timerfd_stale_.store(true, std::memory_order_release);
HITCBC 221   5188 self->interrupt_reactor(); 221   4757 self->interrupt_reactor();
HITCBC 222   5188 })); 222   4757 }));
HITCBC 223   549 } 223   549 }
224   224  
HITCBC 225   5218 inline epoll_scheduler::~epoll_scheduler() 225   5218 inline epoll_scheduler::~epoll_scheduler()
226   { 226   {
HITCBC 227   2609 if (timer_fd_ >= 0) 227   2609 if (timer_fd_ >= 0)
HITCBC 228   547 ::close(timer_fd_); 228   547 ::close(timer_fd_);
HITCBC 229   2609 if (event_fd_ >= 0) 229   2609 if (event_fd_ >= 0)
HITCBC 230   2609 ::close(event_fd_); 230   2609 ::close(event_fd_);
HITCBC 231   2609 if (epoll_fd_ >= 0) 231   2609 if (epoll_fd_ >= 0)
HITCBC 232   2609 ::close(epoll_fd_); 232   2609 ::close(epoll_fd_);
HITCBC 233   5218 } 233   5218 }
234   234  
235   inline void 235   inline void
HITCBC 236   2609 epoll_scheduler::shutdown() 236   2609 epoll_scheduler::shutdown()
237   { 237   {
HITCBC 238   2609 shutdown_drain(); 238   2609 shutdown_drain();
239   239  
HITCBC 240   2609 if (event_fd_ >= 0) 240   2609 if (event_fd_ >= 0)
HITCBC 241   2609 interrupt_reactor(); 241   2609 interrupt_reactor();
HITCBC 242   2609 } 242   2609 }
243   243  
244   inline void 244   inline void
HITCBC 245   30 epoll_scheduler::configure_reactor( 245   30 epoll_scheduler::configure_reactor(
246   unsigned max_events, 246   unsigned max_events,
247   unsigned budget_init, 247   unsigned budget_init,
248   unsigned budget_max, 248   unsigned budget_max,
249   unsigned unassisted) 249   unsigned unassisted)
250   { 250   {
HITCBC 251   30 reactor_scheduler::configure_reactor( 251   30 reactor_scheduler::configure_reactor(
252   max_events, budget_init, budget_max, unassisted); 252   max_events, budget_init, budget_max, unassisted);
HITCBC 253   30 event_buffer_.resize(max_events_per_poll_); 253   30 event_buffer_.resize(max_events_per_poll_);
HITCBC 254   30 } 254   30 }
255   255  
256   inline std::error_code 256   inline std::error_code
HITCBC 257   13890 epoll_scheduler::register_descriptor( 257   13558 epoll_scheduler::register_descriptor(
258   int fd, reactor_descriptor_state* desc) const 258   int fd, reactor_descriptor_state* desc) const
259   { 259   {
HITCBC 260   13890 epoll_event ev{}; 260   13558 epoll_event ev{};
HITCBC 261   13890 ev.events = EPOLLIN | EPOLLOUT | EPOLLET | EPOLLERR | EPOLLHUP; 261   13558 ev.events = EPOLLIN | EPOLLOUT | EPOLLET | EPOLLERR | EPOLLHUP;
HITCBC 262   13890 ev.data.ptr = desc; 262   13558 ev.data.ptr = desc;
263   263  
264   // Initialized before the add: another run thread's reactor can 264   // Initialized before the add: another run thread's reactor can
265   // dispatch an event for the descriptor as soon as it is added. 265   // dispatch an event for the descriptor as soon as it is added.
266   // A completion queued by an earlier registration of the same state 266   // A completion queued by an earlier registration of the same state
267   // may still be running, so the fields it reads change under its 267   // may still be running, so the fields it reads change under its
268   // mutex, and the mutex mode is only written when it differs. 268   // mutex, and the mutex mode is only written when it differs.
HITCBC 269   13890 if (desc->mutex.enabled() != reactor_io_locking_) 269   13558 if (desc->mutex.enabled() != reactor_io_locking_)
HITCBC 270   3 desc->mutex.set_enabled(reactor_io_locking_); 270   3 desc->mutex.set_enabled(reactor_io_locking_);
271   { 271   {
HITCBC 272   13890 conditionally_enabled_mutex::scoped_lock lock(desc->mutex); 272   13558 conditionally_enabled_mutex::scoped_lock lock(desc->mutex);
HITCBC 273   13890 desc->registered_events = ev.events; 273   13558 desc->registered_events = ev.events;
HITCBC 274   13890 desc->unpollable = false; 274   13558 desc->unpollable = false;
HITCBC 275   13890 desc->fd = fd; 275   13558 desc->fd = fd;
HITCBC 276   13890 desc->scheduler_ = this; 276   13558 desc->scheduler_ = this;
HITCBC 277   13890 desc->ready_events_.store(0, std::memory_order_release); 277   13558 desc->ready_events_.store(0, std::memory_order_release);
278   // object_ref_ is not touched: a queued invocation from an 278   // object_ref_ is not touched: a queued invocation from an
279   // earlier registration still owns the reference in it. 279   // earlier registration still owns the reference in it.
HITCBC 280   13890 desc->read_ready = false; 280   13558 desc->read_ready = false;
HITCBC 281   13890 desc->write_ready = false; 281   13558 desc->write_ready = false;
HITCBC 282   13890 } 282   13558 }
283   283  
HITCBC 284   13890 if (::epoll_ctl(epoll_fd_, EPOLL_CTL_ADD, fd, &ev) < 0) 284   13558 if (::epoll_ctl(epoll_fd_, EPOLL_CTL_ADD, fd, &ev) < 0)
285   { 285   {
HITCBC 286   12 int const err = errno; 286   12 int const err = errno;
HITCBC 287   12 conditionally_enabled_mutex::scoped_lock lock(desc->mutex); 287   12 conditionally_enabled_mutex::scoped_lock lock(desc->mutex);
HITCBC 288   12 desc->registered_events = 0; 288   12 desc->registered_events = 0;
289   // EPERM: a file type epoll cannot watch. Its I/O does not 289   // EPERM: a file type epoll cannot watch. Its I/O does not
290   // block, so adopt it unwatched, as asio does. 290   // block, so adopt it unwatched, as asio does.
HITCBC 291   12 if (err != EPERM) 291   12 if (err != EPERM)
HITCBC 292   7 return make_err(err); 292   7 return make_err(err);
HITCBC 293   5 desc->unpollable = true; 293   5 desc->unpollable = true;
HITCBC 294   12 } 294   12 }
HITCBC 295   13883 return {}; 295   13551 return {};
296   } 296   }
297   297  
298   inline void 298   inline void
HITCBC 299   13592 epoll_scheduler::deregister_descriptor(int fd) const 299   13260 epoll_scheduler::deregister_descriptor(int fd) const
300   { 300   {
HITCBC 301   13592 ::epoll_ctl(epoll_fd_, EPOLL_CTL_DEL, fd, nullptr); 301   13260 ::epoll_ctl(epoll_fd_, EPOLL_CTL_DEL, fd, nullptr);
HITCBC 302   13592 } 302   13260 }
303   303  
304   inline void 304   inline void
HITCBC 305   13376 epoll_scheduler::interrupt_reactor() const 305   13325 epoll_scheduler::interrupt_reactor() const
306   { 306   {
HITCBC 307   13376 bool expected = false; 307   13325 bool expected = false;
HITCBC 308   13376 if (eventfd_armed_.compare_exchange_strong( 308   13325 if (eventfd_armed_.compare_exchange_strong(
309   expected, true, std::memory_order_release, 309   expected, true, std::memory_order_release,
310   std::memory_order_relaxed)) 310   std::memory_order_relaxed))
311   { 311   {
HITCBC 312   11061 std::uint64_t val = 1; 312   10981 std::uint64_t val = 1;
HITCBC 313   11061 if (::write(event_fd_, &val, sizeof(val)) < 0) 313   10981 if (::write(event_fd_, &val, sizeof(val)) < 0)
314   { 314   {
315   // The flag is what coalesces later interrupts into a byte 315   // The flag is what coalesces later interrupts into a byte
316   // already in the eventfd; a write that failed put no byte 316   // already in the eventfd; a write that failed put no byte
317   // there, so leaving it armed would swallow every interrupt 317   // there, so leaving it armed would swallow every interrupt
318   // that follows. Disarming keeps the cost to the interrupts 318   // that follows. Disarming keeps the cost to the interrupts
319   // already in flight -- the next one arms and writes again, 319   // already in flight -- the next one arms and writes again,
320   // instead of every one after this coalescing into a byte 320   // instead of every one after this coalescing into a byte
321   // that does not exist. 321   // that does not exist.
HITCBC 322   2 eventfd_armed_.store(false, std::memory_order_release); 322   2 eventfd_armed_.store(false, std::memory_order_release);
323   } 323   }
324   } 324   }
HITCBC 325   13376 } 325   13325 }
326   326  
327   inline void 327   inline void
HITCBC 328   12858 epoll_scheduler::update_timerfd() const 328   11173 epoll_scheduler::update_timerfd() const
329   { 329   {
HITCBC 330   12858 auto* tsvc = timers(); 330   11173 auto* tsvc = timers();
HITCBC 331   12858 if (!tsvc || timer_fd_ < 0) 331   11173 if (!tsvc || timer_fd_ < 0)
HITCBC 332   6 return; 332   6 return;
HITCBC 333   12852 auto nearest = tsvc->nearest_expiry(); 333   11167 auto nearest = tsvc->nearest_expiry();
334   334  
HITCBC 335   12852 itimerspec ts{}; 335   11167 itimerspec ts{};
HITCBC 336   12852 int flags = 0; 336   11167 int flags = 0;
337   337  
HITCBC 338   12852 if (nearest == timer_service::time_point::max()) 338   11167 if (nearest == timer_service::time_point::max())
339   { 339   {
340   // No timers — disarm by setting to 0 (relative) 340   // No timers — disarm by setting to 0 (relative)
341   } 341   }
342   else 342   else
343   { 343   {
HITCBC 344   11504 auto now = std::chrono::steady_clock::now(); 344   9812 auto now = std::chrono::steady_clock::now();
HITCBC 345   11504 if (nearest <= now) 345   9812 if (nearest <= now)
346   { 346   {
347   // Use 1ns instead of 0 — zero disarms the timerfd 347   // Use 1ns instead of 0 — zero disarms the timerfd
HITCBC 348   1085 ts.it_value.tv_nsec = 1; 348   576 ts.it_value.tv_nsec = 1;
349   } 349   }
350   else 350   else
351   { 351   {
HITCBC 352   10419 auto nsec = std::chrono::duration_cast<std::chrono::nanoseconds>( 352   9236 auto nsec = std::chrono::duration_cast<std::chrono::nanoseconds>(
HITCBC 353   10419 nearest - now) 353   9236 nearest - now)
HITCBC 354   10419 .count(); 354   9236 .count();
HITCBC 355   10419 ts.it_value.tv_sec = nsec / 1000000000; 355   9236 ts.it_value.tv_sec = nsec / 1000000000;
HITCBC 356   10419 ts.it_value.tv_nsec = nsec % 1000000000; 356   9236 ts.it_value.tv_nsec = nsec % 1000000000;
HITCBC 357   10419 if (ts.it_value.tv_sec == 0 && ts.it_value.tv_nsec == 0) 357   9236 if (ts.it_value.tv_sec == 0 && ts.it_value.tv_nsec == 0)
MISUBC 358   ✗ ts.it_value.tv_nsec = 1; 358   ✗ ts.it_value.tv_nsec = 1;
359   } 359   }
360   } 360   }
361   361  
HITCBC 362   12852 if (::timerfd_settime(timer_fd_, flags, &ts, nullptr) < 0) 362   11167 if (::timerfd_settime(timer_fd_, flags, &ts, nullptr) < 0)
363   { 363   {
364   // Nothing else would rearm it, so the next pass retries. 364   // Nothing else would rearm it, so the next pass retries.
HITCBC 365   2 int const err = errno; 365   2 int const err = errno;
HITCBC 366   2 timerfd_stale_.store(true, std::memory_order_release); 366   2 timerfd_stale_.store(true, std::memory_order_release);
HITCBC 367   2 detail::throw_system_error(make_err(err), "timerfd_settime"); 367   2 detail::throw_system_error(make_err(err), "timerfd_settime");
368   } 368   }
369   } 369   }
370   370  
371   // Rounded up, so the wait never wakes before the timer is due. 371   // Rounded up, so the wait never wakes before the timer is due.
372   inline int 372   inline int
HITCBC 373   4 epoll_scheduler::timer_timeout_ms(timer_service& svc, int timeout_ms) noexcept 373   4 epoll_scheduler::timer_timeout_ms(timer_service& svc, int timeout_ms) noexcept
374   { 374   {
HITCBC 375   4 auto nearest = svc.nearest_expiry(); 375   4 auto nearest = svc.nearest_expiry();
HITCBC 376   4 if (nearest == timer_service::time_point::max()) 376   4 if (nearest == timer_service::time_point::max())
MISUBC 377   ✗ return timeout_ms; 377   ✗ return timeout_ms;
HITCBC 378   4 auto now = std::chrono::steady_clock::now(); 378   4 auto now = std::chrono::steady_clock::now();
HITCBC 379   4 if (nearest <= now) 379   4 if (nearest <= now)
MISUBC 380   ✗ return 0; 380   ✗ return 0;
381   auto ms = 381   auto ms =
HITCBC 382   4 std::chrono::ceil<std::chrono::milliseconds>(nearest - now).count(); 382   4 std::chrono::ceil<std::chrono::milliseconds>(nearest - now).count();
HITCBC 383   8 ms = (std::min)(ms, 383   8 ms = (std::min)(ms,
HITCBC 384   4 static_cast<decltype(ms)>( 384   4 static_cast<decltype(ms)>(
HITCBC 385   4 (std::numeric_limits<int>::max)())); 385   4 (std::numeric_limits<int>::max)()));
HITCBC 386   4 if (timeout_ms >= 0 && timeout_ms < ms) 386   4 if (timeout_ms >= 0 && timeout_ms < ms)
MISUBC 387   ✗ return timeout_ms; 387   ✗ return timeout_ms;
HITCBC 388   4 return static_cast<int>(ms); 388   4 return static_cast<int>(ms);
389   } 389   }
390   390  
391   inline void 391   inline void
HITCBC 392   88735 epoll_scheduler::run_task(lock_type& lock, context_type& ctx, long timeout_us) 392   87287 epoll_scheduler::run_task(lock_type& lock, context_type& ctx, long timeout_us)
393   { 393   {
394   int timeout_ms; 394   int timeout_ms;
HITCBC 395   88735 if (task_interrupted_) 395   87287 if (task_interrupted_)
HITCBC 396   65014 timeout_ms = 0; 396   65457 timeout_ms = 0;
HITCBC 397   23721 else if (timeout_us < 0) 397   21830 else if (timeout_us < 0)
HITCBC 398   23210 timeout_ms = -1; 398   21284 timeout_ms = -1;
399   else 399   else
HITCBC 400   511 timeout_ms = static_cast<int>((timeout_us + 999) / 1000); 400   546 timeout_ms = static_cast<int>((timeout_us + 999) / 1000);
401   401  
HITCBC 402   88735 if (lock.owns_lock()) 402   87287 if (lock.owns_lock())
HITCBC 403   24356 lock.unlock(); 403   22459 lock.unlock();
404   404  
HITCBC 405   88735 task_cleanup on_exit{this, &lock, ctx}; 405   87287 task_cleanup on_exit{this, &lock, ctx};
406   406  
407   // Flush deferred timerfd programming before blocking 407   // Flush deferred timerfd programming before blocking
HITCBC 408   88735 if (timerfd_stale_.exchange(false, std::memory_order_acquire)) 408   87287 if (timerfd_stale_.exchange(false, std::memory_order_acquire))
HITCBC 409   4564 update_timerfd(); 409   4151 update_timerfd();
410   410  
411   // timer_fd_ is read only once the service is seen, after which it 411   // timer_fd_ is read only once the service is seen, after which it
412   // no longer changes. 412   // no longer changes.
HITCBC 413   88734 auto* tsvc = timers(); 413   87286 auto* tsvc = timers();
HITCBC 414   88734 bool const poll_timers = tsvc && timer_fd_ < 0; 414   87286 bool const poll_timers = tsvc && timer_fd_ < 0;
HITCBC 415   88734 if (poll_timers && timeout_ms != 0) 415   87286 if (poll_timers && timeout_ms != 0)
HITCBC 416   4 timeout_ms = timer_timeout_ms(*tsvc, timeout_ms); 416   4 timeout_ms = timer_timeout_ms(*tsvc, timeout_ms);
417   417  
HITCBC 418   88734 int nfds = ::epoll_wait( 418   87286 int nfds = ::epoll_wait(
HITCBC 419   88734 epoll_fd_, event_buffer_.data(), static_cast<int>(event_buffer_.size()), 419   87286 epoll_fd_, event_buffer_.data(), static_cast<int>(event_buffer_.size()),
420   timeout_ms); 420   timeout_ms);
421   421  
HITCBC 422   88734 if (nfds < 0 && errno != EINTR) 422   87286 if (nfds < 0 && errno != EINTR)
HITCBC 423   3 detail::throw_system_error(make_err(errno), "epoll_wait"); 423   3 detail::throw_system_error(make_err(errno), "epoll_wait");
424   424  
425   // The timerfd is armed relative to when it was set, so it can fire a 425   // The timerfd is armed relative to when it was set, so it can fire a
426   // little after a deadline. A pass that doesn't block checks the 426   // little after a deadline. A pass that doesn't block checks the
427   // clock instead, so poll() never misses a timer that is already due. 427   // clock instead, so poll() never misses a timer that is already due.
HITCBC 428   88731 bool check_timers = poll_timers; 428   87283 bool check_timers = poll_timers;
HITCBC 429   88731 if (!check_timers && tsvc && timeout_ms == 0) 429   87283 if (!check_timers && tsvc && timeout_ms == 0)
430   { 430   {
HITCBC 431   11888 auto const nearest = tsvc->nearest_expiry(); 431   12295 auto const nearest = tsvc->nearest_expiry();
HITCBC 432   23536 check_timers = nearest != (timer_service::time_point::max)() && 432   24350 check_timers = nearest != (timer_service::time_point::max)() &&
HITCBC 433   23536 nearest <= std::chrono::steady_clock::now(); 433   24350 nearest <= std::chrono::steady_clock::now();
434   } 434   }
HITCBC 435   88731 ready_queue local_ops; 435   87283 ready_queue local_ops;
436   436  
HITCBC 437   136546 for (int i = 0; i < nfds; ++i) 437   134082 for (int i = 0; i < nfds; ++i)
438   { 438   {
HITCBC 439   47815 if (event_buffer_[i].data.ptr == nullptr) 439   46799 if (event_buffer_[i].data.ptr == nullptr)
440   { 440   {
441   std::uint64_t val; 441   std::uint64_t val;
442   // NOLINTNEXTLINE(clang-analyzer-unix.BlockInCriticalSection) 442   // NOLINTNEXTLINE(clang-analyzer-unix.BlockInCriticalSection)
HITCBC 443   8450 [[maybe_unused]] auto r = ::read(event_fd_, &val, sizeof(val)); 443   8370 [[maybe_unused]] auto r = ::read(event_fd_, &val, sizeof(val));
HITCBC 444   8450 eventfd_armed_.store(false, std::memory_order_relaxed); 444   8370 eventfd_armed_.store(false, std::memory_order_relaxed);
HITCBC 445   8450 continue; 445   8370 continue;
HITCBC 446   8450 } 446   8370 }
447   447  
HITCBC 448   39365 if (event_buffer_[i].data.ptr == &timer_fd_) 448   38429 if (event_buffer_[i].data.ptr == &timer_fd_)
449   { 449   {
450   std::uint64_t expirations; 450   std::uint64_t expirations;
451   // NOLINTNEXTLINE(clang-analyzer-unix.BlockInCriticalSection) 451   // NOLINTNEXTLINE(clang-analyzer-unix.BlockInCriticalSection)
452   [[maybe_unused]] auto r = 452   [[maybe_unused]] auto r =
HITCBC 453   8290 ::read(timer_fd_, &expirations, sizeof(expirations)); 453   7018 ::read(timer_fd_, &expirations, sizeof(expirations));
HITCBC 454   8290 check_timers = true; 454   7018 check_timers = true;
HITCBC 455   8290 continue; 455   7018 continue;
HITCBC 456   8290 } 456   7018 }
457   457  
458   auto* desc = 458   auto* desc =
HITCBC 459   31075 static_cast<reactor_descriptor_state*>(event_buffer_[i].data.ptr); 459   31411 static_cast<reactor_descriptor_state*>(event_buffer_[i].data.ptr);
460   460  
461   // EPOLLHUP maps to no reactor_event_* bit, so a HUP the widening 461   // EPOLLHUP maps to no reactor_event_* bit, so a HUP the widening
462   // below did not translate would take no branch in 462   // below did not translate would take no branch in
463   // invoke_deferred_io() and, the registration being 463   // invoke_deferred_io() and, the registration being
464   // edge-triggered, never get another chance. 464   // edge-triggered, never get another chance.
465   // 465   //
466   // HUP without OUT means a non-socket: a pipe or tty whose peer 466   // HUP without OUT means a non-socket: a pipe or tty whose peer
467   // closed, with or without data still unread (HUP alone, or 467   // closed, with or without data still unread (HUP alone, or
468   // IN|HUP). Treat it as readable, writable and faulted, the way 468   // IN|HUP). Treat it as readable, writable and faulted, the way
469   // poll() and io_uring report it, so a parked error wait 469   // poll() and io_uring report it, so a parked error wait
470   // completes too. Sockets carry at least OUT with HUP (a fresh 470   // completes too. Sockets carry at least OUT with HUP (a fresh
471   // unconnected stream socket reports HUP|OUT), so they take the 471   // unconnected stream socket reports HUP|OUT), so they take the
472   // plain widening, where forcing IN costs at most one spurious 472   // plain widening, where forcing IN costs at most one spurious
473   // EAGAIN. 473   // EAGAIN.
HITCBC 474   31075 std::uint32_t ev = event_buffer_[i].events; 474   31411 std::uint32_t ev = event_buffer_[i].events;
HITCBC 475   31075 if ((ev & (EPOLLHUP | EPOLLOUT)) == EPOLLHUP) 475   31411 if ((ev & (EPOLLHUP | EPOLLOUT)) == EPOLLHUP)
HITCBC 476   8 ev |= EPOLLIN | EPOLLOUT | EPOLLERR; 476   8 ev |= EPOLLIN | EPOLLOUT | EPOLLERR;
HITCBC 477   31067 else if (ev & EPOLLHUP) 477   31403 else if (ev & EPOLLHUP)
HITCBC 478   345 ev |= EPOLLIN | EPOLLOUT; 478   333 ev |= EPOLLIN | EPOLLOUT;
HITCBC 479   31075 desc->add_ready_events(ev); 479   31411 desc->add_ready_events(ev);
480   480  
HITCBC 481   31075 bool expected = false; 481   31411 bool expected = false;
HITCBC 482   31075 if (desc->is_enqueued_.compare_exchange_strong( 482   31411 if (desc->is_enqueued_.compare_exchange_strong(
483   expected, true, std::memory_order_release, 483   expected, true, std::memory_order_release,
484   std::memory_order_relaxed)) 484   std::memory_order_relaxed))
485   { 485   {
HITCBC 486   31069 local_ops.push(desc); 486   31410 local_ops.push(desc);
487   } 487   }
488   } 488   }
489   489  
490   // Each is already marked enqueued, so a throw below must still 490   // Each is already marked enqueued, so a throw below must still
491   // hand them over or they never queue again. 491   // hand them over or they never queue again.
HITCBC 492   88731 ctx.private_queue.splice(local_ops); 492   87283 ctx.private_queue.splice(local_ops);
493   493  
HITCBC 494   88731 if (check_timers) 494   87283 if (check_timers)
495   { 495   {
HITCBC 496   8294 if (auto* svc = timers()) 496   7022 if (auto* svc = timers())
HITCBC 497   8294 svc->process_expired(); 497   7022 svc->process_expired();
HITCBC 498   8294 update_timerfd(); 498   7022 update_timerfd();
499   } 499   }
500   500  
HITCBC 501   88730 lock.lock(); 501   87282 lock.lock();
HITCBC 502   88735 } 502   87287 }
503   503  
504   } // namespace boost::corosio::detail 504   } // namespace boost::corosio::detail
505   505  
506   #endif // BOOST_COROSIO_HAS_EPOLL 506   #endif // BOOST_COROSIO_HAS_EPOLL
507   507  
508   #endif // BOOST_COROSIO_NATIVE_DETAIL_EPOLL_EPOLL_SCHEDULER_HPP 508   #endif // BOOST_COROSIO_NATIVE_DETAIL_EPOLL_EPOLL_SCHEDULER_HPP