event: introduce event_select()
[bertos.git] / bertos / mware / event.h
1 /**
2  * \file
3  * <!--
4  * This file is part of BeRTOS.
5  *
6  * Bertos is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
19  *
20  * As a special exception, you may use this file as part of a free software
21  * library without restriction.  Specifically, if other files instantiate
22  * templates or use macros or inline functions from this file, or you compile
23  * this file and link it with other files to produce an executable, this
24  * file does not by itself cause the resulting executable to be covered by
25  * the GNU General Public License.  This exception does not however
26  * invalidate any other reasons why the executable file might be covered by
27  * the GNU General Public License.
28  *
29  * Copyright 2003, 2004, 2005 Develer S.r.l. (http://www.develer.com/)
30  * Copyright 1999, 2001, 2003 Bernie Innocenti <bernie@codewiz.org>
31  * -->
32  *
33  * \defgroup event_handling Event handling module
34  * \ingroup core
35  * \{
36  *
37  * \brief Events handling
38  *
39  * This module implements a common system for executing
40  * a user defined action calling a hook function.
41  *
42  *
43  *  Device drivers often need to wait the completion of some event, usually to
44  *  allow the hardware to accomplish some asynchronous task.
45  *
46  *  A common approach is to place a busy wait with a cpu_relax() loop that invokes
47  *  the architecture-specific instructions to say that we're not doing much with
48  *  the processor.
49  *
50  *  Although technically correct, the busy loop degrades the overall system
51  *  performance in presence of multiple processes and power consumption.
52  *
53  *  With the kernel the natural way to implement such wait/complete mechanism is to
54  *  use signals via sig_wait() and sig_post()/sig_send().
55  *
56  *  However, signals in BeRTOS are only available in presence of the kernel (that
57  *  is just a compile-time option). This means that each device driver must provide
58  *  two different interfaces to implement the wait/complete semantic: one with the
59  *  kernel and another without the kernel.
60  *
61  *  The purpose of the completion events is to provide a generic interface to
62  *  implement a synchronization mechanism to block the execution of code until a
63  *  specific event happens.
64  *
65  *  This interface does not depend on the presence of the kernel and it
66  *  automatically uses the appropriate event backend to provide the same
67  *  behaviour with or without the kernel.
68  *
69  *  Example usage (wait for a generic device driver initialization):
70  *  \code
71  *  static Event e;
72  *
73  *  static void irq_handler(void)
74  *  {
75  *      // Completion event has happened, resume the execution of init()
76  *      event_do(&e);
77  *  }
78  *
79  *  static void init(void)
80  *  {
81  *      // Declare the generic completion event
82  *      event_initGeneric(&e);
83  *      // Submit the hardware initialization request
84  *      async_hw_init();
85  *      // Wait for the completion of the event
86  *      event_wait(&e);
87  *  }
88  *  \endcode
89  *
90  * Example usage: wait multiple generic events via event_select()
91  * \code
92  * Event ev1;
93  * Event ev2;
94  *
95  * void event_notifier(void)
96  * {
97  *      Event *evs[] = { &ev1, &ev2 };
98  *
99  *      event_initGeneric(&ev1);
100  *      event_initGeneric(&ev2);
101  *
102  *      while (1)
103  *      {
104  *              int id = event_select(evs, countof(evs),
105  *                                      ms_to_ticks(100));
106  *              if (id < 0)
107  *              {
108  *                      kprintf("no IRQ\n");
109  *                      continue;
110  *              }
111  *              kprintf("IRQ %d happened\n", id);
112  *      }
113  * }
114  *
115  * void irq1_handler(void)
116  * {
117  *      // do something
118  *      ...
119  *
120  *      // notify the completion of event 1
121  *      event_do(&ev1);
122  * }
123  *
124  * void irq2_handler(void)
125  * {
126  *      // do something
127  *      ...
128  *
129  *      // notify the completion of event 2
130  *      event_do(&ev2);
131  * }
132  * \endcode
133  *
134  * \author Bernie Innocenti <bernie@codewiz.org>
135  */
136
137 #ifndef KERN_EVENT_H
138 #define KERN_EVENT_H
139
140 #include <cfg/compiler.h>
141 #include "cfg/cfg_proc.h"
142 #include "cfg/cfg_signal.h"
143 #include "cfg/cfg_timer.h"
144
145 #include <cpu/power.h> /* cpu_relax() */
146
147 #if CONFIG_KERN
148         #if defined(CONFIG_KERN_SIGNALS) && CONFIG_KERN_SIGNALS
149                 #include <kern/signal.h>
150         #endif
151
152         /* Forward decl */
153         struct Process;
154 #endif
155
156 /// User defined callback type
157 typedef void (*Hook)(void *);
158
159 typedef struct Event
160 {
161         void (*action)(struct Event *);
162         union
163         {
164 #if defined(CONFIG_KERN_SIGNALS) && CONFIG_KERN_SIGNALS
165                 struct
166                 {
167                         struct Process *sig_proc;  /* Process to be signalled */
168                         sigbit_t        sig_bit;   /* Signal to send */
169                 } Sig;
170
171                 struct
172                 {
173                         struct Process *sig_proc;  /* Process to be signalled */
174                         Signal          sig;       /* Signal structure */
175                 } SigGen;
176 #endif
177                 struct
178                 {
179                         Hook  func;         /* Pointer to softint hook */
180                         void *user_data;    /* Data to be passed back to user hook */
181                 } Int;
182
183                 struct
184                 {
185                         bool completed;             /* Generic event completion */
186                 } Gen;
187         } Ev;
188 } Event;
189
190 void event_hook_ignore(Event *event);
191 void event_hook_signal(Event *event);
192 void event_hook_softint(Event *event);
193 void event_hook_generic(Event *event);
194 void event_hook_generic_signal(Event *event);
195
196 /** Initialize the event \a e as a no-op */
197 #define event_initNone(e) \
198         ((e)->action = event_hook_ignore)
199
200 /** Same as event_initNone(), but returns the initialized event */
201 INLINE Event event_createNone(void);
202 INLINE Event event_createNone(void)
203 {
204         Event e;
205         e.action = event_hook_ignore;
206         return e;
207 }
208
209 /** Initialize the event \a e with a software interrupt (call function \a f, with parameter \a u) */
210 #define event_initSoftint(e,f,u) \
211         ((e)->action = event_hook_softint,(e)->Ev.Int.func = (f), (e)->Ev.Int.user_data = (u))
212
213 /** Same as event_initSoftint(), but returns the initialized event */
214 INLINE Event event_createSoftint(Hook func, void *user_data)
215 {
216         Event e;
217         e.action = event_hook_softint;
218         e.Ev.Int.func = func;
219         e.Ev.Int.user_data = user_data;
220         return e;
221 }
222
223 #if defined(CONFIG_KERN_SIGNALS) && CONFIG_KERN_SIGNALS
224
225 /** Initialize the event \a e with a signal (send signal \a s to process \a p) */
226 #define event_initSignal(e,p,s) \
227         ((e)->action = event_hook_signal,(e)->Ev.Sig.sig_proc = (p), (e)->Ev.Sig.sig_bit = (s))
228
229 /** Same as event_initSignal(), but returns the initialized event */
230 INLINE Event event_createSignal(struct Process *proc, sigbit_t bit)
231 {
232         Event e;
233         e.action = event_hook_signal;
234         e.Ev.Sig.sig_proc = proc;
235         e.Ev.Sig.sig_bit = bit;
236         return e;
237 }
238
239 #endif
240
241 #if defined(CONFIG_KERN_SIGNALS) && CONFIG_KERN_SIGNALS
242 /** Initialize the generic sleepable event \a e */
243 #define event_initGeneric(e)                                    \
244         ((e)->action = event_hook_generic_signal,               \
245                 (e)->Ev.SigGen.sig_proc = proc_current(),       \
246                 (e)->Ev.SigGen.sig.wait = 0, (e)->Ev.SigGen.sig.recv = 0)
247 #else
248 #define event_initGeneric(e) \
249         ((e)->action = event_hook_generic, (e)->Ev.Gen.completed = false)
250 #endif
251
252 /**
253  * Signal used to implement generic events.
254  */
255 #define EVENT_GENERIC_SIGNAL    SIG_SYSTEM5
256
257 /**
258  * Create a generic sleepable event.
259  *
260  * \return the properly initialized generic event structure.
261  */
262 INLINE Event event_createGeneric(void)
263 {
264         Event e;
265         event_initGeneric(&e);
266         return e;
267 }
268
269 /**
270  * Wait the completion of event \a e.
271  *
272  * This function releases the CPU the application is configured to use
273  * the kernel, otherwise it's just a busy wait.
274  * \note It's forbidden to use this function inside irq handling functions.
275  */
276 INLINE void event_wait(Event *e)
277 {
278 #if defined(CONFIG_KERN_SIGNALS) && CONFIG_KERN_SIGNALS
279         e->Ev.Sig.sig_proc = proc_current();
280         sig_waitSignal(&e->Ev.SigGen.sig, EVENT_GENERIC_SIGNAL);
281 #else
282         while (ACCESS_SAFE(e->Ev.Gen.completed) == false)
283                 cpu_relax();
284         e->Ev.Gen.completed = false;
285         MEMORY_BARRIER;
286 #endif
287 }
288
289 /**
290  * Wait for multiple events
291  *
292  * On success return the offset in the \a evs vector of the Event that
293  * happened, -1 if the timeout expires.
294  *
295  * NOTE: timeout == 0 means no timeout.
296  */
297 #if defined(CONFIG_KERN_SIGNALS) && CONFIG_KERN_SIGNALS
298 INLINE int event_select(Event **evs, int n, ticks_t timeout)
299 {
300         sigmask_t mask = (1 << n) - 1;
301         int i;
302
303         ASSERT(n <= SIG_USER_MAX);
304         for (i = 0; i < n; i++)
305         {
306                 Event *e = evs[i];
307                 /* Map each event to a distinct signal bit */
308                 event_initSignal(e, proc_current(), 1 << i);
309         }
310         mask = timeout ? sig_waitTimeout(mask, timeout) : sig_wait(mask);
311         i = UINT8_LOG2(mask);
312
313         return i < n ? i : -1;
314 }
315 #else
316 INLINE int event_select(Event **evs, int n, ticks_t timeout)
317 {
318         ticks_t end = timer_clock() + timeout;
319         int i;
320
321         while (1)
322         {
323                 for (i = 0; i < n; i++)
324                 {
325                         Event *e = evs[i];
326                         if (ACCESS_SAFE(e->Ev.Gen.completed) == true)
327                         {
328                                 e->Ev.Gen.completed = false;
329                                 MEMORY_BARRIER;
330                                 return i;
331                         }
332                 }
333                 if (timeout && TIMER_AFTER(timer_clock(), end))
334                         break;
335                 cpu_relax();
336         }
337         return -1;
338 }
339 #endif
340
341
342 #if CONFIG_TIMER_EVENTS
343 #include <drv/timer.h> /* timer_clock() */
344
345 /**
346  * Wait the completion of event \a e or \a timeout elapses.
347  *
348  * \note It's forbidden to use this function inside irq handling functions.
349  */
350 INLINE bool event_waitTimeout(Event *e, ticks_t timeout)
351 {
352         bool ret;
353
354 #if defined(CONFIG_KERN_SIGNALS) && CONFIG_KERN_SIGNALS
355         e->Ev.Sig.sig_proc = proc_current();
356         ret = (sig_waitTimeoutSignal(&e->Ev.SigGen.sig,
357                                 EVENT_GENERIC_SIGNAL, timeout) & SIG_TIMEOUT) ?
358                                 false : true;
359 #else
360         ticks_t end = timer_clock() + timeout;
361
362         while ((ACCESS_SAFE(e->Ev.Gen.completed) == false) ||
363                         TIMER_AFTER(timer_clock(), end))
364                 cpu_relax();
365         ret = e->Ev.Gen.completed;
366         e->Ev.Gen.completed = false;
367 #endif
368         MEMORY_BARRIER;
369         return ret;
370 }
371 #endif /* CONFIG_TIMER_EVENTS */
372
373 /**
374  * Trigger an event.
375  *
376  * Execute the callback function associated with event \a e.
377  *
378  * This function can be used also in interrupt routines, but only if the
379  * event was created as a signal or generic event.
380  */
381 INLINE void event_do(struct Event *e)
382 {
383         e->action(e);
384 }
385
386 /** \} */
387
388 #endif /* KERN_EVENT_H */