BReactor.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  1. /**
  2. * @file BReactor.h
  3. * @author Ambroz Bizjak <ambrop7@gmail.com>
  4. *
  5. * @section LICENSE
  6. *
  7. * Redistribution and use in source and binary forms, with or without
  8. * modification, are permitted provided that the following conditions are met:
  9. * 1. Redistributions of source code must retain the above copyright
  10. * notice, this list of conditions and the following disclaimer.
  11. * 2. Redistributions in binary form must reproduce the above copyright
  12. * notice, this list of conditions and the following disclaimer in the
  13. * documentation and/or other materials provided with the distribution.
  14. * 3. Neither the name of the author nor the
  15. * names of its contributors may be used to endorse or promote products
  16. * derived from this software without specific prior written permission.
  17. *
  18. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  19. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  20. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  21. * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
  22. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  23. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  24. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  25. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  26. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  27. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  28. *
  29. * @section DESCRIPTION
  30. *
  31. * Event loop that supports file desciptor (Linux) or HANDLE (Windows) events
  32. * and timers.
  33. */
  34. #ifndef BADVPN_SYSTEM_BREACTOR_H
  35. #define BADVPN_SYSTEM_BREACTOR_H
  36. #if (defined(BADVPN_USE_WINAPI) + defined(BADVPN_USE_EPOLL) + defined(BADVPN_USE_KEVENT) + defined(BADVPN_USE_POLL)) != 1
  37. #error Unknown event backend or too many event backends
  38. #endif
  39. #ifdef BADVPN_USE_WINAPI
  40. #include <windows.h>
  41. #endif
  42. #ifdef BADVPN_USE_EPOLL
  43. #include <sys/epoll.h>
  44. #endif
  45. #ifdef BADVPN_USE_KEVENT
  46. #include <sys/types.h>
  47. #include <sys/event.h>
  48. #include <sys/time.h>
  49. #endif
  50. #ifdef BADVPN_USE_POLL
  51. #include <poll.h>
  52. #endif
  53. #include <stdint.h>
  54. #include <misc/debug.h>
  55. #include <misc/debugcounter.h>
  56. #include <base/DebugObject.h>
  57. #include <structure/LinkedList1.h>
  58. #include <structure/BHeap.h>
  59. #include <system/BTime.h>
  60. #include <base/BPending.h>
  61. struct BTimer_t;
  62. /**
  63. * Handler function invoked when the timer expires.
  64. * The timer was in running state.
  65. * The timer enters not running state before this function is invoked.
  66. * This function is being called from within the timer's previosly
  67. * associated reactor.
  68. *
  69. * @param user value passed to {@link BTimer_Init}
  70. */
  71. typedef void (*BTimer_handler) (void *user);
  72. /**
  73. * Timer object used with {@link BReactor}.
  74. */
  75. typedef struct BTimer_t {
  76. btime_t msTime;
  77. BTimer_handler handler;
  78. void *handler_pointer;
  79. uint8_t active;
  80. uint8_t expired;
  81. btime_t absTime;
  82. union {
  83. BHeapNode heap_node;
  84. LinkedList1Node list_node;
  85. };
  86. } BTimer;
  87. /**
  88. * Initializes the timer object.
  89. * The timer object is initialized in not running state.
  90. *
  91. * @param bt the object
  92. * @param msTime default timeout in milliseconds
  93. * @param handler handler function invoked when the timer expires
  94. * @param user value to pass to the handler function
  95. */
  96. void BTimer_Init (BTimer *bt, btime_t msTime, BTimer_handler handler, void *user);
  97. /**
  98. * Checks if the timer is running.
  99. *
  100. * @param bt the object
  101. * @return 1 if running, 0 if not running
  102. */
  103. int BTimer_IsRunning (BTimer *bt);
  104. #ifndef BADVPN_USE_WINAPI
  105. struct BFileDescriptor_t;
  106. #define BREACTOR_READ (1 << 0)
  107. #define BREACTOR_WRITE (1 << 1)
  108. #define BREACTOR_ERROR (1 << 2)
  109. /**
  110. * Handler function invoked by the reactor when one or more events are detected.
  111. * The events argument will contain a subset of the monitored events (BREACTOR_READ, BREACTOR_WRITE),
  112. * plus possibly the error event (BREACTOR_ERROR).
  113. * The file descriptor object is in active state, being called from within
  114. * the associated reactor.
  115. *
  116. * @param user value passed to {@link BFileDescriptor_Init}
  117. * @param events bitmask composed of a subset of monitored events (BREACTOR_READ, BREACTOR_WRITE),
  118. * and possibly the error event (BREACTOR_ERROR).
  119. * Will be nonzero.
  120. */
  121. typedef void (*BFileDescriptor_handler) (void *user, int events);
  122. /**
  123. * File descriptor object used with {@link BReactor}.
  124. */
  125. typedef struct BFileDescriptor_t {
  126. int fd;
  127. BFileDescriptor_handler handler;
  128. void *user;
  129. int active;
  130. int waitEvents;
  131. #ifdef BADVPN_USE_EPOLL
  132. struct BFileDescriptor_t **epoll_returned_ptr;
  133. #endif
  134. #ifdef BADVPN_USE_KEVENT
  135. int kevent_tag;
  136. int **kevent_returned_ptr;
  137. #endif
  138. #ifdef BADVPN_USE_POLL
  139. LinkedList1Node poll_enabled_fds_list_node;
  140. int poll_returned_index;
  141. #endif
  142. } BFileDescriptor;
  143. /**
  144. * Intializes the file descriptor object.
  145. * The object is initialized in not active state.
  146. *
  147. * @param bs file descriptor object to initialize
  148. * @param fb file descriptor to represent
  149. * @param handler handler function invoked by the reactor when a monitored event is detected
  150. * @param user value passed to the handler functuon
  151. */
  152. void BFileDescriptor_Init (BFileDescriptor *bs, int fd, BFileDescriptor_handler handler, void *user);
  153. #endif
  154. // BReactor
  155. #define BSYSTEM_MAX_RESULTS 64
  156. #define BSYSTEM_MAX_HANDLES 64
  157. #define BSYSTEM_MAX_POLL_FDS 4096
  158. /**
  159. * Event loop that supports file desciptor (Linux) or HANDLE (Windows) events
  160. * and timers.
  161. */
  162. typedef struct {
  163. int exiting;
  164. int exit_code;
  165. // jobs
  166. BPendingGroup pending_jobs;
  167. // timers
  168. BHeap timers_heap;
  169. LinkedList1 timers_expired_list;
  170. // limits
  171. LinkedList1 active_limits_list;
  172. #ifdef BADVPN_USE_WINAPI
  173. LinkedList1 iocp_list;
  174. HANDLE iocp_handle;
  175. LinkedList1 iocp_ready_list;
  176. #endif
  177. #ifdef BADVPN_USE_EPOLL
  178. int efd; // epoll fd
  179. struct epoll_event epoll_results[BSYSTEM_MAX_RESULTS]; // epoll returned events buffer
  180. int epoll_results_num; // number of events in the array
  181. int epoll_results_pos; // number of events processed so far
  182. #endif
  183. #ifdef BADVPN_USE_KEVENT
  184. int kqueue_fd;
  185. struct kevent kevent_results[BSYSTEM_MAX_RESULTS];
  186. int kevent_results_num;
  187. int kevent_results_pos;
  188. #endif
  189. #ifdef BADVPN_USE_POLL
  190. LinkedList1 poll_enabled_fds_list;
  191. int poll_num_enabled_fds;
  192. int poll_results_num;
  193. int poll_results_pos;
  194. struct pollfd *poll_results_pollfds;
  195. BFileDescriptor **poll_results_bfds;
  196. #endif
  197. DebugObject d_obj;
  198. #ifndef BADVPN_USE_WINAPI
  199. DebugCounter d_fds_counter;
  200. #endif
  201. #ifdef BADVPN_USE_KEVENT
  202. DebugCounter d_kevent_ctr;
  203. #endif
  204. DebugCounter d_limits_ctr;
  205. } BReactor;
  206. /**
  207. * Initializes the reactor.
  208. * {@link BLog_Init} must have been done.
  209. * {@link BTime_Init} must have been done.
  210. *
  211. * @param bsys the object
  212. * @return 1 on success, 0 on failure
  213. */
  214. int BReactor_Init (BReactor *bsys) WARN_UNUSED;
  215. /**
  216. * Frees the reactor.
  217. * Must not be called from within the event loop ({@link BReactor_Exec}).
  218. * There must be no {@link BPending} objects using the pending group
  219. * returned by {@link BReactor_PendingGroup}.
  220. * There must be no running timers in this reactor.
  221. * There must be no limit objects in this reactor.
  222. * There must be no file descriptors or handles registered
  223. * with this reactor.
  224. * There must be no {@link BReactorKEvent} objects in this reactor.
  225. *
  226. * @param bsys the object
  227. */
  228. void BReactor_Free (BReactor *bsys);
  229. /**
  230. * Runs the event loop.
  231. *
  232. * @param bsys the object
  233. * @return value passed to {@link BReactor_Quit}
  234. */
  235. int BReactor_Exec (BReactor *bsys);
  236. /**
  237. * Causes the event loop ({@link BReactor_Exec}) to cease
  238. * dispatching events and return.
  239. * Any further calls of {@link BReactor_Exec} will return immediately.
  240. *
  241. * @param bsys the object
  242. * @param code value {@link BReactor_Exec} should return. If this is
  243. * called more than once, it will return the last code.
  244. */
  245. void BReactor_Quit (BReactor *bsys, int code);
  246. /**
  247. * Starts a timer to expire after its default time.
  248. * The timer must have been initialized with {@link BTimer_Init}.
  249. * If the timer is in running state, it must be associated with this reactor.
  250. * The timer enters running state, associated with this reactor.
  251. *
  252. * @param bsys the object
  253. * @param bt timer to start
  254. */
  255. void BReactor_SetTimer (BReactor *bsys, BTimer *bt);
  256. /**
  257. * Starts a timer to expire after a given time.
  258. * The timer must have been initialized with {@link BTimer_Init}.
  259. * If the timer is in running state, it must be associated with this reactor.
  260. * The timer enters running state, associated with this reactor.
  261. *
  262. * @param bsys the object
  263. * @param bt timer to start
  264. * @param after relative expiration time
  265. */
  266. void BReactor_SetTimerAfter (BReactor *bsys, BTimer *bt, btime_t after);
  267. /**
  268. * Starts a timer to expire at the specified time.
  269. * The timer must have been initialized with {@link BTimer_Init}.
  270. * If the timer is in running state, it must be associated with this reactor.
  271. * The timer enters running state, associated with this reactor.
  272. * The timer's expiration time is set to the time argument.
  273. *
  274. * @param bsys the object
  275. * @param bt timer to start
  276. * @param time absolute expiration time (according to {@link btime_gettime})
  277. */
  278. void BReactor_SetTimerAbsolute (BReactor *bsys, BTimer *bt, btime_t time);
  279. /**
  280. * Stops a timer.
  281. * If the timer is in running state, it must be associated with this reactor.
  282. * The timer enters not running state.
  283. *
  284. * @param bsys the object
  285. * @param bt timer to stop
  286. */
  287. void BReactor_RemoveTimer (BReactor *bsys, BTimer *bt);
  288. /**
  289. * Returns a {@link BPendingGroup} object that can be used to schedule jobs for
  290. * the reactor to execute. These jobs have complete priority over other events
  291. * (timers, file descriptors and Windows handles).
  292. * The returned pending group may only be used as an argument to {@link BPending_Init},
  293. * and must not be accessed by other means.
  294. * All {@link BPending} objects using this group must be freed before freeing
  295. * the reactor.
  296. *
  297. * @param bsys the object
  298. * @return pending group for scheduling jobs for the reactor to execute
  299. */
  300. BPendingGroup * BReactor_PendingGroup (BReactor *bsys);
  301. /**
  302. * Executes pending jobs until either:
  303. * - the reference job is reached, or
  304. * - {@link BReactor_Quit} is called.
  305. * The reference job must be reached before the job list empties.
  306. * The reference job will not be executed.
  307. *
  308. * WARNING: Use with care. This should only be used to to work around third-party software
  309. * that does not integrade into the jobs system. In particular, you should think about:
  310. * - the effects the jobs to be executed may have, and
  311. * - the environment those jobs expect to be executed in.
  312. *
  313. * @param bsys the object
  314. * @param ref reference job. It is not accessed in any way, only its address is compared to
  315. * pending jobs before they are executed.
  316. * @return 1 if the reference job was reached,
  317. * 0 if {@link BReactor_Quit} was called (either while executing a job, or before)
  318. */
  319. int BReactor_Synchronize (BReactor *bsys, BPending *ref);
  320. #ifndef BADVPN_USE_WINAPI
  321. /**
  322. * Starts monitoring a file descriptor.
  323. *
  324. * @param bsys the object
  325. * @param bs file descriptor object. Must have been initialized with
  326. * {@link BFileDescriptor_Init} Must be in not active state.
  327. * On success, the file descriptor object enters active state,
  328. * associated with this reactor.
  329. * @return 1 on success, 0 on failure
  330. */
  331. int BReactor_AddFileDescriptor (BReactor *bsys, BFileDescriptor *bs) WARN_UNUSED;
  332. /**
  333. * Stops monitoring a file descriptor.
  334. *
  335. * @param bsys the object
  336. * @param bs {@link BFileDescriptor} object. Must be in active state,
  337. * associated with this reactor. The file descriptor object
  338. * enters not active state.
  339. */
  340. void BReactor_RemoveFileDescriptor (BReactor *bsys, BFileDescriptor *bs);
  341. /**
  342. * Sets monitored file descriptor events.
  343. *
  344. * @param bsys the object
  345. * @param bs {@link BFileDescriptor} object. Must be in active state,
  346. * associated with this reactor.
  347. * @param events events to watch for. Must not have any bits other than
  348. * BREACTOR_READ and BREACTOR_WRITE.
  349. * This overrides previosly monitored events.
  350. */
  351. void BReactor_SetFileDescriptorEvents (BReactor *bsys, BFileDescriptor *bs, int events);
  352. #endif
  353. typedef struct {
  354. BReactor *reactor;
  355. int limit;
  356. int count;
  357. LinkedList1Node active_limits_list_node;
  358. DebugObject d_obj;
  359. } BReactorLimit;
  360. /**
  361. * Initializes a limit object.
  362. * A limit object consists of a counter integer, which is initialized to
  363. * zero, is incremented by {@link BReactorLimit_Increment} up to \a limit,
  364. * and is reset to zero every time the event loop performs a wait.
  365. * If the event loop has processed all detected events, and before performing
  366. * a wait, it determines that timers have expired, the counter will not be reset.
  367. *
  368. * @param o the object
  369. * @param reactor reactor the object is tied to
  370. * @param limit maximum counter value. Must be >0.
  371. */
  372. void BReactorLimit_Init (BReactorLimit *o, BReactor *reactor, int limit);
  373. /**
  374. * Frees a limit object.
  375. *
  376. * @param o the object
  377. */
  378. void BReactorLimit_Free (BReactorLimit *o);
  379. /**
  380. * Attempts to increment the counter of a limit object.
  381. *
  382. * @param o the object
  383. * @return 1 if the counter was lesser than the limit and was incremented,
  384. * 0 if the counter was greater or equal to the limit and could not be
  385. * incremented
  386. */
  387. int BReactorLimit_Increment (BReactorLimit *o);
  388. /**
  389. * Sets the limit of a limit object.
  390. *
  391. * @param o the object
  392. * @param limit new limit. Must be >0.
  393. */
  394. void BReactorLimit_SetLimit (BReactorLimit *o, int limit);
  395. #ifdef BADVPN_USE_KEVENT
  396. typedef void (*BReactorKEvent_handler) (void *user, u_int fflags, intptr_t data);
  397. typedef struct {
  398. BReactor *reactor;
  399. BReactorKEvent_handler handler;
  400. void *user;
  401. uintptr_t ident;
  402. short filter;
  403. int kevent_tag;
  404. int **kevent_returned_ptr;
  405. DebugObject d_obj;
  406. } BReactorKEvent;
  407. int BReactorKEvent_Init (BReactorKEvent *o, BReactor *reactor, BReactorKEvent_handler handler, void *user, uintptr_t ident, short filter, u_int fflags, intptr_t data);
  408. void BReactorKEvent_Free (BReactorKEvent *o);
  409. #endif
  410. #ifdef BADVPN_USE_WINAPI
  411. #define BREACTOR_IOCP_EVENT_SUCCEEDED 1
  412. #define BREACTOR_IOCP_EVENT_FAILED 2
  413. #define BREACTOR_IOCP_EVENT_EXITING 3
  414. typedef void (*BReactorIOCPOverlapped_handler) (void *user, int event, DWORD bytes);
  415. typedef struct {
  416. OVERLAPPED olap;
  417. BReactor *reactor;
  418. void *user;
  419. BReactorIOCPOverlapped_handler handler;
  420. LinkedList1Node iocp_list_node;
  421. int is_ready;
  422. LinkedList1Node ready_list_node;
  423. int ready_succeeded;
  424. DWORD ready_bytes;
  425. DebugObject d_obj;
  426. } BReactorIOCPOverlapped;
  427. HANDLE BReactor_GetIOCPHandle (BReactor *reactor);
  428. void BReactorIOCPOverlapped_Init (BReactorIOCPOverlapped *o, BReactor *reactor, void *user, BReactorIOCPOverlapped_handler handler);
  429. void BReactorIOCPOverlapped_Free (BReactorIOCPOverlapped *o);
  430. void BReactorIOCPOverlapped_Wait (BReactorIOCPOverlapped *o, int *out_succeeded, DWORD *out_bytes);
  431. #endif
  432. #endif