epoll.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  1. /*
  2. * SRT - Secure, Reliable, Transport
  3. * Copyright (c) 2018 Haivision Systems Inc.
  4. *
  5. * This Source Code Form is subject to the terms of the Mozilla Public
  6. * License, v. 2.0. If a copy of the MPL was not distributed with this
  7. * file, You can obtain one at http://mozilla.org/MPL/2.0/.
  8. *
  9. */
  10. /*****************************************************************************
  11. Copyright (c) 2001 - 2010, The Board of Trustees of the University of Illinois.
  12. All rights reserved.
  13. Redistribution and use in source and binary forms, with or without
  14. modification, are permitted provided that the following conditions are
  15. met:
  16. * Redistributions of source code must retain the above
  17. copyright notice, this list of conditions and the
  18. following disclaimer.
  19. * Redistributions in binary form must reproduce the
  20. above copyright notice, this list of conditions
  21. and the following disclaimer in the documentation
  22. and/or other materials provided with the distribution.
  23. * Neither the name of the University of Illinois
  24. nor the names of its contributors may be used to
  25. endorse or promote products derived from this
  26. software without specific prior written permission.
  27. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
  28. IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
  29. THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  30. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  31. CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  32. EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  33. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  34. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  35. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  36. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  37. SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  38. *****************************************************************************/
  39. /*****************************************************************************
  40. written by
  41. Yunhong Gu, last updated 08/20/2010
  42. modified by
  43. Haivision Systems Inc.
  44. *****************************************************************************/
  45. #ifndef INC_SRT_EPOLL_H
  46. #define INC_SRT_EPOLL_H
  47. #include <map>
  48. #include <set>
  49. #include <list>
  50. #include "udt.h"
  51. namespace srt
  52. {
  53. class CUDT;
  54. class CRendezvousQueue;
  55. class CUDTGroup;
  56. class CEPollDesc
  57. {
  58. #ifdef __GNUG__
  59. const int m_iID; // epoll ID
  60. #else
  61. const int m_iID SRT_ATR_UNUSED; // epoll ID
  62. #endif
  63. struct Wait;
  64. struct Notice: public SRT_EPOLL_EVENT
  65. {
  66. Wait* parent;
  67. Notice(Wait* p, SRTSOCKET sock, int ev): parent(p)
  68. {
  69. fd = sock;
  70. events = ev;
  71. }
  72. };
  73. /// The type for `m_USockEventNotice`, the pair contains:
  74. /// * The back-pointer to the subscriber object for which this event notice serves
  75. /// * The events currently being on
  76. typedef std::list<Notice> enotice_t;
  77. struct Wait
  78. {
  79. /// Events the subscriber is interested with. Only those will be
  80. /// regarded when updating event flags.
  81. int32_t watch;
  82. /// Which events should be edge-triggered. When the event isn't
  83. /// mentioned in `watch`, this bit flag is disregarded. Otherwise
  84. /// it means that the event is to be waited for persistent state
  85. /// if this flag is not present here, and for edge trigger, if
  86. /// the flag is present here.
  87. int32_t edge;
  88. /// The current persistent state. This is usually duplicated in
  89. /// a dedicated state object in `m_USockEventNotice`, however the state
  90. /// here will stay forever as is, regardless of the edge/persistent
  91. /// subscription mode for the event.
  92. int32_t state;
  93. /// The iterator to `m_USockEventNotice` container that contains the
  94. /// event notice object for this subscription, or the value from
  95. /// `nullNotice()` if there is no such object.
  96. enotice_t::iterator notit;
  97. Wait(explicit_t<int32_t> sub, explicit_t<int32_t> etr, enotice_t::iterator i)
  98. :watch(sub)
  99. ,edge(etr)
  100. ,state(0)
  101. ,notit(i)
  102. {
  103. }
  104. int edgeOnly() { return edge & watch; }
  105. /// Clear all flags for given direction from the notices
  106. /// and subscriptions, and checks if this made the event list
  107. /// for this watch completely empty.
  108. /// @param direction event type that has to be cleared
  109. /// @return true, if this cleared the last event (the caller
  110. /// want to remove the subscription for this socket)
  111. bool clear(int32_t direction)
  112. {
  113. if (watch & direction)
  114. {
  115. watch &= ~direction;
  116. edge &= ~direction;
  117. state &= ~direction;
  118. return watch == 0;
  119. }
  120. return false;
  121. }
  122. };
  123. typedef std::map<SRTSOCKET, Wait> ewatch_t;
  124. #if ENABLE_HEAVY_LOGGING
  125. std::string DisplayEpollWatch();
  126. #endif
  127. /// Sockets that are subscribed for events in this eid.
  128. ewatch_t m_USockWatchState;
  129. /// Objects representing changes in SRT sockets.
  130. /// Objects are removed from here when an event is registerred as edge-triggered.
  131. /// Otherwise it is removed only when all events as per subscription
  132. /// are no longer on.
  133. enotice_t m_USockEventNotice;
  134. // Special behavior
  135. int32_t m_Flags;
  136. enotice_t::iterator nullNotice() { return m_USockEventNotice.end(); }
  137. // Only CEPoll class should have access to it.
  138. // Guarding private access to the class is not necessary
  139. // within the epoll module.
  140. friend class CEPoll;
  141. CEPollDesc(int id, int localID)
  142. : m_iID(id)
  143. , m_Flags(0)
  144. , m_iLocalID(localID)
  145. {
  146. }
  147. static const int32_t EF_NOCHECK_EMPTY = 1 << 0;
  148. static const int32_t EF_CHECK_REP = 1 << 1;
  149. int32_t flags() const { return m_Flags; }
  150. bool flags(int32_t f) const { return (m_Flags & f) != 0; }
  151. void set_flags(int32_t flg) { m_Flags |= flg; }
  152. void clr_flags(int32_t flg) { m_Flags &= ~flg; }
  153. // Container accessors for ewatch_t.
  154. bool watch_empty() const { return m_USockWatchState.empty(); }
  155. Wait* watch_find(SRTSOCKET sock)
  156. {
  157. ewatch_t::iterator i = m_USockWatchState.find(sock);
  158. if (i == m_USockWatchState.end())
  159. return NULL;
  160. return &i->second;
  161. }
  162. // Container accessors for enotice_t.
  163. enotice_t::iterator enotice_begin() { return m_USockEventNotice.begin(); }
  164. enotice_t::iterator enotice_end() { return m_USockEventNotice.end(); }
  165. enotice_t::const_iterator enotice_begin() const { return m_USockEventNotice.begin(); }
  166. enotice_t::const_iterator enotice_end() const { return m_USockEventNotice.end(); }
  167. bool enotice_empty() const { return m_USockEventNotice.empty(); }
  168. const int m_iLocalID; // local system epoll ID
  169. std::set<SYSSOCKET> m_sLocals; // set of local (non-UDT) descriptors
  170. std::pair<ewatch_t::iterator, bool> addWatch(SRTSOCKET sock, explicit_t<int32_t> events, explicit_t<int32_t> et_events)
  171. {
  172. return m_USockWatchState.insert(std::make_pair(sock, Wait(events, et_events, nullNotice())));
  173. }
  174. void addEventNotice(Wait& wait, SRTSOCKET sock, int events)
  175. {
  176. // `events` contains bits to be set, so:
  177. //
  178. // 1. If no notice object exists, add it exactly with `events`.
  179. // 2. If it exists, only set the bits from `events`.
  180. // ASSUME: 'events' is not 0, that is, we have some readiness
  181. if (wait.notit == nullNotice()) // No notice object
  182. {
  183. // Add new event notice and bind to the wait object.
  184. m_USockEventNotice.push_back(Notice(&wait, sock, events));
  185. wait.notit = --m_USockEventNotice.end();
  186. return;
  187. }
  188. // We have an existing event notice, so update it
  189. wait.notit->events |= events;
  190. }
  191. // This function only updates the corresponding event notice object
  192. // according to the change in the events.
  193. void updateEventNotice(Wait& wait, SRTSOCKET sock, int events, bool enable)
  194. {
  195. if (enable)
  196. {
  197. addEventNotice(wait, sock, events);
  198. }
  199. else
  200. {
  201. removeExcessEvents(wait, ~events);
  202. }
  203. }
  204. void removeSubscription(SRTSOCKET u)
  205. {
  206. std::map<SRTSOCKET, Wait>::iterator i = m_USockWatchState.find(u);
  207. if (i == m_USockWatchState.end())
  208. return;
  209. if (i->second.notit != nullNotice())
  210. {
  211. m_USockEventNotice.erase(i->second.notit);
  212. // NOTE: no need to update the Wait::notit field
  213. // because the Wait object is about to be removed anyway.
  214. }
  215. m_USockWatchState.erase(i);
  216. }
  217. void clearAll()
  218. {
  219. m_USockEventNotice.clear();
  220. m_USockWatchState.clear();
  221. }
  222. void removeExistingNotices(Wait& wait)
  223. {
  224. m_USockEventNotice.erase(wait.notit);
  225. wait.notit = nullNotice();
  226. }
  227. void removeEvents(Wait& wait)
  228. {
  229. if (wait.notit == nullNotice())
  230. return;
  231. removeExistingNotices(wait);
  232. }
  233. // This function removes notices referring to
  234. // events that are NOT present in @a nevts, but
  235. // may be among subscriptions and therefore potentially
  236. // have an associated notice.
  237. void removeExcessEvents(Wait& wait, int nevts)
  238. {
  239. // Update the event notice, should it exist
  240. // If the watch points to a null notice, there's simply
  241. // no notice there, so nothing to update or prospectively
  242. // remove - but may be something to add.
  243. if (wait.notit == nullNotice())
  244. return;
  245. // `events` contains bits to be cleared.
  246. // 1. If there is no notice event, do nothing - clear already.
  247. // 2. If there is a notice event, update by clearing the bits
  248. // 2.1. If this made resulting state to be 0, also remove the notice.
  249. const int newstate = wait.notit->events & nevts;
  250. if (newstate)
  251. {
  252. wait.notit->events = newstate;
  253. }
  254. else
  255. {
  256. // If the new state is full 0 (no events),
  257. // then remove the corresponding notice object
  258. removeExistingNotices(wait);
  259. }
  260. }
  261. bool checkEdge(enotice_t::iterator i)
  262. {
  263. // This function should check if this event was subscribed
  264. // as edge-triggered, and if so, clear the event from the notice.
  265. // Update events and check edge mode at the subscriber
  266. i->events &= ~i->parent->edgeOnly();
  267. if(!i->events)
  268. {
  269. removeExistingNotices(*i->parent);
  270. return true;
  271. }
  272. return false;
  273. }
  274. /// This should work in a loop around the notice container of
  275. /// the given eid container and clear out the notice for
  276. /// particular event type. If this has cleared effectively the
  277. /// last existing event, it should return the socket id
  278. /// so that the caller knows to remove it also from subscribers.
  279. ///
  280. /// @param i iterator in the notice container
  281. /// @param event event type to be cleared
  282. /// @retval (socket) Socket to be removed from subscriptions
  283. /// @retval SRT_INVALID_SOCK Nothing to be done (associated socket
  284. /// still has other subscriptions)
  285. SRTSOCKET clearEventSub(enotice_t::iterator i, int event)
  286. {
  287. // We need to remove the notice and subscription
  288. // for this event. The 'i' iterator is safe to
  289. // delete, even indirectly.
  290. // This works merely like checkEdge, just on request to clear the
  291. // identified event, if found.
  292. if (i->events & event)
  293. {
  294. // The notice has a readiness flag on this event.
  295. // This means that there exists also a subscription.
  296. Wait* w = i->parent;
  297. if (w->clear(event))
  298. return i->fd;
  299. }
  300. return SRT_INVALID_SOCK;
  301. }
  302. };
  303. class CEPoll
  304. {
  305. friend class srt::CUDT;
  306. friend class srt::CUDTGroup;
  307. friend class srt::CRendezvousQueue;
  308. public:
  309. CEPoll();
  310. ~CEPoll();
  311. public: // for CUDTUnited API
  312. /// create a new EPoll.
  313. /// @return new EPoll ID if success, otherwise an error number.
  314. int create(CEPollDesc** ppd = 0);
  315. /// delete all user sockets (SRT sockets) from an EPoll
  316. /// @param [in] eid EPoll ID.
  317. /// @return 0
  318. int clear_usocks(int eid);
  319. /// add a system socket to an EPoll.
  320. /// @param [in] eid EPoll ID.
  321. /// @param [in] s system Socket ID.
  322. /// @param [in] events events to watch.
  323. /// @return 0 if success, otherwise an error number.
  324. int add_ssock(const int eid, const SYSSOCKET& s, const int* events = NULL);
  325. /// remove a system socket event from an EPoll; socket will be removed if no events to watch.
  326. /// @param [in] eid EPoll ID.
  327. /// @param [in] s system socket ID.
  328. /// @return 0 if success, otherwise an error number.
  329. int remove_ssock(const int eid, const SYSSOCKET& s);
  330. /// update a UDT socket events from an EPoll.
  331. /// @param [in] eid EPoll ID.
  332. /// @param [in] u UDT socket ID.
  333. /// @param [in] events events to watch.
  334. /// @return 0 if success, otherwise an error number.
  335. int update_usock(const int eid, const SRTSOCKET& u, const int* events);
  336. /// update a system socket events from an EPoll.
  337. /// @param [in] eid EPoll ID.
  338. /// @param [in] u UDT socket ID.
  339. /// @param [in] events events to watch.
  340. /// @return 0 if success, otherwise an error number.
  341. int update_ssock(const int eid, const SYSSOCKET& s, const int* events = NULL);
  342. /// wait for EPoll events or timeout.
  343. /// @param [in] eid EPoll ID.
  344. /// @param [out] readfds UDT sockets available for reading.
  345. /// @param [out] writefds UDT sockets available for writing.
  346. /// @param [in] msTimeOut timeout threshold, in milliseconds.
  347. /// @param [out] lrfds system file descriptors for reading.
  348. /// @param [out] lwfds system file descriptors for writing.
  349. /// @return number of sockets available for IO.
  350. int wait(const int eid, std::set<SRTSOCKET>* readfds, std::set<SRTSOCKET>* writefds, int64_t msTimeOut, std::set<SYSSOCKET>* lrfds, std::set<SYSSOCKET>* lwfds);
  351. typedef std::map<SRTSOCKET, int> fmap_t;
  352. /// Lightweit and more internal-reaching version of `uwait` for internal use only.
  353. /// This function wait for sockets to be ready and reports them in `st` map.
  354. ///
  355. /// @param d the internal structure of the epoll container
  356. /// @param st output container for the results: { socket_type, event }
  357. /// @param msTimeOut timeout after which return with empty output is allowed
  358. /// @param report_by_exception if true, errors will result in exception intead of returning -1
  359. /// @retval -1 error occurred
  360. /// @retval >=0 number of ready sockets (actually size of `st`)
  361. int swait(CEPollDesc& d, fmap_t& st, int64_t msTimeOut, bool report_by_exception = true);
  362. /// Empty subscription check - for internal use only.
  363. bool empty(const CEPollDesc& d) const;
  364. /// Reports which events are ready on the given socket.
  365. /// @param mp socket event map retirned by `swait`
  366. /// @param sock which socket to ask
  367. /// @return event flags for given socket, or 0 if none
  368. static int ready(const fmap_t& mp, SRTSOCKET sock)
  369. {
  370. fmap_t::const_iterator y = mp.find(sock);
  371. if (y == mp.end())
  372. return 0;
  373. return y->second;
  374. }
  375. /// Reports whether socket is ready for given event.
  376. /// @param mp socket event map retirned by `swait`
  377. /// @param sock which socket to ask
  378. /// @param event which events it should be ready for
  379. /// @return true if the given socket is ready for given event
  380. static bool isready(const fmap_t& mp, SRTSOCKET sock, SRT_EPOLL_OPT event)
  381. {
  382. return (ready(mp, sock) & event) != 0;
  383. }
  384. // Could be a template directly, but it's now hidden in the imp file.
  385. void clear_ready_usocks(CEPollDesc& d, int direction);
  386. /// wait for EPoll events or timeout optimized with explicit EPOLL_ERR event and the edge mode option.
  387. /// @param [in] eid EPoll ID.
  388. /// @param [out] fdsSet array of user socket events (SRT_EPOLL_IN | SRT_EPOLL_OUT | SRT_EPOLL_ERR).
  389. /// @param [int] fdsSize of fds array
  390. /// @param [in] msTimeOut timeout threshold, in milliseconds.
  391. /// @return total of available events in the epoll system (can be greater than fdsSize)
  392. int uwait(const int eid, SRT_EPOLL_EVENT* fdsSet, int fdsSize, int64_t msTimeOut);
  393. /// close and release an EPoll.
  394. /// @param [in] eid EPoll ID.
  395. /// @return 0 if success, otherwise an error number.
  396. int release(const int eid);
  397. public: // for CUDT to acknowledge IO status
  398. /// Update events available for a UDT socket. At the end this function
  399. /// counts the number of updated EIDs with given events.
  400. /// @param [in] uid UDT socket ID.
  401. /// @param [in] eids EPoll IDs to be set
  402. /// @param [in] events Combination of events to update
  403. /// @param [in] enable true -> enable, otherwise disable
  404. /// @return -1 if invalid events, otherwise the number of changes
  405. int update_events(const SRTSOCKET& uid, std::set<int>& eids, int events, bool enable);
  406. int setflags(const int eid, int32_t flags);
  407. private:
  408. int m_iIDSeed; // seed to generate a new ID
  409. srt::sync::Mutex m_SeedLock;
  410. std::map<int, CEPollDesc> m_mPolls; // all epolls
  411. mutable srt::sync::Mutex m_EPollLock;
  412. };
  413. #if ENABLE_HEAVY_LOGGING
  414. std::string DisplayEpollResults(const std::map<SRTSOCKET, int>& sockset);
  415. #endif
  416. } // namespace srt
  417. #endif