+/**
+ * Prevent the compiler from optimizing access to the variable \a x, enforcing
+ * a refetch from memory. This also forbid from reordering successing instances
+ * of ACCESS_SAFE().
+ *
+ * TODO: move this to cfg/compiler.h
+ */
+#define ACCESS_SAFE(x) (*(volatile typeof(x) *)&(x))
+
+#if defined(CONFIG_KERN_SIGNALS) && CONFIG_KERN_SIGNALS
+/** Initialize the generic sleepable event \a e */
+#define event_initGeneric(e) \
+ event_initSignal(e, proc_current(), SIG_SYSTEM5)
+#else
+#define event_initGeneric(e) \
+ ((e)->action = event_hook_generic, (e)->Ev.Gen.completed = false)
+#endif
+
+/**
+ * Create a generic sleepable event.
+ *
+ * \return the properly initialized generic event structure.
+ */
+INLINE Event event_createGeneric(void)
+{
+ Event e;
+ event_initGeneric(&e);
+ return e;
+}
+
+/**
+ * Wait the completion of event \a e.
+ */
+INLINE void event_wait(Event *e)
+{
+#if defined(CONFIG_KERN_SIGNALS) && CONFIG_KERN_SIGNALS
+ e->Ev.Sig.sig_proc = proc_current();
+ sig_wait(e->Ev.Sig.sig_bit);
+#else
+ while (ACCESS_SAFE(e->Ev.Gen.completed) == false)
+ cpu_relax();
+ e->Ev.Gen.completed = false;
+ MEMORY_BARRIER;
+#endif
+}
+
+#if CONFIG_TIMER_EVENTS
+#include <drv/timer.h> /* timer_clock() */
+
+/* TODO: move these macros to drv/timer.h */
+#define TIMER_AFTER(x, y) ((long)(y) - (long)(x) < 0)
+#define TIMER_BEFORE(x, y) TIMER_AFTER(y, x)
+
+/**
+ * Wait the completion of event \a e or \a timeout elapses.
+ */
+INLINE bool event_waitTimeout(Event *e, ticks_t timeout)
+{
+#if defined(CONFIG_KERN_SIGNALS) && CONFIG_KERN_SIGNALS
+ e->Ev.Sig.sig_proc = proc_current();
+ return (sig_waitTimeout(e->Ev.Sig.sig_bit, timeout) & SIG_TIMEOUT) ?
+ false : true;
+#else
+ ticks_t end = timer_clock() + timeout;
+ bool ret;
+
+ while ((ACCESS_SAFE(e->Ev.Gen.completed) == false) ||
+ TIMER_AFTER(timer_clock(), end))
+ cpu_relax();
+ ret = e->Ev.Gen.completed;
+ e->Ev.Gen.completed = false;
+ MEMORY_BARRIER;
+
+ return ret;
+#endif
+}
+#endif /* CONFIG_TIMER_EVENTS */
+