1 ///////////////////////////////////////////////////////////////////////////////
2 // Name:        src/unix/epolldispatcher.cpp
3 // Purpose:     implements dispatcher for epoll_wait() call
4 // Author:      Lukasz Michalski
5 // Created:     April 2007
6 // Copyright:   (c) 2007 Lukasz Michalski
7 // Licence:     wxWindows licence
8 ///////////////////////////////////////////////////////////////////////////////
9 
10 // ============================================================================
11 // declarations
12 // ============================================================================
13 
14 // ----------------------------------------------------------------------------
15 // headers
16 // ----------------------------------------------------------------------------
17 
18 // for compilers that support precompilation, includes "wx.h".
19 #include "wx/wxprec.h"
20 
21 #if wxUSE_EPOLL_DISPATCHER
22 
23 #include "wx/unix/private/epolldispatcher.h"
24 #include "wx/unix/private.h"
25 #include "wx/stopwatch.h"
26 
27 #ifndef WX_PRECOMP
28     #include "wx/log.h"
29     #include "wx/intl.h"
30 #endif
31 
32 #include <sys/epoll.h>
33 #include <errno.h>
34 #include <unistd.h>
35 
36 #define wxEpollDispatcher_Trace wxT("epolldispatcher")
37 
38 // ============================================================================
39 // implementation
40 // ============================================================================
41 
42 // helper: return EPOLLxxx mask corresponding to the given flags (and also log
43 // debugging messages about it)
GetEpollMask(int flags,int fd)44 static uint32_t GetEpollMask(int flags, int fd)
45 {
46     wxUnusedVar(fd); // unused if wxLogTrace() disabled
47 
48     uint32_t ep = 0;
49 
50     if ( flags & wxFDIO_INPUT )
51     {
52         ep |= EPOLLIN;
53         wxLogTrace(wxEpollDispatcher_Trace,
54                    wxT("Registered fd %d for input events"), fd);
55     }
56 
57     if ( flags & wxFDIO_OUTPUT )
58     {
59         ep |= EPOLLOUT;
60         wxLogTrace(wxEpollDispatcher_Trace,
61                    wxT("Registered fd %d for output events"), fd);
62     }
63 
64     if ( flags & wxFDIO_EXCEPTION )
65     {
66         ep |= EPOLLERR | EPOLLHUP;
67         wxLogTrace(wxEpollDispatcher_Trace,
68                    wxT("Registered fd %d for exceptional events"), fd);
69     }
70 
71     return ep;
72 }
73 
74 // ----------------------------------------------------------------------------
75 // wxEpollDispatcher
76 // ----------------------------------------------------------------------------
77 
78 /* static */
Create()79 wxEpollDispatcher *wxEpollDispatcher::Create()
80 {
81     int epollDescriptor = epoll_create(1024);
82     if ( epollDescriptor == -1 )
83     {
84         wxLogSysError(_("Failed to create epoll descriptor"));
85         return NULL;
86     }
87     wxLogTrace(wxEpollDispatcher_Trace,
88                    wxT("Epoll fd %d created"), epollDescriptor);
89     return new wxEpollDispatcher(epollDescriptor);
90 }
91 
wxEpollDispatcher(int epollDescriptor)92 wxEpollDispatcher::wxEpollDispatcher(int epollDescriptor)
93 {
94     wxASSERT_MSG( epollDescriptor != -1, wxT("invalid descriptor") );
95 
96     m_epollDescriptor = epollDescriptor;
97 }
98 
~wxEpollDispatcher()99 wxEpollDispatcher::~wxEpollDispatcher()
100 {
101     if ( close(m_epollDescriptor) != 0 )
102     {
103         wxLogSysError(_("Error closing epoll descriptor"));
104     }
105 }
106 
RegisterFD(int fd,wxFDIOHandler * handler,int flags)107 bool wxEpollDispatcher::RegisterFD(int fd, wxFDIOHandler* handler, int flags)
108 {
109     epoll_event ev;
110     ev.events = GetEpollMask(flags, fd);
111     ev.data.ptr = handler;
112 
113     const int ret = epoll_ctl(m_epollDescriptor, EPOLL_CTL_ADD, fd, &ev);
114     if ( ret != 0 )
115     {
116         wxLogSysError(_("Failed to add descriptor %d to epoll descriptor %d"),
117                       fd, m_epollDescriptor);
118 
119         return false;
120     }
121     wxLogTrace(wxEpollDispatcher_Trace,
122                wxT("Added fd %d (handler %p) to epoll %d"), fd, handler, m_epollDescriptor);
123 
124     return true;
125 }
126 
ModifyFD(int fd,wxFDIOHandler * handler,int flags)127 bool wxEpollDispatcher::ModifyFD(int fd, wxFDIOHandler* handler, int flags)
128 {
129     epoll_event ev;
130     ev.events = GetEpollMask(flags, fd);
131     ev.data.ptr = handler;
132 
133     const int ret = epoll_ctl(m_epollDescriptor, EPOLL_CTL_MOD, fd, &ev);
134     if ( ret != 0 )
135     {
136         wxLogSysError(_("Failed to modify descriptor %d in epoll descriptor %d"),
137                       fd, m_epollDescriptor);
138 
139         return false;
140     }
141 
142     wxLogTrace(wxEpollDispatcher_Trace,
143                 wxT("Modified fd %d (handler: %p) on epoll %d"), fd, handler, m_epollDescriptor);
144     return true;
145 }
146 
UnregisterFD(int fd)147 bool wxEpollDispatcher::UnregisterFD(int fd)
148 {
149     epoll_event ev;
150     ev.events = 0;
151     ev.data.ptr = NULL;
152 
153     if ( epoll_ctl(m_epollDescriptor, EPOLL_CTL_DEL, fd, &ev) != 0 )
154     {
155         wxLogSysError(_("Failed to unregister descriptor %d from epoll descriptor %d"),
156                       fd, m_epollDescriptor);
157     }
158     wxLogTrace(wxEpollDispatcher_Trace,
159                 wxT("removed fd %d from %d"), fd, m_epollDescriptor);
160     return true;
161 }
162 
163 int
DoPoll(epoll_event * events,int numEvents,int timeout) const164 wxEpollDispatcher::DoPoll(epoll_event *events, int numEvents, int timeout) const
165 {
166     // the code below relies on TIMEOUT_INFINITE being -1 so that we can pass
167     // timeout value directly to epoll_wait() which interprets -1 as meaning to
168     // wait forever and would need to be changed if the value of
169     // TIMEOUT_INFINITE ever changes
170     wxCOMPILE_TIME_ASSERT( TIMEOUT_INFINITE == -1, UpdateThisCode );
171 
172     wxMilliClock_t timeEnd;
173     if ( timeout > 0 )
174         timeEnd = wxGetLocalTimeMillis();
175 
176     int rc;
177     for ( ;; )
178     {
179         rc = epoll_wait(m_epollDescriptor, events, numEvents, timeout);
180         if ( rc != -1 || errno != EINTR )
181             break;
182 
183         // we got interrupted, update the timeout and restart
184         if ( timeout > 0 )
185         {
186             timeout = wxMilliClockToLong(timeEnd - wxGetLocalTimeMillis());
187             if ( timeout < 0 )
188                 return 0;
189         }
190     }
191 
192     return rc;
193 }
194 
HasPending() const195 bool wxEpollDispatcher::HasPending() const
196 {
197     epoll_event event;
198 
199     // NB: it's not really clear if epoll_wait() can return a number greater
200     //     than the number of events passed to it but just in case it can, use
201     //     >= instead of == here, see #10397
202     return DoPoll(&event, 1, 0) >= 1;
203 }
204 
Dispatch(int timeout)205 int wxEpollDispatcher::Dispatch(int timeout)
206 {
207     epoll_event events[16];
208 
209     const int rc = DoPoll(events, WXSIZEOF(events), timeout);
210 
211     if ( rc == -1 )
212     {
213         wxLogSysError(_("Waiting for IO on epoll descriptor %d failed"),
214                       m_epollDescriptor);
215         return -1;
216     }
217 
218     int numEvents = 0;
219     for ( epoll_event *p = events; p < events + rc; p++ )
220     {
221         wxFDIOHandler * const handler = (wxFDIOHandler *)(p->data.ptr);
222         if ( !handler )
223         {
224             wxFAIL_MSG( wxT("NULL handler in epoll_event?") );
225             continue;
226         }
227 
228         // note that for compatibility with wxSelectDispatcher we call
229         // OnReadWaiting() on EPOLLHUP as this is what epoll_wait() returns
230         // when the write end of a pipe is closed while with select() the
231         // remaining pipe end becomes ready for reading when this happens
232         if ( p->events & (EPOLLIN | EPOLLHUP) )
233             handler->OnReadWaiting();
234         else if ( p->events & EPOLLOUT )
235             handler->OnWriteWaiting();
236         else if ( p->events & EPOLLERR )
237             handler->OnExceptionWaiting();
238         else
239             continue;
240 
241         numEvents++;
242     }
243 
244     return numEvents;
245 }
246 
247 #endif // wxUSE_EPOLL_DISPATCHER
248