2
0

dasynq.h 85 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372
  1. #ifndef DASYNQ_H_
  2. #define DASYNQ_H_
  3. #include "dasynq/config.h"
  4. #include "dasynq/flags.h"
  5. #include "dasynq/stableheap.h"
  6. #include "dasynq/interrupt.h"
  7. #include "dasynq/util.h"
  8. // Dasynq uses a "mix-in" pattern to produce an event loop implementation incorporating selectable
  9. // implementations of various components (main backend, timers, child process watch mechanism etc). In C++
  10. // this can be achieved by a template for some component which extends its own type parameter:
  11. //
  12. // template <typename Base> class X : public B { .... }
  13. //
  14. // (Note that in a sense this is actually the opposite of the so-called "Curiously Recurring Template"
  15. // pattern, which can be used to achieve a similar goal). We can chain several such components together to
  16. // "mix in" the functionality of each into the final class, eg:
  17. //
  18. // template <typename T> using loop_t =
  19. // epoll_loop<interrupt_channel<timer_fd_events<child_proc_events<T>>>>;
  20. //
  21. // (which defines an alias template "loop_t", whose implementation will use the epoll backend, a standard
  22. // interrupt channel implementation, a timerfd-based timer implementation, and the standard child process
  23. // watch implementation). We sometimes need the base class to be able to call derived-class members: to do
  24. // this we pass a reference to the derived instance into a template member function in the base, for example
  25. // the "init" function:
  26. //
  27. // template <typename T> void init(T *derived)
  28. // {
  29. // // can call method on derived:
  30. // derived->add_listener();
  31. // // chain to next class:
  32. // Base::init(derived);
  33. // }
  34. //
  35. // The 'loop_t' defined above is a template for a usable backend mechanism for the event_loop template
  36. // class. At the base all this is the event_dispatch class, defined below, which receives event
  37. // notifications and inserts them into a queue for processing. The event_loop class, also below, wraps this
  38. // (via composition) in an interface which can be used to register/de-register/enable/disable event
  39. // watchers, and which can process the queued events by calling the watcher callbacks. The event_loop class
  40. // also provides some synchronisation to ensure thread-safety, and abstracts away some differences between
  41. // backends.
  42. //
  43. // The differences are exposed as traits, partly via a separate traits class (loop_traits_t as defined
  44. // below, which contains the "main" traits, particularly the sigdata_t, fd_r and fd_s types). Note that the
  45. // event_dispatch class exposes the loop traits as traits_t, and these are then potentially augmented at
  46. // each stage of the mechanism inheritance chain (i.e. the final traits are exposed as
  47. // `loop_t<event_dispatch>::traits_t'.
  48. //
  49. // The trait members are:
  50. // sigdata_t - a wrapper for the siginfo_t type or equivalent used to pass signal parameters
  51. // fd_r - a file descriptor wrapper, if the backend is able to retrieve the file descriptor when
  52. // it receives an fd event. Not all backends can do this.
  53. // fd_s - a file descriptor storage wrapper. If the backend can retrieve file descriptors, this
  54. // will be empty (and ideally zero-size), otherwise it stores a file descriptor.
  55. // With an fd_r and fd_s instance you can always retrieve the file descriptor:
  56. // `fdr.get_fd(fds)' will return it.
  57. // has_bidi_fd_watch
  58. // - boolean indicating whether a single watch can support watching for both input and output
  59. // events simultaneously
  60. // has_separate_rw_fd_watches
  61. // - boolean indicating whether it is possible to add separate input and output watches for the
  62. // same fd. Either this or has_bidi_fd_watch must be true.
  63. // interrupt_after_fd_add
  64. // - boolean indicating if a loop interrupt must be forced after adding/enabling an fd watch.
  65. // interrupt_after_signal_add
  66. // - boolean indicating if a loop interrupt must be forced after adding or enabling a signal
  67. // watch.
  68. // supports_non_oneshot_fd
  69. // - boolean; if true, event_dispatch can arm an fd watch without ONESHOT and returning zero
  70. // events from receive_fd_event (the event notification function) will leave the descriptor
  71. // armed. If false, all fd watches are effectively ONESHOT (they can be re-armed immediately
  72. // after delivery by returning an appropriate event flag mask).
  73. // full_timer_support
  74. // - boolean indicating that the monotonic and system clocks are actually different clocks and
  75. // that timers against the system clock will work correctly if the system clock time is
  76. // adjusted. If false, the monotonic clock may not be present at all (monotonic clock will map
  77. // to system clock), and timers against either clock are not guaranteed to work correctly if
  78. // the system clock is adjusted.
  79. #if DASYNQ_HAVE_EPOLL <= 0
  80. #if _POSIX_TIMERS > 0
  81. #include "dasynq/posixtimer.h"
  82. namespace dasynq {
  83. template <typename T, bool provide_mono_timer = true> using timer_events = posix_timer_events<T, provide_mono_timer>;
  84. } // namespace dasynq
  85. #else
  86. #include "dasynq/itimer.h"
  87. namespace dasynq {
  88. template <typename T, bool provide_mono_timer = true> using timer_events = itimer_events<T, provide_mono_timer>;
  89. } // namespace dasynq
  90. #endif
  91. #endif
  92. #if DASYNQ_HAVE_KQUEUE
  93. #if DASYNQ_KQUEUE_MACOS_WORKAROUND
  94. #include "dasynq/kqueue-macos.h"
  95. #include "dasynq/childproc.h"
  96. namespace dasynq {
  97. template <typename T> using loop_t = macos_kqueue_loop<timer_events<child_proc_events<interrupt_channel<T>>, false>>;
  98. using loop_traits_t = macos_kqueue_traits;
  99. } // namespace dasynq
  100. #else
  101. #include "dasynq/kqueue.h"
  102. #include "dasynq/childproc.h"
  103. namespace dasynq {
  104. template <typename T> using loop_t = kqueue_loop<timer_events<child_proc_events<interrupt_channel<T>>, false>>;
  105. using loop_traits_t = kqueue_traits;
  106. } // namespace dasynq
  107. #endif
  108. #elif DASYNQ_HAVE_EPOLL
  109. #include "dasynq/epoll.h"
  110. #include "dasynq/timerfd.h"
  111. #include "dasynq/childproc.h"
  112. namespace dasynq {
  113. template <typename T> using loop_t = epoll_loop<interrupt_channel<timer_fd_events<child_proc_events<T>>>>;
  114. using loop_traits_t = epoll_traits;
  115. } // namespace dasynq
  116. #else
  117. #include "dasynq/childproc.h"
  118. #if DASYNQ_HAVE_PSELECT
  119. #include "dasynq/pselect.h"
  120. namespace dasynq {
  121. template <typename T> using loop_t = pselect_events<timer_events<interrupt_channel<child_proc_events<T>>, false>>;
  122. using loop_traits_t = select_traits;
  123. } // namespace dasynq
  124. #else
  125. #include "dasynq/select.h"
  126. namespace dasynq {
  127. template <typename T> using loop_t = select_events<timer_events<interrupt_channel<child_proc_events<T>>, false>>;
  128. using loop_traits_t = select_traits;
  129. } // namespace dasynq
  130. #endif
  131. #endif
  132. #include <atomic>
  133. #include <condition_variable>
  134. #include <cstdint>
  135. #include <cstddef>
  136. #include <system_error>
  137. #include <unistd.h>
  138. #include <fcntl.h>
  139. #include "dasynq/mutex.h"
  140. #include "dasynq/basewatchers.h"
  141. namespace dasynq {
  142. /**
  143. * Values for rearm/disarm return from event handlers
  144. */
  145. enum class rearm
  146. {
  147. /** Re-arm the event watcher so that it receives further events */
  148. REARM,
  149. /** Disarm the event watcher so that it receives no further events, until it is re-armed explicitly */
  150. DISARM,
  151. /** Leave in current armed/disarmed state */
  152. NOOP,
  153. /** Remove the event watcher (and call "removed" callback) */
  154. REMOVE,
  155. /** The watcher has been removed - don't touch it! */
  156. REMOVED,
  157. /** RE-queue the watcher to have its notification called again */
  158. REQUEUE
  159. };
  160. // Tag type to specify that initialisation should be delayed
  161. class delayed_init {
  162. DASYNQ_EMPTY_BODY
  163. };
  164. namespace dprivate {
  165. // Classes for implementing a fair(ish) wait queue.
  166. // A queue node can be signalled when it reaches the head of
  167. // the queue.
  168. template <typename T_Mutex> class waitqueue;
  169. template <typename T_Mutex> class waitqueue_node;
  170. // Select an appropriate condition variable type for a mutex:
  171. // condition_variable if mutex is std::mutex, or condition_variable_any
  172. // otherwise.
  173. template <class T_Mutex> class condvar_selector;
  174. template <> class condvar_selector<std::mutex>
  175. {
  176. public:
  177. typedef std::condition_variable condvar;
  178. };
  179. template <class T_Mutex> class condvar_selector
  180. {
  181. public:
  182. typedef std::condition_variable_any condvar;
  183. };
  184. // For a single-threaded loop, the waitqueue is a no-op:
  185. template <> class waitqueue_node<null_mutex>
  186. {
  187. // Specialised waitqueue_node for null_mutex.
  188. friend class waitqueue<null_mutex>;
  189. public:
  190. void wait(std::unique_lock<null_mutex> &ul) { }
  191. void signal() { }
  192. DASYNQ_EMPTY_BODY
  193. };
  194. template <typename T_Mutex> class waitqueue_node
  195. {
  196. typename condvar_selector<T_Mutex>::condvar condvar;
  197. friend class waitqueue<T_Mutex>;
  198. // ptr to next node in queue, set to null when added to queue tail:
  199. waitqueue_node * next;
  200. public:
  201. void signal()
  202. {
  203. condvar.notify_one();
  204. }
  205. void wait(std::unique_lock<T_Mutex> &mutex_lock)
  206. {
  207. condvar.wait(mutex_lock);
  208. }
  209. };
  210. template <> class waitqueue<null_mutex>
  211. {
  212. public:
  213. // remove current head of queue, return new head:
  214. waitqueue_node<null_mutex> * unqueue()
  215. {
  216. return nullptr;
  217. }
  218. waitqueue_node<null_mutex> * get_head()
  219. {
  220. return nullptr;
  221. }
  222. waitqueue_node<null_mutex> * get_second()
  223. {
  224. return nullptr;
  225. }
  226. bool check_head(waitqueue_node<null_mutex> &node)
  227. {
  228. return true;
  229. }
  230. bool is_empty()
  231. {
  232. return true;
  233. }
  234. void queue(waitqueue_node<null_mutex> *node)
  235. {
  236. }
  237. };
  238. template <typename T_Mutex> class waitqueue
  239. {
  240. waitqueue_node<T_Mutex> * tail = nullptr;
  241. waitqueue_node<T_Mutex> * head = nullptr;
  242. public:
  243. // remove current head of queue, return new head:
  244. waitqueue_node<T_Mutex> * unqueue()
  245. {
  246. head = head->next;
  247. if (head == nullptr) {
  248. tail = nullptr;
  249. }
  250. return head;
  251. }
  252. waitqueue_node<T_Mutex> * get_head()
  253. {
  254. return head;
  255. }
  256. waitqueue_node<T_Mutex> * get_second()
  257. {
  258. return head->next;
  259. }
  260. bool check_head(waitqueue_node<T_Mutex> &node)
  261. {
  262. return head == &node;
  263. }
  264. bool is_empty()
  265. {
  266. return head == nullptr;
  267. }
  268. void queue(waitqueue_node<T_Mutex> *node)
  269. {
  270. node->next = nullptr;
  271. if (tail) {
  272. tail->next = node;
  273. }
  274. else {
  275. head = node;
  276. }
  277. tail = node;
  278. }
  279. };
  280. // friend of event_loop for giving access to various private members
  281. class loop_access {
  282. public:
  283. template <typename Loop>
  284. static typename Loop::mutex_t &get_base_lock(Loop &loop) noexcept
  285. {
  286. return loop.get_base_lock();
  287. }
  288. template <typename Loop>
  289. static rearm process_fd_rearm(Loop &loop, typename Loop::base_fd_watcher *bfw,
  290. rearm rearm_type) noexcept
  291. {
  292. return loop.process_fd_rearm(bfw, rearm_type);
  293. }
  294. template <typename Loop>
  295. static rearm process_primary_rearm(Loop &loop, typename Loop::base_bidi_fd_watcher *bdfw,
  296. rearm rearm_type) noexcept
  297. {
  298. return loop.process_primary_rearm(bdfw, rearm_type);
  299. }
  300. template <typename Loop>
  301. static rearm process_secondary_rearm(Loop &loop, typename Loop::base_bidi_fd_watcher * bdfw,
  302. base_watcher * outw, rearm rearm_type) noexcept
  303. {
  304. return loop.process_secondary_rearm(bdfw, outw, rearm_type);
  305. }
  306. template <typename Loop>
  307. static void process_signal_rearm(Loop &loop, typename Loop::base_signal_watcher * bsw,
  308. rearm rearm_type) noexcept
  309. {
  310. loop.process_signal_rearm(bsw, rearm_type);
  311. }
  312. template <typename Loop>
  313. static void process_child_watch_rearm(Loop &loop, typename Loop::base_child_watcher *bcw,
  314. rearm rearm_type) noexcept
  315. {
  316. loop.process_child_watch_rearm(bcw, rearm_type);
  317. }
  318. template <typename Loop>
  319. static void process_timer_rearm(Loop &loop, typename Loop::base_timer_watcher *btw,
  320. rearm rearm_type) noexcept
  321. {
  322. loop.process_timer_rearm(btw, rearm_type);
  323. }
  324. template <typename Loop>
  325. static void requeue_watcher(Loop &loop, base_watcher *watcher) noexcept
  326. {
  327. loop.requeue_watcher(watcher);
  328. }
  329. template <typename Loop>
  330. static void release_watcher(Loop &loop, base_watcher *watcher) noexcept
  331. {
  332. loop.release_watcher(watcher);
  333. }
  334. };
  335. // Do standard post-dispatch processing for a watcher. This handles the case of removing or
  336. // re-queueing watchers depending on the rearm type. This is called from the individual
  337. // watcher dispatch functions to handle REMOVE or REQUEUE re-arm values.
  338. template <typename Loop> void post_dispatch(Loop &loop, base_watcher *watcher, rearm rearm_type)
  339. {
  340. if (rearm_type == rearm::REMOVE) {
  341. loop_access::get_base_lock(loop).unlock();
  342. loop_access::release_watcher(loop, watcher);
  343. watcher->watch_removed();
  344. loop_access::get_base_lock(loop).lock();
  345. }
  346. else if (rearm_type == rearm::REQUEUE) {
  347. loop_access::requeue_watcher(loop, watcher);
  348. }
  349. }
  350. // Post-dispatch handling for bidi fd watchers.
  351. template <typename Loop> void post_dispatch(Loop &loop, bidi_fd_watcher<Loop> *bdfd_watcher,
  352. base_watcher *out_watcher, rearm rearm_type)
  353. {
  354. base_watcher *watcher = (base_watcher *)bdfd_watcher;
  355. if (rearm_type == rearm::REMOVE) {
  356. loop_access::get_base_lock(loop).unlock();
  357. loop_access::release_watcher(loop, watcher);
  358. loop_access::release_watcher(loop, out_watcher);
  359. watcher->watch_removed();
  360. loop_access::get_base_lock(loop).lock();
  361. }
  362. else if (rearm_type == rearm::REQUEUE) {
  363. loop_access::requeue_watcher(loop, watcher);
  364. }
  365. }
  366. // The event_dispatch class serves as the base class (mixin) for the backend mechanism. It
  367. // mostly manages queing and dequeing of events and maintains/owns the relevant data
  368. // structures, including a mutex lock.
  369. //
  370. // The backend mechanism should call one of the receiveXXX functions to notify of an event
  371. // received. The watcher will then be queued.
  372. //
  373. // In general the functions should be called with lock held. In practice this means that the
  374. // event loop backend implementations (that deposit received events here) must obtain the
  375. // lock; they are also free to use it to protect their own internal data structures.
  376. template <typename Traits, typename LoopTraits> class event_dispatch
  377. {
  378. friend class dasynq::event_loop<typename LoopTraits::mutex_t, LoopTraits>;;
  379. public:
  380. using mutex_t = typename LoopTraits::mutex_t;
  381. using traits_t = Traits;
  382. using delayed_init = dasynq::delayed_init;
  383. private:
  384. // queue data structure/pointer
  385. prio_queue event_queue;
  386. using base_signal_watcher = dprivate::base_signal_watcher<typename traits_t::sigdata_t>;
  387. using base_child_watcher = dprivate::base_child_watcher;
  388. using base_timer_watcher = dprivate::base_timer_watcher;
  389. // Add a watcher into the queueing system (but don't queue it). Call with lock held.
  390. // may throw: std::bad_alloc
  391. void prepare_watcher(base_watcher *bwatcher)
  392. {
  393. allocate_handle(event_queue, bwatcher->heap_handle, bwatcher);
  394. }
  395. void queue_watcher(base_watcher *bwatcher) noexcept
  396. {
  397. event_queue.insert(bwatcher->heap_handle, bwatcher->priority);
  398. }
  399. void dequeue_watcher(base_watcher *bwatcher) noexcept
  400. {
  401. if (event_queue.is_queued(bwatcher->heap_handle)) {
  402. event_queue.remove(bwatcher->heap_handle);
  403. }
  404. }
  405. // Remove watcher from the queueing system
  406. void release_watcher(base_watcher *bwatcher) noexcept
  407. {
  408. event_queue.deallocate(bwatcher->heap_handle);
  409. }
  410. protected:
  411. mutex_t lock;
  412. template <typename T> void init(T *loop) noexcept { }
  413. void cleanup() noexcept { }
  414. void sigmaskf(int how, const sigset_t *set, sigset_t *oset)
  415. {
  416. LoopTraits::sigmaskf(how, set, oset);
  417. }
  418. // Receive a signal; return true to disable signal watch or false to leave enabled.
  419. // Called with lock held.
  420. template <typename T>
  421. bool receive_signal(T &loop_mech, typename Traits::sigdata_t & siginfo, void * userdata) noexcept
  422. {
  423. base_signal_watcher * bwatcher = static_cast<base_signal_watcher *>(userdata);
  424. bwatcher->siginfo = siginfo;
  425. queue_watcher(bwatcher);
  426. return true;
  427. }
  428. // Receive fd event delivered from backend mechansim. Returns the desired watch mask, as per
  429. // set_fd_enabled, which can be used to leave the watch disabled, re-enable it or re-enable
  430. // one direction of a bi-directional watcher.
  431. template <typename T>
  432. std::tuple<int, typename Traits::fd_s> receive_fd_event(T &loop_mech, typename Traits::fd_r fd_r,
  433. void * userdata, int flags) noexcept
  434. {
  435. base_fd_watcher * bfdw = static_cast<base_fd_watcher *>(userdata);
  436. bfdw->event_flags |= flags;
  437. typename Traits::fd_s watch_fd_s {bfdw->watch_fd};
  438. base_watcher * bwatcher = bfdw;
  439. bool is_multi_watch = bfdw->watch_flags & multi_watch;
  440. if (is_multi_watch) {
  441. base_bidi_fd_watcher *bbdw = static_cast<base_bidi_fd_watcher *>(bwatcher);
  442. bbdw->watch_flags &= ~flags;
  443. if ((flags & IN_EVENTS) && (flags & OUT_EVENTS)) {
  444. // Queue the secondary watcher first:
  445. queue_watcher(&bbdw->out_watcher);
  446. }
  447. else if (flags & OUT_EVENTS) {
  448. // Use the secondary watcher for queueing:
  449. bwatcher = &(bbdw->out_watcher);
  450. }
  451. }
  452. queue_watcher(bwatcher);
  453. if (is_multi_watch && ! traits_t::has_separate_rw_fd_watches) {
  454. // If this is a bidirectional fd-watch, it has been disabled in *both* directions
  455. // as the event was delivered. However, the other direction should not be disabled
  456. // yet, so we need to re-enable:
  457. int in_out_mask = IN_EVENTS | OUT_EVENTS;
  458. if ((bfdw->watch_flags & in_out_mask) != 0) {
  459. // We need to re-enable the other channel now:
  460. return std::make_tuple((bfdw->watch_flags & in_out_mask) | ONE_SHOT, watch_fd_s);
  461. // We are the polling thread: don't need to interrupt polling, even if it would
  462. // normally be required.
  463. }
  464. }
  465. return std::make_tuple(0, watch_fd_s);
  466. }
  467. // Child process terminated. Called with both the main lock and the reaper lock held.
  468. void receive_child_stat(pid_t child, int status, void * userdata) noexcept
  469. {
  470. base_child_watcher * watcher = static_cast<base_child_watcher *>(userdata);
  471. watcher->child_status = status;
  472. watcher->child_termd = true;
  473. queue_watcher(watcher);
  474. }
  475. void receive_timer_expiry(timer_handle_t & timer_handle, void * userdata, int intervals) noexcept
  476. {
  477. base_timer_watcher * watcher = static_cast<base_timer_watcher *>(userdata);
  478. watcher->intervals += intervals;
  479. queue_watcher(watcher);
  480. }
  481. // Pull a single event from the queue; returns nullptr if the queue is empty.
  482. // Call with lock held.
  483. base_watcher * pull_queued_event() noexcept
  484. {
  485. if (event_queue.empty()) {
  486. return nullptr;
  487. }
  488. auto & rhndl = event_queue.get_root();
  489. base_watcher *r = dprivate::get_watcher(event_queue, rhndl);
  490. event_queue.pull_root();
  491. return r;
  492. }
  493. size_t num_queued_events() noexcept
  494. {
  495. return event_queue.size();
  496. }
  497. // Queue a watcher for removal, or issue "removed" callback to it.
  498. // Call with lock free.
  499. void issue_delete(base_watcher *watcher) noexcept
  500. {
  501. // This is only called when the attention lock is held, so if the watcher is not
  502. // active/queued now, it cannot become active (and will not be reported with an event)
  503. // during execution of this function.
  504. lock.lock();
  505. if (watcher->active) {
  506. // If the watcher is active, set deleteme true; the watcher will be removed
  507. // at the end of current processing (i.e. when active is set false).
  508. watcher->deleteme = true;
  509. lock.unlock();
  510. }
  511. else {
  512. // Actually do the delete.
  513. dequeue_watcher(watcher);
  514. release_watcher(watcher);
  515. lock.unlock();
  516. watcher->watch_removed();
  517. }
  518. }
  519. // Queue a watcher for removal, or issue "removed" callback to it.
  520. // Call with lock free.
  521. void issue_delete(base_bidi_fd_watcher *watcher) noexcept
  522. {
  523. lock.lock();
  524. if (watcher->active) {
  525. watcher->deleteme = true;
  526. release_watcher(watcher);
  527. }
  528. else {
  529. dequeue_watcher(watcher);
  530. release_watcher(watcher);
  531. watcher->read_removed = true;
  532. }
  533. base_watcher *secondary = &(watcher->out_watcher);
  534. if (secondary->active) {
  535. secondary->deleteme = true;
  536. release_watcher(watcher);
  537. }
  538. else {
  539. dequeue_watcher(secondary);
  540. release_watcher(watcher);
  541. watcher->write_removed = true;
  542. }
  543. if (watcher->read_removed && watcher->write_removed) {
  544. lock.unlock();
  545. watcher->watch_removed();
  546. }
  547. else {
  548. lock.unlock();
  549. }
  550. }
  551. event_dispatch() { }
  552. event_dispatch(const event_dispatch &) = delete;
  553. };
  554. } // namespace dasynq
  555. // This is the main event_loop implementation. It serves as an interface to the event loop backend (of which
  556. // it maintains an internal instance). It also serialises polling the backend and provides safe deletion of
  557. // watchers (see comments inline).
  558. //
  559. // The T_Mutex type parameter specifies the mutex type. A null_mutex can be used for a single-threaded event
  560. // loop; std::mutex, or any mutex providing a compatible interface, can be used for a thread-safe event
  561. // loop.
  562. //
  563. // The Traits type parameter specifies any required traits for the event loop. This specifies the back-end
  564. // to use (backend_t, a template) and the basic back-end traits (backend_traits_t).
  565. // The default is `default_traits<T_Mutex>'.
  566. //
  567. template <typename T_Mutex, typename Traits>
  568. class event_loop
  569. {
  570. using my_event_loop_t = event_loop<T_Mutex, Traits>;
  571. friend class dprivate::fd_watcher<my_event_loop_t>;
  572. friend class dprivate::bidi_fd_watcher<my_event_loop_t>;
  573. friend class dprivate::signal_watcher<my_event_loop_t>;
  574. friend class dprivate::child_proc_watcher<my_event_loop_t>;
  575. friend class dprivate::timer<my_event_loop_t>;
  576. friend class dprivate::loop_access;
  577. using backend_traits_t = typename Traits::backend_traits_t;
  578. template <typename T> using event_dispatch = dprivate::event_dispatch<T,Traits>;
  579. using dispatch_t = event_dispatch<backend_traits_t>;
  580. using loop_mech_t = typename Traits::template backend_t<dispatch_t>;
  581. using reaper_mutex_t = typename loop_mech_t::reaper_mutex_t;
  582. public:
  583. using traits_t = Traits;
  584. using loop_traits_t = typename loop_mech_t::traits_t;
  585. using mutex_t = T_Mutex;
  586. private:
  587. template <typename T> using waitqueue = dprivate::waitqueue<T>;
  588. template <typename T> using waitqueue_node = dprivate::waitqueue_node<T>;
  589. using base_watcher = dprivate::base_watcher;
  590. using base_signal_watcher = dprivate::base_signal_watcher<typename loop_traits_t::sigdata_t>;
  591. using base_fd_watcher = dprivate::base_fd_watcher;
  592. using base_bidi_fd_watcher = dprivate::base_bidi_fd_watcher;
  593. using base_child_watcher = dprivate::base_child_watcher;
  594. using base_timer_watcher = dprivate::base_timer_watcher;
  595. using watch_type_t = dprivate::watch_type_t;
  596. loop_mech_t loop_mech;
  597. // There is a complex problem with most asynchronous event notification mechanisms
  598. // when used in a multi-threaded environment. Generally, a file descriptor or other
  599. // event type that we are watching will be associated with some data used to manage
  600. // that event source. For example a web server needs to maintain information about
  601. // each client connection, such as the state of the connection (what protocol version
  602. // has been negotiated, etc; if a transfer is taking place, what file is being
  603. // transferred etc).
  604. //
  605. // However, sometimes we want to remove an event source (eg webserver wants to drop
  606. // a connection) and delete the associated data. The problem here is that it is
  607. // difficult to be sure when it is ok to actually remove the data, since when
  608. // requesting to unwatch the source in one thread it is still possible that an
  609. // event from that source is just being reported to another thread (in which case
  610. // the data will be needed).
  611. //
  612. // To solve that, we:
  613. // - allow only one thread to poll for events at a time, using a lock
  614. // - use the same lock to prevent polling, if we want to unwatch an event source
  615. // - generate an event to interrupt any polling that may already be occurring in
  616. // another thread
  617. // - mark handlers as active if they are currently executing, and
  618. // - when removing an active handler, simply set a flag which causes it to be
  619. // removed once the current processing is finished, rather than removing it
  620. // immediately.
  621. //
  622. // In particular the lock mechanism for preventing multiple threads polling and
  623. // for allowing polling to be interrupted is tricky. We can't use a simple mutex
  624. // since there is significant chance that it will be highly contended and there
  625. // are no guarantees that its acquisition will be fair. In particular, we don't
  626. // want a thread that is trying to unwatch a source being starved while another
  627. // thread polls the event source.
  628. //
  629. // So, we use two wait queues protected by a single mutex. The "attn_waitqueue"
  630. // (attention queue) is the high-priority queue, used for threads wanting to
  631. // unwatch event sources. The "wait_waitquueue" is the queue used by threads
  632. // that wish to actually poll for events, while they are waiting for the main
  633. // queue to become quiet.
  634. // - The head of the "attn_waitqueue" is always the holder of the lock
  635. // - Therefore, a poll-waiter must be moved from the wait_waitqueue to the
  636. // attn_waitqueue to actually gain the lock. This is only done if the
  637. // attn_waitqueue is otherwise empty.
  638. // - The mutex only protects manipulation of the wait queues, and so should not
  639. // be highly contended.
  640. //
  641. // To claim the lock for a poll-wait, the procedure is:
  642. // - check if the attn_waitqueue is empty;
  643. // - if it is, insert node at the head, thus claiming the lock, and return
  644. // - otherwise, insert node in the wait_waitqueue, and wait
  645. // To claim the lock for an unwatch, the procedure is:
  646. // - insert node in the attn_waitqueue
  647. // - if the node is at the head of the queue, lock is claimed; return
  648. // - otherwise, if a poll is in progress, interrupt it
  649. // - wait until our node is at the head of the attn_waitqueue
  650. mutex_t wait_lock; // protects the wait/attention queues
  651. bool long_poll_running = false; // whether any thread is polling the backend (with non-zero timeout)
  652. waitqueue<mutex_t> attn_waitqueue;
  653. waitqueue<mutex_t> wait_waitqueue;
  654. mutex_t &get_base_lock() noexcept
  655. {
  656. return loop_mech.lock;
  657. }
  658. reaper_mutex_t &get_reaper_lock() noexcept
  659. {
  660. return loop_mech.get_reaper_lock();
  661. }
  662. void register_signal(base_signal_watcher *callBack, int signo)
  663. {
  664. std::lock_guard<mutex_t> guard(loop_mech.lock);
  665. loop_mech.prepare_watcher(callBack);
  666. try {
  667. loop_mech.add_signal_watch_nolock(signo, callBack);
  668. if (backend_traits_t::interrupt_after_signal_add) {
  669. interrupt_if_necessary();
  670. }
  671. }
  672. catch (...) {
  673. loop_mech.release_watcher(callBack);
  674. throw;
  675. }
  676. }
  677. void deregister(base_signal_watcher *callBack, int signo) noexcept
  678. {
  679. loop_mech.remove_signal_watch(signo);
  680. waitqueue_node<T_Mutex> qnode;
  681. get_attn_lock(qnode);
  682. loop_mech.issue_delete(callBack);
  683. release_lock(qnode);
  684. }
  685. void register_fd(base_fd_watcher *callback, int fd, int eventmask, bool enabled, bool emulate = false)
  686. {
  687. std::lock_guard<mutex_t> guard(loop_mech.lock);
  688. loop_mech.prepare_watcher(callback);
  689. try {
  690. if (! loop_mech.add_fd_watch(fd, callback, eventmask | ONE_SHOT, enabled, emulate)) {
  691. callback->emulatefd = true;
  692. callback->emulate_enabled = enabled;
  693. if (enabled) {
  694. callback->event_flags = eventmask & IO_EVENTS;
  695. if (eventmask & IO_EVENTS) {
  696. requeue_watcher(callback);
  697. }
  698. }
  699. }
  700. else if (enabled && backend_traits_t::interrupt_after_fd_add) {
  701. interrupt_if_necessary();
  702. }
  703. }
  704. catch (...) {
  705. loop_mech.release_watcher(callback);
  706. throw;
  707. }
  708. }
  709. // Register a bidi fd watcher. The watch_flags should already be set to the eventmask to watch
  710. // (i.e. eventmask == callback->watch_flags is a pre-condition).
  711. void register_fd(base_bidi_fd_watcher *callback, int fd, int eventmask, bool emulate = false)
  712. {
  713. std::lock_guard<mutex_t> guard(loop_mech.lock);
  714. loop_mech.prepare_watcher(callback);
  715. try {
  716. loop_mech.prepare_watcher(&callback->out_watcher);
  717. try {
  718. bool do_interrupt = false;
  719. if (backend_traits_t::has_separate_rw_fd_watches) {
  720. int r = loop_mech.add_bidi_fd_watch(fd, callback, eventmask | ONE_SHOT, emulate);
  721. if (r & IN_EVENTS) {
  722. callback->emulatefd = true;
  723. if (eventmask & IN_EVENTS) {
  724. callback->watch_flags &= ~IN_EVENTS;
  725. requeue_watcher(callback);
  726. }
  727. }
  728. else if ((eventmask & IN_EVENTS) && backend_traits_t::interrupt_after_fd_add) {
  729. do_interrupt = true;
  730. }
  731. if (r & OUT_EVENTS) {
  732. callback->out_watcher.emulatefd = true;
  733. if (eventmask & OUT_EVENTS) {
  734. callback->watch_flags &= ~OUT_EVENTS;
  735. requeue_watcher(&callback->out_watcher);
  736. }
  737. }
  738. else if ((eventmask & OUT_EVENTS) && backend_traits_t::interrupt_after_fd_add) {
  739. do_interrupt = true;
  740. }
  741. }
  742. else {
  743. if (! loop_mech.add_fd_watch(fd, callback, eventmask | ONE_SHOT, true, emulate)) {
  744. callback->emulatefd = true;
  745. callback->out_watcher.emulatefd = true;
  746. if (eventmask & IN_EVENTS) {
  747. callback->watch_flags &= ~IN_EVENTS;
  748. requeue_watcher(callback);
  749. }
  750. if (eventmask & OUT_EVENTS) {
  751. callback->watch_flags &= ~OUT_EVENTS;
  752. requeue_watcher(&callback->out_watcher);
  753. }
  754. }
  755. else if (backend_traits_t::interrupt_after_fd_add) {
  756. do_interrupt = true;
  757. }
  758. }
  759. if (do_interrupt) {
  760. interrupt_if_necessary();
  761. }
  762. }
  763. catch (...) {
  764. loop_mech.release_watcher(&callback->out_watcher);
  765. throw;
  766. }
  767. }
  768. catch (...) {
  769. loop_mech.release_watcher(callback);
  770. throw;
  771. }
  772. }
  773. void set_fd_enabled(base_watcher *watcher, int fd, int watch_flags, bool enabled) noexcept
  774. {
  775. if (enabled) {
  776. loop_mech.enable_fd_watch(fd, watcher, watch_flags | ONE_SHOT);
  777. if (backend_traits_t::interrupt_after_fd_add) {
  778. interrupt_if_necessary();
  779. }
  780. }
  781. else {
  782. loop_mech.disable_fd_watch(fd, watch_flags);
  783. }
  784. }
  785. void set_fd_enabled_nolock(base_watcher *watcher, int fd, int watch_flags, bool enabled) noexcept
  786. {
  787. if (enabled) {
  788. loop_mech.enable_fd_watch_nolock(fd, watcher, watch_flags | ONE_SHOT);
  789. if (backend_traits_t::interrupt_after_fd_add) {
  790. interrupt_if_necessary();
  791. }
  792. }
  793. else {
  794. loop_mech.disable_fd_watch_nolock(fd, watch_flags);
  795. }
  796. }
  797. void deregister(base_fd_watcher *callback, int fd) noexcept
  798. {
  799. if (callback->emulatefd) {
  800. auto & ed = (dispatch_t &) loop_mech;
  801. ed.issue_delete(callback);
  802. return;
  803. }
  804. loop_mech.remove_fd_watch(fd, callback->watch_flags);
  805. waitqueue_node<T_Mutex> qnode;
  806. get_attn_lock(qnode);
  807. auto & ed = (dispatch_t &) loop_mech;
  808. ed.issue_delete(callback);
  809. release_lock(qnode);
  810. }
  811. void deregister(base_bidi_fd_watcher *callback, int fd) noexcept
  812. {
  813. if (backend_traits_t::has_separate_rw_fd_watches) {
  814. loop_mech.remove_bidi_fd_watch(fd);
  815. }
  816. else {
  817. loop_mech.remove_fd_watch(fd, callback->watch_flags);
  818. }
  819. waitqueue_node<T_Mutex> qnode;
  820. get_attn_lock(qnode);
  821. dispatch_t & ed = (dispatch_t &) loop_mech;
  822. ed.issue_delete(callback);
  823. release_lock(qnode);
  824. }
  825. void reserve_child_watch(base_child_watcher *callback)
  826. {
  827. std::lock_guard<mutex_t> guard(loop_mech.lock);
  828. loop_mech.prepare_watcher(callback);
  829. try {
  830. loop_mech.reserve_child_watch_nolock(callback->watch_handle);
  831. }
  832. catch (...) {
  833. loop_mech.release_watcher(callback);
  834. throw;
  835. }
  836. }
  837. void unreserve(base_child_watcher *callback) noexcept
  838. {
  839. std::lock_guard<mutex_t> guard(loop_mech.lock);
  840. loop_mech.unreserve_child_watch(callback->watch_handle);
  841. loop_mech.release_watcher(callback);
  842. }
  843. void register_child(base_child_watcher *callback, pid_t child)
  844. {
  845. std::lock_guard<mutex_t> guard(loop_mech.lock);
  846. loop_mech.prepare_watcher(callback);
  847. try {
  848. loop_mech.add_child_watch_nolock(callback->watch_handle, child, callback);
  849. }
  850. catch (...) {
  851. loop_mech.release_watcher(callback);
  852. throw;
  853. }
  854. }
  855. void register_reserved_child(base_child_watcher *callback, pid_t child) noexcept
  856. {
  857. loop_mech.add_reserved_child_watch(callback->watch_handle, child, callback);
  858. }
  859. void register_reserved_child_nolock(base_child_watcher *callback, pid_t child) noexcept
  860. {
  861. loop_mech.add_reserved_child_watch_nolock(callback->watch_handle, child, callback);
  862. }
  863. void deregister(base_child_watcher *callback, pid_t child) noexcept
  864. {
  865. loop_mech.remove_child_watch(callback->watch_handle);
  866. waitqueue_node<T_Mutex> qnode;
  867. get_attn_lock(qnode);
  868. loop_mech.issue_delete(callback);
  869. release_lock(qnode);
  870. }
  871. // Stop watching a child process, but retain watch reservation so that another child can be
  872. // watched without running into resource allocation issues.
  873. void stop_watch(base_child_watcher *callback) noexcept
  874. {
  875. loop_mech.stop_child_watch(callback->watch_handle);
  876. }
  877. void register_timer(base_timer_watcher *callback, clock_type clock)
  878. {
  879. std::lock_guard<mutex_t> guard(loop_mech.lock);
  880. loop_mech.prepare_watcher(callback);
  881. try {
  882. loop_mech.add_timer_nolock(callback->timer_handle, callback, clock);
  883. }
  884. catch (...) {
  885. loop_mech.release_watcher(callback);
  886. }
  887. }
  888. void set_timer(base_timer_watcher *callBack, const timespec &timeout, clock_type clock) noexcept
  889. {
  890. struct timespec interval {0, 0};
  891. loop_mech.set_timer(callBack->timer_handle, timeout, interval, true, clock);
  892. }
  893. void set_timer(base_timer_watcher *callBack, const timespec &timeout, const timespec &interval,
  894. clock_type clock) noexcept
  895. {
  896. loop_mech.set_timer(callBack->timer_handle, timeout, interval, true, clock);
  897. }
  898. void set_timer_rel(base_timer_watcher *callBack, const timespec &timeout, clock_type clock) noexcept
  899. {
  900. struct timespec interval {0, 0};
  901. loop_mech.set_timer_rel(callBack->timer_handle, timeout, interval, true, clock);
  902. }
  903. void set_timer_rel(base_timer_watcher *callBack, const timespec &timeout,
  904. const timespec &interval, clock_type clock) noexcept
  905. {
  906. loop_mech.set_timer_rel(callBack->timer_handle, timeout, interval, true, clock);
  907. }
  908. void set_timer_enabled(base_timer_watcher *callback, clock_type clock, bool enabled) noexcept
  909. {
  910. loop_mech.enable_timer(callback->timer_handle, enabled, clock);
  911. }
  912. void set_timer_enabled_nolock(base_timer_watcher *callback, clock_type clock, bool enabled) noexcept
  913. {
  914. loop_mech.enable_timer_nolock(callback->timer_handle, enabled, clock);
  915. }
  916. void stop_timer(base_timer_watcher *callback, clock_type clock) noexcept
  917. {
  918. loop_mech.stop_timer(callback->timer_handle, clock);
  919. }
  920. void deregister(base_timer_watcher *callback, clock_type clock) noexcept
  921. {
  922. loop_mech.remove_timer(callback->timer_handle, clock);
  923. waitqueue_node<T_Mutex> qnode;
  924. get_attn_lock(qnode);
  925. loop_mech.issue_delete(callback);
  926. release_lock(qnode);
  927. }
  928. void dequeue_watcher(base_watcher *watcher) noexcept
  929. {
  930. loop_mech.dequeue_watcher(watcher);
  931. }
  932. void requeue_watcher(base_watcher *watcher) noexcept
  933. {
  934. loop_mech.queue_watcher(watcher);
  935. interrupt_if_necessary();
  936. }
  937. void release_watcher(base_watcher *watcher) noexcept
  938. {
  939. loop_mech.release_watcher(watcher);
  940. }
  941. // Interrupt the current poll-waiter, if necessary - that is, if the loop is multi-thread safe, and if
  942. // there is currently another thread polling the backend event mechanism.
  943. void interrupt_if_necessary()
  944. {
  945. wait_lock.lock();
  946. bool attn_q_empty = attn_waitqueue.is_empty(); // (always false for single-threaded loops)
  947. wait_lock.unlock();
  948. if (! attn_q_empty) {
  949. loop_mech.interrupt_wait();
  950. }
  951. }
  952. // Acquire the attention lock (when held, ensures that no thread is polling the AEN
  953. // mechanism). This can be used to safely remove watches, since it is certain that
  954. // notification callbacks won't be run while the attention lock is held. Any in-progress
  955. // poll will be interrupted so that the lock should be acquired quickly.
  956. void get_attn_lock(waitqueue_node<T_Mutex> &qnode) noexcept
  957. {
  958. std::unique_lock<T_Mutex> ulock(wait_lock);
  959. attn_waitqueue.queue(&qnode);
  960. if (! attn_waitqueue.check_head(qnode)) {
  961. if (long_poll_running) {
  962. // We want to interrupt any in-progress poll so that the attn queue will progress
  963. // but we don't want to do that unnecessarily. If we are 2nd in the queue then the
  964. // head must be doing the poll; interrupt it. Otherwise, we assume the 2nd has
  965. // already interrupted it.
  966. if (attn_waitqueue.get_second() == &qnode) {
  967. loop_mech.interrupt_wait();
  968. }
  969. }
  970. while (! attn_waitqueue.check_head(qnode)) {
  971. qnode.wait(ulock);
  972. }
  973. }
  974. }
  975. // Acquire the attention lock, but without interrupting any poll that's in progress
  976. // (prefer to fail in that case).
  977. bool poll_attn_lock(waitqueue_node<T_Mutex> &qnode) noexcept
  978. {
  979. std::unique_lock<T_Mutex> ulock(wait_lock);
  980. if (long_poll_running) {
  981. // There are poll-waiters, bail out
  982. return false;
  983. }
  984. // Nobody's doing a long poll, wait until we're at the head of the attn queue and return
  985. // success:
  986. attn_waitqueue.queue(&qnode);
  987. while (! attn_waitqueue.check_head(qnode)) {
  988. qnode.wait(ulock);
  989. }
  990. return true;
  991. }
  992. // Acquire the poll-wait lock (to be held when polling the AEN mechanism; lower priority than
  993. // the attention lock). The poll-wait lock is used to prevent more than a single thread from
  994. // polling the event loop mechanism at a time; if this is not done, it is basically
  995. // impossible to safely deregister watches.
  996. void get_pollwait_lock(waitqueue_node<T_Mutex> &qnode) noexcept
  997. {
  998. std::unique_lock<T_Mutex> ulock(wait_lock);
  999. if (attn_waitqueue.is_empty()) {
  1000. // Queue is completely empty:
  1001. attn_waitqueue.queue(&qnode);
  1002. }
  1003. else {
  1004. wait_waitqueue.queue(&qnode);
  1005. }
  1006. while (! attn_waitqueue.check_head(qnode)) {
  1007. qnode.wait(ulock);
  1008. }
  1009. long_poll_running = true;
  1010. }
  1011. // Release the poll-wait/attention lock.
  1012. void release_lock(waitqueue_node<T_Mutex> &qnode) noexcept
  1013. {
  1014. std::unique_lock<T_Mutex> ulock(wait_lock);
  1015. long_poll_running = false;
  1016. waitqueue_node<T_Mutex> * nhead = attn_waitqueue.unqueue();
  1017. if (nhead != nullptr) {
  1018. // Someone else now owns the lock, signal them to wake them up
  1019. nhead->signal();
  1020. }
  1021. else {
  1022. // Nobody is waiting in attn_waitqueue (the high-priority queue) so check in
  1023. // wait_waitqueue (the low-priority queue)
  1024. if (! wait_waitqueue.is_empty()) {
  1025. auto nhead = wait_waitqueue.get_head();
  1026. wait_waitqueue.unqueue();
  1027. attn_waitqueue.queue(nhead);
  1028. long_poll_running = true;
  1029. nhead->signal();
  1030. }
  1031. }
  1032. }
  1033. void process_signal_rearm(base_signal_watcher * bsw, rearm rearm_type) noexcept
  1034. {
  1035. // Called with lock held
  1036. if (rearm_type == rearm::REARM) {
  1037. loop_mech.rearm_signal_watch_nolock(bsw->siginfo.get_signo(), bsw);
  1038. if (backend_traits_t::interrupt_after_signal_add) {
  1039. interrupt_if_necessary();
  1040. }
  1041. }
  1042. else if (rearm_type == rearm::REMOVE) {
  1043. loop_mech.remove_signal_watch_nolock(bsw->siginfo.get_signo());
  1044. }
  1045. // Note that signal watchers cannot (currently) be disarmed
  1046. }
  1047. // Process rearm return from an fd_watcher, including the primary watcher of a bidi_fd_watcher.
  1048. // Depending on the rearm value, we re-arm, remove, or disarm the watcher, etc.
  1049. rearm process_fd_rearm(base_fd_watcher * bfw, rearm rearm_type) noexcept
  1050. {
  1051. bool emulatedfd = static_cast<base_watcher *>(bfw)->emulatefd;
  1052. if (emulatedfd) {
  1053. if (rearm_type == rearm::REARM) {
  1054. bfw->emulate_enabled = true;
  1055. rearm_type = rearm::REQUEUE;
  1056. }
  1057. else if (rearm_type == rearm::DISARM) {
  1058. bfw->emulate_enabled = false;
  1059. }
  1060. else if (rearm_type == rearm::NOOP) {
  1061. if (bfw->emulate_enabled) {
  1062. rearm_type = rearm::REQUEUE;
  1063. }
  1064. }
  1065. }
  1066. else if (rearm_type == rearm::REARM) {
  1067. set_fd_enabled_nolock(bfw, bfw->watch_fd,
  1068. bfw->watch_flags & (IN_EVENTS | OUT_EVENTS), true);
  1069. }
  1070. else if (rearm_type == rearm::DISARM) {
  1071. loop_mech.disable_fd_watch_nolock(bfw->watch_fd, bfw->watch_flags);
  1072. }
  1073. else if (rearm_type == rearm::REMOVE) {
  1074. loop_mech.remove_fd_watch_nolock(bfw->watch_fd, bfw->watch_flags);
  1075. }
  1076. return rearm_type;
  1077. }
  1078. // Process rearm option from the primary watcher in bidi_fd_watcher
  1079. rearm process_primary_rearm(base_bidi_fd_watcher * bdfw, rearm rearm_type) noexcept
  1080. {
  1081. bool emulatedfd = static_cast<base_watcher *>(bdfw)->emulatefd;
  1082. // Called with lock held
  1083. if (rearm_type == rearm::REMOVE) {
  1084. bdfw->read_removed = 1;
  1085. if (backend_traits_t::has_separate_rw_fd_watches) {
  1086. bdfw->watch_flags &= ~IN_EVENTS;
  1087. if (! emulatedfd) {
  1088. loop_mech.remove_fd_watch_nolock(bdfw->watch_fd, IN_EVENTS);
  1089. }
  1090. return bdfw->write_removed ? rearm::REMOVE : rearm::NOOP;
  1091. }
  1092. else {
  1093. if (! bdfw->write_removed) {
  1094. if (bdfw->watch_flags & IN_EVENTS) {
  1095. bdfw->watch_flags &= ~IN_EVENTS;
  1096. if (! emulatedfd) {
  1097. set_fd_enabled_nolock(bdfw, bdfw->watch_fd, bdfw->watch_flags,
  1098. bdfw->watch_flags != 0);
  1099. }
  1100. }
  1101. return rearm::NOOP;
  1102. }
  1103. else {
  1104. // both removed: actually remove
  1105. if (! emulatedfd) {
  1106. loop_mech.remove_fd_watch_nolock(bdfw->watch_fd, 0 /* not used */);
  1107. }
  1108. return rearm::REMOVE;
  1109. }
  1110. }
  1111. }
  1112. else if (rearm_type == rearm::DISARM) {
  1113. bdfw->watch_flags &= ~IN_EVENTS;
  1114. if (! emulatedfd) {
  1115. if (! backend_traits_t::has_separate_rw_fd_watches) {
  1116. int watch_flags = bdfw->watch_flags & (IN_EVENTS | OUT_EVENTS);
  1117. set_fd_enabled_nolock(bdfw, bdfw->watch_fd, watch_flags, watch_flags != 0);
  1118. }
  1119. else {
  1120. loop_mech.disable_fd_watch_nolock(bdfw->watch_fd, IN_EVENTS);
  1121. }
  1122. }
  1123. }
  1124. else if (rearm_type == rearm::REARM) {
  1125. if (! emulatedfd) {
  1126. bdfw->watch_flags |= IN_EVENTS;
  1127. if (! backend_traits_t::has_separate_rw_fd_watches) {
  1128. int watch_flags = bdfw->watch_flags;
  1129. set_fd_enabled_nolock(bdfw, bdfw->watch_fd,
  1130. watch_flags & (IN_EVENTS | OUT_EVENTS), true);
  1131. }
  1132. else {
  1133. set_fd_enabled_nolock(bdfw, bdfw->watch_fd, IN_EVENTS, true);
  1134. }
  1135. }
  1136. else {
  1137. bdfw->watch_flags &= ~IN_EVENTS;
  1138. rearm_type = rearm::REQUEUE;
  1139. }
  1140. }
  1141. else if (rearm_type == rearm::NOOP) {
  1142. if (bdfw->emulatefd) {
  1143. if (bdfw->watch_flags & IN_EVENTS) {
  1144. bdfw->watch_flags &= ~IN_EVENTS;
  1145. rearm_type = rearm::REQUEUE;
  1146. }
  1147. }
  1148. }
  1149. return rearm_type;
  1150. }
  1151. // Process re-arm for the secondary (output) watcher in a Bi-direction Fd watcher.
  1152. rearm process_secondary_rearm(base_bidi_fd_watcher * bdfw, base_watcher * outw, rearm rearm_type) noexcept
  1153. {
  1154. bool emulatedfd = outw->emulatefd;
  1155. // Called with lock held
  1156. if (emulatedfd) {
  1157. if (rearm_type == rearm::REMOVE) {
  1158. bdfw->write_removed = 1;
  1159. bdfw->watch_flags &= ~OUT_EVENTS;
  1160. rearm_type = bdfw->read_removed ? rearm::REMOVE : rearm::NOOP;
  1161. }
  1162. else if (rearm_type == rearm::DISARM) {
  1163. bdfw->watch_flags &= ~OUT_EVENTS;
  1164. }
  1165. else if (rearm_type == rearm::REARM) {
  1166. bdfw->watch_flags &= ~OUT_EVENTS;
  1167. rearm_type = rearm::REQUEUE;
  1168. }
  1169. else if (rearm_type == rearm::NOOP) {
  1170. if (bdfw->watch_flags & OUT_EVENTS) {
  1171. bdfw->watch_flags &= ~OUT_EVENTS;
  1172. rearm_type = rearm::REQUEUE;
  1173. }
  1174. }
  1175. return rearm_type;
  1176. }
  1177. else if (rearm_type == rearm::REMOVE) {
  1178. bdfw->write_removed = 1;
  1179. if (backend_traits_t::has_separate_rw_fd_watches) {
  1180. bdfw->watch_flags &= ~OUT_EVENTS;
  1181. loop_mech.remove_fd_watch_nolock(bdfw->watch_fd, OUT_EVENTS);
  1182. return bdfw->read_removed ? rearm::REMOVE : rearm::NOOP;
  1183. }
  1184. else {
  1185. if (! bdfw->read_removed) {
  1186. if (bdfw->watch_flags & OUT_EVENTS) {
  1187. bdfw->watch_flags &= ~OUT_EVENTS;
  1188. set_fd_enabled_nolock(bdfw, bdfw->watch_fd, bdfw->watch_flags, true);
  1189. }
  1190. return rearm::NOOP;
  1191. }
  1192. else {
  1193. // both removed: actually remove
  1194. loop_mech.remove_fd_watch_nolock(bdfw->watch_fd, 0 /* not used */);
  1195. return rearm::REMOVE;
  1196. }
  1197. }
  1198. }
  1199. else if (rearm_type == rearm::DISARM) {
  1200. bdfw->watch_flags &= ~OUT_EVENTS;
  1201. if (! backend_traits_t::has_separate_rw_fd_watches) {
  1202. int watch_flags = bdfw->watch_flags;
  1203. set_fd_enabled_nolock(bdfw, bdfw->watch_fd, watch_flags & (IN_EVENTS | OUT_EVENTS), true);
  1204. }
  1205. else {
  1206. loop_mech.disable_fd_watch_nolock(bdfw->watch_fd, OUT_EVENTS);
  1207. }
  1208. }
  1209. else if (rearm_type == rearm::REARM) {
  1210. bdfw->watch_flags |= OUT_EVENTS;
  1211. if (! backend_traits_t::has_separate_rw_fd_watches) {
  1212. int watch_flags = bdfw->watch_flags;
  1213. set_fd_enabled_nolock(bdfw, bdfw->watch_fd, watch_flags & (IN_EVENTS | OUT_EVENTS), true);
  1214. }
  1215. else {
  1216. set_fd_enabled_nolock(bdfw, bdfw->watch_fd, OUT_EVENTS | ONE_SHOT, true);
  1217. }
  1218. }
  1219. return rearm_type;
  1220. }
  1221. void process_child_watch_rearm(base_child_watcher *bcw, rearm rearm_type) noexcept
  1222. {
  1223. if (rearm_type == rearm::REMOVE || rearm_type == rearm::DISARM) {
  1224. loop_mech.unreserve_child_watch_nolock(bcw->watch_handle);
  1225. }
  1226. }
  1227. void process_timer_rearm(base_timer_watcher *btw, rearm rearm_type) noexcept
  1228. {
  1229. // Called with lock held
  1230. if (rearm_type == rearm::REARM) {
  1231. loop_mech.enable_timer_nolock(btw->timer_handle, true, btw->clock);
  1232. }
  1233. else if (rearm_type == rearm::REMOVE) {
  1234. loop_mech.remove_timer_nolock(btw->timer_handle, btw->clock);
  1235. }
  1236. else if (rearm_type == rearm::DISARM) {
  1237. loop_mech.enable_timer_nolock(btw->timer_handle, false, btw->clock);
  1238. }
  1239. }
  1240. // Process queued events; returns true if any events were processed.
  1241. // limit - maximum number of events to process before returning; -1 for
  1242. // no limit.
  1243. bool process_events(int limit) noexcept
  1244. {
  1245. loop_mech.lock.lock();
  1246. if (limit == 0) {
  1247. return false;
  1248. }
  1249. // limit processing to the number of events currently queued, to avoid prolonged processing
  1250. // of watchers which requeueu themselves immediately (including file watchers which are using
  1251. // emulation for watching regular files)
  1252. //
  1253. // If limit is -1 (no limit) we rely on this being always larger than/equal to the number of
  1254. // queued events when cast to size_t (which is unsigned).
  1255. limit = std::min(size_t(limit), loop_mech.num_queued_events());
  1256. base_watcher * pqueue = loop_mech.pull_queued_event();
  1257. bool active = false;
  1258. while (pqueue != nullptr) {
  1259. pqueue->active = true;
  1260. active = true;
  1261. base_bidi_fd_watcher *bbfw = nullptr;
  1262. // (Above variables are initialised only to silence compiler warnings).
  1263. if (pqueue->watchType == watch_type_t::SECONDARYFD) {
  1264. // construct a pointer to the main watcher, using integer arithmetic to avoid undefined
  1265. // pointer arithmetic:
  1266. uintptr_t rp = (uintptr_t)pqueue;
  1267. // Here we take the offset of a member from a non-standard-layout class, which is
  1268. // specified to have undefined result by the C++ language standard, but which
  1269. // in practice works fine:
  1270. _Pragma ("GCC diagnostic push")
  1271. _Pragma ("GCC diagnostic ignored \"-Winvalid-offsetof\"")
  1272. rp -= offsetof(base_bidi_fd_watcher, out_watcher);
  1273. _Pragma ("GCC diagnostic pop")
  1274. bbfw = (base_bidi_fd_watcher *)rp;
  1275. // issue a secondary dispatch:
  1276. bbfw->dispatch_second(this);
  1277. }
  1278. else {
  1279. pqueue->dispatch(this);
  1280. }
  1281. if (limit > 0) {
  1282. limit--;
  1283. if (limit == 0) break;
  1284. }
  1285. pqueue = loop_mech.pull_queued_event();
  1286. }
  1287. loop_mech.lock.unlock();
  1288. return active;
  1289. }
  1290. public:
  1291. using fd_watcher = dprivate::fd_watcher<my_event_loop_t>;
  1292. using bidi_fd_watcher = dprivate::bidi_fd_watcher<my_event_loop_t>;
  1293. using signal_watcher = dprivate::signal_watcher<my_event_loop_t>;
  1294. using child_proc_watcher = dprivate::child_proc_watcher<my_event_loop_t>;
  1295. using timer = dprivate::timer<my_event_loop_t>;
  1296. template <typename D> using fd_watcher_impl = dprivate::fd_watcher_impl<my_event_loop_t, D>;
  1297. template <typename D> using bidi_fd_watcher_impl = dprivate::bidi_fd_watcher_impl<my_event_loop_t, D>;
  1298. template <typename D> using signal_watcher_impl = dprivate::signal_watcher_impl<my_event_loop_t, D>;
  1299. template <typename D> using child_proc_watcher_impl = dprivate::child_proc_watcher_impl<my_event_loop_t, D>;
  1300. template <typename D> using timer_impl = dprivate::timer_impl<my_event_loop_t, D>;
  1301. // Poll the event loop and process any pending events (up to a limit). If no events are pending, wait
  1302. // for and process at least one event.
  1303. void run(int limit = -1) noexcept
  1304. {
  1305. // Poll the mechanism first, in case high-priority events are pending:
  1306. waitqueue_node<T_Mutex> qnode;
  1307. get_pollwait_lock(qnode);
  1308. loop_mech.pull_events(false);
  1309. release_lock(qnode);
  1310. while (! process_events(limit)) {
  1311. // Pull events from the AEN mechanism and insert them in our internal queue:
  1312. get_pollwait_lock(qnode);
  1313. loop_mech.pull_events(true);
  1314. release_lock(qnode);
  1315. }
  1316. }
  1317. // Poll the event loop and process any pending events (up to a limit).
  1318. void poll(int limit = -1) noexcept
  1319. {
  1320. waitqueue_node<T_Mutex> qnode;
  1321. if (poll_attn_lock(qnode)) {
  1322. loop_mech.pull_events(false);
  1323. release_lock(qnode);
  1324. }
  1325. process_events(limit);
  1326. }
  1327. // Get the current time corresponding to a specific clock.
  1328. // ts - the timespec variable to receive the time
  1329. // clock - specifies the clock
  1330. // force_update (default = false) - if true, the time returned will be updated from
  1331. // the system rather than being a previously cached result. It may be more
  1332. // accurate, but note that reading from a system clock may be relatively expensive.
  1333. void get_time(timespec &ts, clock_type clock, bool force_update = false) noexcept
  1334. {
  1335. loop_mech.get_time(ts, clock, force_update);
  1336. }
  1337. void get_time(time_val &tv, clock_type clock, bool force_update = false) noexcept
  1338. {
  1339. loop_mech.get_time(tv, clock, force_update);
  1340. }
  1341. event_loop() { }
  1342. event_loop(delayed_init d) noexcept : loop_mech(d) { }
  1343. event_loop(const event_loop &other) = delete;
  1344. // Perform delayed initialisation, if constructed with delayed_init
  1345. void init()
  1346. {
  1347. loop_mech.init();
  1348. }
  1349. };
  1350. typedef event_loop<null_mutex> event_loop_n;
  1351. typedef event_loop<std::mutex> event_loop_th;
  1352. namespace dprivate {
  1353. // Posix signal event watcher
  1354. template <typename EventLoop>
  1355. class signal_watcher : private dprivate::base_signal_watcher<typename EventLoop::loop_traits_t::sigdata_t>
  1356. {
  1357. template <typename, typename> friend class signal_watcher_impl;
  1358. using base_watcher = dprivate::base_watcher;
  1359. using T_Mutex = typename EventLoop::mutex_t;
  1360. public:
  1361. using event_loop_t = EventLoop;
  1362. using siginfo_p = typename signal_watcher::siginfo_p;
  1363. // Register this watcher to watch the specified signal.
  1364. // If an attempt is made to register with more than one event loop at
  1365. // a time, behaviour is undefined. The signal should be masked before
  1366. // call.
  1367. inline void add_watch(event_loop_t &eloop, int signo, int prio = DEFAULT_PRIORITY)
  1368. {
  1369. base_watcher::init();
  1370. this->priority = prio;
  1371. this->siginfo.set_signo(signo);
  1372. eloop.register_signal(this, signo);
  1373. }
  1374. inline void deregister(event_loop_t &eloop) noexcept
  1375. {
  1376. eloop.deregister(this, this->siginfo.get_signo());
  1377. }
  1378. template <typename T>
  1379. static signal_watcher<event_loop_t> *add_watch(event_loop_t &eloop, int signo, T watch_hndlr)
  1380. {
  1381. class lambda_sig_watcher : public signal_watcher_impl<event_loop_t, lambda_sig_watcher>
  1382. {
  1383. private:
  1384. T watch_hndlr;
  1385. public:
  1386. lambda_sig_watcher(T watch_handlr_a) : watch_hndlr(watch_handlr_a)
  1387. {
  1388. //
  1389. }
  1390. rearm received(event_loop_t &eloop, int signo, siginfo_p siginfo)
  1391. {
  1392. return watch_hndlr(eloop, signo, siginfo);
  1393. }
  1394. void watch_removed() noexcept override
  1395. {
  1396. delete this;
  1397. }
  1398. };
  1399. lambda_sig_watcher * lsw = new lambda_sig_watcher(watch_hndlr);
  1400. lsw->add_watch(eloop, signo);
  1401. return lsw;
  1402. }
  1403. // virtual rearm received(EventLoop &eloop, int signo, siginfo_p siginfo) = 0;
  1404. };
  1405. template <typename EventLoop, typename Derived>
  1406. class signal_watcher_impl : public signal_watcher<EventLoop>
  1407. {
  1408. void dispatch(void *loop_ptr) noexcept override
  1409. {
  1410. EventLoop &loop = *static_cast<EventLoop *>(loop_ptr);
  1411. loop_access::get_base_lock(loop).unlock();
  1412. auto rearm_type = static_cast<Derived *>(this)->received(loop, this->siginfo.get_signo(), this->siginfo);
  1413. loop_access::get_base_lock(loop).lock();
  1414. if (rearm_type != rearm::REMOVED) {
  1415. this->active = false;
  1416. if (this->deleteme) {
  1417. // We don't want a watch that is marked "deleteme" to re-arm itself.
  1418. rearm_type = rearm::REMOVE;
  1419. }
  1420. loop_access::process_signal_rearm(loop, this, rearm_type);
  1421. post_dispatch(loop, this, rearm_type);
  1422. }
  1423. }
  1424. };
  1425. // Posix file descriptor event watcher
  1426. template <typename EventLoop>
  1427. class fd_watcher : private dprivate::base_fd_watcher
  1428. {
  1429. template <typename, typename> friend class fd_watcher_impl;
  1430. using base_watcher = dprivate::base_watcher;
  1431. using mutex_t = typename EventLoop::mutex_t;
  1432. protected:
  1433. // Set the types of event to watch. Only supported if loop_traits_t_t::has_bidi_fd_watch
  1434. // is true; otherwise has unspecified behavior.
  1435. // Only safe to call from within the callback handler (fdEvent). Might not take
  1436. // effect until the current callback handler returns with REARM.
  1437. void set_watch_flags(int newFlags)
  1438. {
  1439. this->watch_flags = newFlags;
  1440. }
  1441. public:
  1442. using event_loop_t = EventLoop;
  1443. // Register a file descriptor watcher with an event loop. Flags
  1444. // can be any combination of dasynq::IN_EVENTS / dasynq::OUT_EVENTS.
  1445. // Exactly one of IN_EVENTS/OUT_EVENTS must be specified if the event
  1446. // loop does not support bi-directional fd watchers (i.e. if
  1447. // ! loop_traits_t::has_bidi_fd_watch).
  1448. //
  1449. // Mechanisms supporting dual watchers allow for two watchers for a
  1450. // single file descriptor (one watching read status and the other
  1451. // write status). Others mechanisms support only a single watcher
  1452. // per file descriptor. Adding a watcher beyond what is supported
  1453. // causes undefined behavior.
  1454. //
  1455. // Can fail with std::bad_alloc or std::system_error.
  1456. void add_watch(event_loop_t &eloop, int fd, int flags, bool enabled = true, int prio = DEFAULT_PRIORITY)
  1457. {
  1458. base_watcher::init();
  1459. this->priority = prio;
  1460. this->watch_fd = fd;
  1461. this->watch_flags = flags;
  1462. eloop.register_fd(this, fd, flags, enabled, true);
  1463. }
  1464. void add_watch_noemu(event_loop_t &eloop, int fd, int flags, bool enabled = true, int prio = DEFAULT_PRIORITY)
  1465. {
  1466. base_watcher::init();
  1467. this->priority = prio;
  1468. this->watch_fd = fd;
  1469. this->watch_flags = flags;
  1470. eloop.register_fd(this, fd, flags, enabled, false);
  1471. }
  1472. int get_watched_fd()
  1473. {
  1474. return this->watch_fd;
  1475. }
  1476. // Deregister a file descriptor watcher.
  1477. //
  1478. // If other threads may be polling the event loop, it is not safe to assume
  1479. // the watcher is unregistered until the watch_removed() callback is issued
  1480. // (which will not occur until the event handler returns, if it is active).
  1481. // In a single threaded environment, it is safe to delete the watcher after
  1482. // calling this method as long as the handler (if it is active) accesses no
  1483. // internal state and returns rearm::REMOVED.
  1484. void deregister(event_loop_t &eloop) noexcept
  1485. {
  1486. eloop.deregister(this, this->watch_fd);
  1487. }
  1488. void set_enabled(event_loop_t &eloop, bool enable) noexcept
  1489. {
  1490. std::lock_guard<mutex_t> guard(eloop.get_base_lock());
  1491. if (this->emulatefd) {
  1492. if (enable && ! this->emulate_enabled) {
  1493. loop_access::requeue_watcher(eloop, this);
  1494. }
  1495. this->emulate_enabled = enable;
  1496. }
  1497. else {
  1498. eloop.set_fd_enabled_nolock(this, this->watch_fd, this->watch_flags, enable);
  1499. }
  1500. if (! enable) {
  1501. eloop.dequeue_watcher(this);
  1502. }
  1503. }
  1504. // Add an Fd watch via a lambda. The watch is allocated dynamically and destroys
  1505. // itself when removed from the event loop.
  1506. template <typename T>
  1507. static fd_watcher<EventLoop> *add_watch(event_loop_t &eloop, int fd, int flags, T watchHndlr)
  1508. {
  1509. class lambda_fd_watcher : public fd_watcher_impl<event_loop_t, lambda_fd_watcher>
  1510. {
  1511. private:
  1512. T watchHndlr;
  1513. public:
  1514. lambda_fd_watcher(T watchHandlr_a) : watchHndlr(watchHandlr_a)
  1515. {
  1516. //
  1517. }
  1518. rearm fd_event(event_loop_t &eloop, int fd, int flags)
  1519. {
  1520. return watchHndlr(eloop, fd, flags);
  1521. }
  1522. void watch_removed() noexcept override
  1523. {
  1524. delete this;
  1525. }
  1526. };
  1527. lambda_fd_watcher * lfd = new lambda_fd_watcher(watchHndlr);
  1528. lfd->add_watch(eloop, fd, flags);
  1529. return lfd;
  1530. }
  1531. // virtual rearm fd_event(EventLoop &eloop, int fd, int flags) = 0;
  1532. };
  1533. template <typename EventLoop, typename Derived>
  1534. class fd_watcher_impl : public fd_watcher<EventLoop>
  1535. {
  1536. void dispatch(void *loop_ptr) noexcept override
  1537. {
  1538. EventLoop &loop = *static_cast<EventLoop *>(loop_ptr);
  1539. // In case emulating, clear enabled here; REARM or explicit set_enabled will re-enable.
  1540. this->emulate_enabled = false;
  1541. loop_access::get_base_lock(loop).unlock();
  1542. auto rearm_type = static_cast<Derived *>(this)->fd_event(loop, this->watch_fd, this->event_flags);
  1543. loop_access::get_base_lock(loop).lock();
  1544. if (rearm_type != rearm::REMOVED) {
  1545. this->event_flags = 0;
  1546. this->active = false;
  1547. if (this->deleteme) {
  1548. // We don't want a watch that is marked "deleteme" to re-arm itself.
  1549. rearm_type = rearm::REMOVE;
  1550. }
  1551. rearm_type = loop_access::process_fd_rearm(loop, this, rearm_type);
  1552. post_dispatch(loop, this, rearm_type);
  1553. }
  1554. }
  1555. };
  1556. // A Bi-directional file descriptor watcher with independent read- and write- channels.
  1557. // This watcher type has two event notification methods which can both potentially be
  1558. // active at the same time.
  1559. template <typename EventLoop>
  1560. class bidi_fd_watcher : private dprivate::base_bidi_fd_watcher
  1561. {
  1562. template <typename, typename> friend class bidi_fd_watcher_impl;
  1563. using base_watcher = dprivate::base_watcher;
  1564. using mutex_t = typename EventLoop::mutex_t;
  1565. void set_watch_enabled(EventLoop &eloop, bool in, bool b)
  1566. {
  1567. int events = in ? IN_EVENTS : OUT_EVENTS;
  1568. auto orig_flags = this->watch_flags;
  1569. if (b) {
  1570. this->watch_flags |= events;
  1571. }
  1572. else {
  1573. this->watch_flags &= ~events;
  1574. }
  1575. dprivate::base_watcher * watcher = in ? this : &this->out_watcher;
  1576. if (! watcher->emulatefd) {
  1577. if (EventLoop::loop_traits_t::has_separate_rw_fd_watches) {
  1578. eloop.set_fd_enabled_nolock(this, this->watch_fd, events | ONE_SHOT, b);
  1579. }
  1580. else {
  1581. eloop.set_fd_enabled_nolock(this, this->watch_fd,
  1582. (this->watch_flags & IO_EVENTS) | ONE_SHOT,
  1583. (this->watch_flags & IO_EVENTS) != 0);
  1584. }
  1585. }
  1586. else {
  1587. // emulation: if enabling a previously disabled watcher, must queue now:
  1588. if (b && (orig_flags != this->watch_flags)) {
  1589. this->watch_flags = orig_flags;
  1590. loop_access::requeue_watcher(eloop, watcher);
  1591. }
  1592. }
  1593. if (! b) {
  1594. eloop.dequeue_watcher(watcher);
  1595. }
  1596. }
  1597. public:
  1598. using event_loop_t = EventLoop;
  1599. void set_in_watch_enabled(event_loop_t &eloop, bool b) noexcept
  1600. {
  1601. eloop.get_base_lock().lock();
  1602. set_watch_enabled(eloop, true, b);
  1603. eloop.get_base_lock().unlock();
  1604. }
  1605. void set_out_watch_enabled(event_loop_t &eloop, bool b) noexcept
  1606. {
  1607. eloop.get_base_lock().lock();
  1608. set_watch_enabled(eloop, false, b);
  1609. eloop.get_base_lock().unlock();
  1610. }
  1611. // Set the watch flags, which enables/disables both the in-watch and the out-watch accordingly.
  1612. //
  1613. // Concurrency: this method can only be called if
  1614. // - it does not enable a watcher that might currently be active
  1615. /// - unless the event loop will not be polled while the watcher is active.
  1616. // (i.e. it is ok to call setWatchFlags from within the readReady/writeReady handlers if no other
  1617. // thread will poll the event loop; it is always ok to *dis*able a watcher that might be active,
  1618. // though the re-arm action returned by the callback may undo the effect).
  1619. void set_watches(event_loop_t &eloop, int new_flags) noexcept
  1620. {
  1621. std::lock_guard<mutex_t> guard(eloop.get_base_lock());
  1622. bool use_emulation = this->emulatefd || this->out_watcher.emulatefd;
  1623. if (use_emulation || EventLoop::loop_traits_t::has_separate_rw_fd_watches) {
  1624. set_watch_enabled(eloop, true, (new_flags & IN_EVENTS) != 0);
  1625. set_watch_enabled(eloop, false, (new_flags & OUT_EVENTS) != 0);
  1626. }
  1627. else {
  1628. this->watch_flags = (this->watch_flags & ~IO_EVENTS) | new_flags;
  1629. eloop.set_fd_enabled_nolock((dprivate::base_watcher *) this, this->watch_fd, this->watch_flags & IO_EVENTS, true);
  1630. }
  1631. }
  1632. // Register a bi-direction file descriptor watcher with an event loop. Flags
  1633. // can be any combination of dasynq::IN_EVENTS / dasynq::OUT_EVENTS.
  1634. //
  1635. // Can fail with std::bad_alloc or std::system_error.
  1636. void add_watch(event_loop_t &eloop, int fd, int flags, int inprio = DEFAULT_PRIORITY, int outprio = DEFAULT_PRIORITY)
  1637. {
  1638. base_watcher::init();
  1639. this->out_watcher.base_watcher::init();
  1640. this->watch_fd = fd;
  1641. this->watch_flags = flags | dprivate::multi_watch;
  1642. this->read_removed = false;
  1643. this->write_removed = false;
  1644. this->priority = inprio;
  1645. this->set_priority(this->out_watcher, outprio);
  1646. eloop.register_fd(this, fd, flags, true);
  1647. }
  1648. void add_watch_noemu(event_loop_t &eloop, int fd, int flags, int inprio = DEFAULT_PRIORITY, int outprio = DEFAULT_PRIORITY)
  1649. {
  1650. base_watcher::init();
  1651. this->out_watcher.base_watcher::init();
  1652. this->watch_fd = fd;
  1653. this->watch_flags = flags | dprivate::multi_watch;
  1654. this->read_removed = false;
  1655. this->write_removed = false;
  1656. this->priority = inprio;
  1657. this->set_priority(this->out_watcher, outprio);
  1658. eloop.register_fd(this, fd, flags, false);
  1659. }
  1660. int get_watched_fd()
  1661. {
  1662. return this->watch_fd;
  1663. }
  1664. // Deregister a bi-direction file descriptor watcher.
  1665. //
  1666. // If other threads may be polling the event loop, it is not safe to assume
  1667. // the watcher is unregistered until the watch_removed() callback is issued
  1668. // (which will not occur until the event handler returns, if it is active).
  1669. // In a single threaded environment, it is safe to delete the watcher after
  1670. // calling this method as long as the handler (if it is active) accesses no
  1671. // internal state and returns rearm::REMOVED.
  1672. void deregister(event_loop_t &eloop) noexcept
  1673. {
  1674. eloop.deregister(this, this->watch_fd);
  1675. }
  1676. template <typename T>
  1677. static bidi_fd_watcher<event_loop_t> *add_watch(event_loop_t &eloop, int fd, int flags, T watch_hndlr)
  1678. {
  1679. class lambda_bidi_watcher : public bidi_fd_watcher_impl<event_loop_t, lambda_bidi_watcher>
  1680. {
  1681. private:
  1682. T watch_hndlr;
  1683. public:
  1684. lambda_bidi_watcher(T watch_handlr_a) : watch_hndlr(watch_handlr_a)
  1685. {
  1686. //
  1687. }
  1688. rearm read_ready(event_loop_t &eloop, int fd)
  1689. {
  1690. return watch_hndlr(eloop, fd, IN_EVENTS);
  1691. }
  1692. rearm write_ready(event_loop_t &eloop, int fd)
  1693. {
  1694. return watch_hndlr(eloop, fd, OUT_EVENTS);
  1695. }
  1696. void watch_removed() noexcept override
  1697. {
  1698. delete this;
  1699. }
  1700. };
  1701. lambda_bidi_watcher * lfd = new lambda_bidi_watcher(watch_hndlr);
  1702. lfd->add_watch(eloop, fd, flags);
  1703. return lfd;
  1704. }
  1705. // virtual rearm read_ready(EventLoop &eloop, int fd) noexcept = 0;
  1706. // virtual rearm write_ready(EventLoop &eloop, int fd) noexcept = 0;
  1707. };
  1708. template <typename EventLoop, typename Derived>
  1709. class bidi_fd_watcher_impl : public bidi_fd_watcher<EventLoop>
  1710. {
  1711. void dispatch(void *loop_ptr) noexcept override
  1712. {
  1713. EventLoop &loop = *static_cast<EventLoop *>(loop_ptr);
  1714. this->emulate_enabled = false;
  1715. loop_access::get_base_lock(loop).unlock();
  1716. auto rearm_type = static_cast<Derived *>(this)->read_ready(loop, this->watch_fd);
  1717. loop_access::get_base_lock(loop).lock();
  1718. if (rearm_type != rearm::REMOVED) {
  1719. this->event_flags &= ~IN_EVENTS;
  1720. this->active = false;
  1721. if (this->deleteme) {
  1722. // We don't want a watch that is marked "deleteme" to re-arm itself.
  1723. rearm_type = rearm::REMOVE;
  1724. }
  1725. rearm_type = loop_access::process_primary_rearm(loop, this, rearm_type);
  1726. auto &outwatcher = bidi_fd_watcher<EventLoop>::out_watcher;
  1727. post_dispatch(loop, this, &outwatcher, rearm_type);
  1728. }
  1729. }
  1730. void dispatch_second(void *loop_ptr) noexcept override
  1731. {
  1732. auto &outwatcher = bidi_fd_watcher<EventLoop>::out_watcher;
  1733. EventLoop &loop = *static_cast<EventLoop *>(loop_ptr);
  1734. loop_access::get_base_lock(loop).unlock();
  1735. auto rearm_type = static_cast<Derived *>(this)->write_ready(loop, this->watch_fd);
  1736. loop_access::get_base_lock(loop).lock();
  1737. if (rearm_type != rearm::REMOVED) {
  1738. this->event_flags &= ~OUT_EVENTS;
  1739. outwatcher.active = false;
  1740. if (outwatcher.deleteme) {
  1741. // We don't want a watch that is marked "deleteme" to re-arm itself.
  1742. rearm_type = rearm::REMOVE;
  1743. }
  1744. rearm_type = loop_access::process_secondary_rearm(loop, this, &outwatcher, rearm_type);
  1745. if (rearm_type == rearm::REQUEUE) {
  1746. post_dispatch(loop, &outwatcher, rearm_type);
  1747. }
  1748. else {
  1749. post_dispatch(loop, this, &outwatcher, rearm_type);
  1750. }
  1751. }
  1752. }
  1753. };
  1754. // Child process event watcher
  1755. template <typename EventLoop>
  1756. class child_proc_watcher : private dprivate::base_child_watcher
  1757. {
  1758. template <typename, typename> friend class child_proc_watcher_impl;
  1759. using base_watcher = dprivate::base_watcher;
  1760. using mutex_t = typename EventLoop::mutex_t;
  1761. public:
  1762. using event_loop_t = EventLoop;
  1763. // send a signal to this process, if it is still running, in a race-free manner.
  1764. // return is as for POSIX kill(); return is -1 with errno=ESRCH if process has
  1765. // already terminated.
  1766. int send_signal(event_loop_t &loop, int signo) noexcept
  1767. {
  1768. auto reaper_mutex = loop.get_reaper_mutex();
  1769. std::lock_guard<decltype(reaper_mutex)> guard(reaper_mutex);
  1770. if (this->child_termd) {
  1771. errno = ESRCH;
  1772. return -1;
  1773. }
  1774. return kill(this->watch_pid, signo);
  1775. }
  1776. // Reserve resources for a child watcher with the given event loop.
  1777. // Reservation can fail with std::bad_alloc. Some backends do not support
  1778. // reservation (it will always fail) - check loop_traits_t::supports_childwatch_reservation.
  1779. void reserve_watch(event_loop_t &eloop)
  1780. {
  1781. eloop.reserve_child_watch(this);
  1782. }
  1783. void unreserve(event_loop_t &eloop)
  1784. {
  1785. eloop.unreserve(this);
  1786. }
  1787. // Register a watcher for the given child process with an event loop.
  1788. // Registration can fail with std::bad_alloc.
  1789. // Note that in multi-threaded programs, use of this function may be prone to a
  1790. // race condition such that the child terminates before the watcher is registered.
  1791. void add_watch(event_loop_t &eloop, pid_t child, int prio = DEFAULT_PRIORITY)
  1792. {
  1793. base_watcher::init();
  1794. this->watch_pid = child;
  1795. this->priority = prio;
  1796. eloop.register_child(this, child);
  1797. }
  1798. // Register a watcher for the given child process with an event loop,
  1799. // after having reserved resources previously (using reserveWith).
  1800. // Registration cannot fail.
  1801. // Note that in multi-threaded programs, use of this function may be prone to a
  1802. // race condition such that the child terminates before the watcher is registered;
  1803. // use the "fork" member function to avoid this.
  1804. void add_reserved(event_loop_t &eloop, pid_t child, int prio = DEFAULT_PRIORITY) noexcept
  1805. {
  1806. base_watcher::init();
  1807. this->watch_pid = child;
  1808. this->priority = prio;
  1809. eloop.register_reserved_child(this, child);
  1810. }
  1811. void deregister(event_loop_t &eloop, pid_t child) noexcept
  1812. {
  1813. eloop.deregister(this, child);
  1814. }
  1815. // Stop watching the currently watched child, but retain watch reservation.
  1816. void stop_watch(event_loop_t &eloop) noexcept
  1817. {
  1818. eloop.stop_watch(this);
  1819. }
  1820. // Fork and watch the child with this watcher on the given event loop.
  1821. // If resource limitations prevent the child process from being watched, it is
  1822. // terminated immediately (or if the implementation allows, never started),
  1823. // and a suitable std::system_error or std::bad_alloc exception is thrown.
  1824. // Returns:
  1825. // - the child pid in the parent
  1826. // - 0 in the child
  1827. pid_t fork(event_loop_t &eloop, bool from_reserved = false, int prio = DEFAULT_PRIORITY)
  1828. {
  1829. base_watcher::init();
  1830. this->priority = prio;
  1831. if (EventLoop::loop_traits_t::supports_childwatch_reservation) {
  1832. // Reserve a watch, fork, then claim reservation
  1833. if (! from_reserved) {
  1834. reserve_watch(eloop);
  1835. }
  1836. auto &lock = eloop.get_base_lock();
  1837. lock.lock();
  1838. pid_t child = ::fork();
  1839. if (child == -1) {
  1840. // Unreserve watch.
  1841. lock.unlock();
  1842. unreserve(eloop);
  1843. throw std::system_error(errno, std::system_category());
  1844. }
  1845. if (child == 0) {
  1846. // I am the child
  1847. lock.unlock(); // may not really be necessary
  1848. return 0;
  1849. }
  1850. // Register this watcher.
  1851. this->watch_pid = child;
  1852. eloop.register_reserved_child_nolock(this, child);
  1853. lock.unlock();
  1854. return child;
  1855. }
  1856. else {
  1857. int pipefds[2];
  1858. if (pipe2(pipefds, O_CLOEXEC) == -1) {
  1859. throw std::system_error(errno, std::system_category());
  1860. }
  1861. std::lock_guard<mutex_t> guard(eloop.get_base_lock());
  1862. pid_t child = ::fork();
  1863. if (child == -1) {
  1864. throw std::system_error(errno, std::system_category());
  1865. }
  1866. if (child == 0) {
  1867. // I am the child
  1868. close(pipefds[1]);
  1869. // Wait for message from parent before continuing:
  1870. int rr;
  1871. int r = read(pipefds[0], &rr, sizeof(rr));
  1872. while (r == -1 && errno == EINTR) {
  1873. r = read(pipefds[0], &rr, sizeof(rr));
  1874. }
  1875. if (r <= 0) _exit(0);
  1876. close(pipefds[0]);
  1877. return 0;
  1878. }
  1879. close(pipefds[0]); // close read end
  1880. // Register this watcher.
  1881. try {
  1882. this->watch_pid = child;
  1883. eloop.register_child(this, child);
  1884. // Continue in child (it doesn't matter what is written):
  1885. write(pipefds[1], &pipefds, sizeof(int));
  1886. close(pipefds[1]);
  1887. return child;
  1888. }
  1889. catch (...) {
  1890. close(pipefds[1]);
  1891. throw;
  1892. }
  1893. }
  1894. }
  1895. // virtual rearm child_status(EventLoop &eloop, pid_t child, int status) = 0;
  1896. };
  1897. template <typename EventLoop, typename Derived>
  1898. class child_proc_watcher_impl : public child_proc_watcher<EventLoop>
  1899. {
  1900. void dispatch(void *loop_ptr) noexcept override
  1901. {
  1902. EventLoop &loop = *static_cast<EventLoop *>(loop_ptr);
  1903. loop_access::get_base_lock(loop).unlock();
  1904. auto rearm_type = static_cast<Derived *>(this)->status_change(loop, this->watch_pid, this->child_status);
  1905. loop_access::get_base_lock(loop).lock();
  1906. if (rearm_type != rearm::REMOVED) {
  1907. this->active = false;
  1908. if (this->deleteme) {
  1909. // We don't want a watch that is marked "deleteme" to re-arm itself.
  1910. rearm_type = rearm::REMOVE;
  1911. }
  1912. loop_access::process_child_watch_rearm(loop, this, rearm_type);
  1913. // rearm_type = loop.process??;
  1914. post_dispatch(loop, this, rearm_type);
  1915. }
  1916. }
  1917. };
  1918. template <typename EventLoop>
  1919. class timer : private base_timer_watcher
  1920. {
  1921. template <typename, typename> friend class timer_impl;
  1922. using base_t = base_timer_watcher;
  1923. using mutex_t = typename EventLoop::mutex_t;
  1924. public:
  1925. using event_loop_t = EventLoop;
  1926. void add_timer(event_loop_t &eloop, clock_type clock = clock_type::MONOTONIC, int prio = DEFAULT_PRIORITY)
  1927. {
  1928. base_watcher::init();
  1929. this->priority = prio;
  1930. this->clock = clock;
  1931. this->intervals = 0;
  1932. eloop.register_timer(this, clock);
  1933. }
  1934. void arm_timer(event_loop_t &eloop, const timespec &timeout) noexcept
  1935. {
  1936. eloop.set_timer(this, timeout, base_t::clock);
  1937. }
  1938. void arm_timer(event_loop_t &eloop, const timespec &timeout, const timespec &interval) noexcept
  1939. {
  1940. eloop.set_timer(this, timeout, interval, base_t::clock);
  1941. }
  1942. // Arm timer, relative to now:
  1943. void arm_timer_rel(event_loop_t &eloop, const timespec &timeout) noexcept
  1944. {
  1945. eloop.set_timer_rel(this, timeout, base_t::clock);
  1946. }
  1947. void arm_timer_rel(event_loop_t &eloop, const timespec &timeout,
  1948. const timespec &interval) noexcept
  1949. {
  1950. eloop.set_timer_rel(this, timeout, interval, base_t::clock);
  1951. }
  1952. void stop_timer(event_loop_t &eloop) noexcept
  1953. {
  1954. eloop.stop_timer(this, base_t::clock);
  1955. }
  1956. void set_enabled(event_loop_t &eloop, clock_type clock, bool enabled) noexcept
  1957. {
  1958. std::lock_guard<mutex_t> guard(eloop.get_base_lock());
  1959. eloop.set_timer_enabled_nolock(this, clock, enabled);
  1960. if (! enabled) {
  1961. eloop.dequeue_watcher(this);
  1962. }
  1963. }
  1964. void deregister(event_loop_t &eloop) noexcept
  1965. {
  1966. eloop.deregister(this, this->clock);
  1967. }
  1968. template <typename T>
  1969. static timer<EventLoop> *add_timer(EventLoop &eloop, clock_type clock, bool relative,
  1970. const timespec &timeout, const timespec &interval, T watch_hndlr)
  1971. {
  1972. class lambda_timer : public timer_impl<event_loop_t, lambda_timer>
  1973. {
  1974. private:
  1975. T watch_hndlr;
  1976. public:
  1977. lambda_timer(T watch_handlr_a) : watch_hndlr(watch_handlr_a)
  1978. {
  1979. //
  1980. }
  1981. rearm timer_expiry(event_loop_t &eloop, int intervals)
  1982. {
  1983. return watch_hndlr(eloop, intervals);
  1984. }
  1985. void watch_removed() noexcept override
  1986. {
  1987. delete this;
  1988. }
  1989. };
  1990. lambda_timer * lt = new lambda_timer(watch_hndlr);
  1991. lt->add_timer(eloop, clock);
  1992. if (relative) {
  1993. lt->arm_timer_rel(eloop, timeout, interval);
  1994. }
  1995. else {
  1996. lt->arm_timer(eloop, timeout, interval);
  1997. }
  1998. return lt;
  1999. }
  2000. // Timer expired, and the given number of intervals have elapsed before
  2001. // expiry event was queued. Normally intervals == 1 to indicate no
  2002. // overrun.
  2003. // virtual rearm timer_expiry(event_loop_t &eloop, int intervals) = 0;
  2004. };
  2005. template <typename EventLoop, typename Derived>
  2006. class timer_impl : public timer<EventLoop>
  2007. {
  2008. void dispatch(void *loop_ptr) noexcept override
  2009. {
  2010. EventLoop &loop = *static_cast<EventLoop *>(loop_ptr);
  2011. loop_access::get_base_lock(loop).unlock();
  2012. auto intervals_report = this->intervals;
  2013. this->intervals = 0;
  2014. auto rearm_type = static_cast<Derived *>(this)->timer_expiry(loop, intervals_report);
  2015. loop_access::get_base_lock(loop).lock();
  2016. if (rearm_type != rearm::REMOVED) {
  2017. this->active = false;
  2018. if (this->deleteme) {
  2019. // We don't want a watch that is marked "deleteme" to re-arm itself.
  2020. rearm_type = rearm::REMOVE;
  2021. }
  2022. loop_access::process_timer_rearm(loop, this, rearm_type);
  2023. post_dispatch(loop, this, rearm_type);
  2024. }
  2025. }
  2026. };
  2027. } // namespace dprivate
  2028. } // namespace dasynq
  2029. #endif /* DASYNQ_H_ */