37a37a255196d5655ee35ce45273932a54c81475
[bertos.git] / bertos / kern / signal.c
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 2004, 2008 Develer S.r.l. (http://www.develer.com/)
30  * Copyright 1999, 2000, 2001 Bernie Innocenti <bernie@codewiz.org>
31  * -->
32  *
33  * \brief IPC signals implementation.
34  *
35  * Signals are a low-level IPC primitive.  A process receives a signal
36  * when some external event has happened.  Like interrupt requests,
37  * signals do not carry any additional information.  If processing a
38  * specific event requires additional data, the process must obtain it
39  * through some other mechanism.
40  *
41  * Despite the name, one shouldn't confuse these signals with POSIX
42  * signals.  POSIX signals are usually executed synchronously, like
43  * software interrupts.
44  *
45  * Signals are very low overhead.  Using them exclusively to wait
46  * for multiple asynchronous events results in very simple dispatch
47  * logic with low processor and resource usage.
48  *
49  * The "event" module is a higher-level interface that can optionally
50  * deliver signals to processes.  Messages provide even higher-level
51  * IPC services built on signals.  Semaphore arbitration is also
52  * implemented using signals.
53  *
54  * In this implementation, each process has a limited set of signal
55  * bits (usually 32) and can wait for multiple signals at the same
56  * time using sig_wait().  Signals can also be polled using sig_check(),
57  * but a process spinning on its signals usually defeats their purpose
58  * of providing a multitasking-friendly infrastructure for event-driven
59  * applications.
60  *
61  * Signals are like flags: they are either active or inactive.  After an
62  * external event has delivered a particular signal, it remains raised until
63  * the process acknowledges it using either sig_wait() or sig_check().
64  * Counting signals is not a reliable way to count how many times a
65  * particular event has occurred, because the same signal may be
66  * delivered twice before the process can notice.
67  *
68  * Signals can be delivered synchronously via sig_send() or asynchronously via
69  * sig_post().
70  *
71  * In the synchronous case the process is awakened if it was waiting for any
72  * signal and immediately dispatched for execution via a direct context switch,
73  * if its priority is greater than the running process.
74  *
75  * <pre>
76  * - Synchronous-signal delivery:
77  *
78  *     P1__                                   __P2
79  *         \                                 /
80  *          \__sig_send()____proc_wakeup()__/
81  * </pre>
82  *
83  * In the asynchronous case, the process is scheduled for execution as a
84  * consequence of the delivery, but it will be dispatched by the scheduler as
85  * usual, according to the scheduling policy.
86  *
87  * <pre>
88  * - Asynchronous-signal delivery:
89  *
90  *     P1__                  __P1__                       __P2
91  *         \                /      \                     /
92  *          \__sig_post()__/        \__proc_schedule()__/
93  * </pre>
94  *
95  * In this way, any execution context, including an interrupt handler, can
96  * deliver a signal to a process. However, synchronous signal delivery from a
97  * non-sleepable context (like an interrupt handler) is forbidden in order to
98  * avoid potential deadlock conditions. Instead, sig_post() can be used from
99  * any context, expecially from interrupt context or when the preemption is
100  * disabled.
101  *
102  * Multiple independent signals may be delivered at once with a single
103  * invocation of sig_send() or sig_post(), although this is rarely useful.
104  *
105  * \section signal_allocation Signal Allocation
106  *
107  * There's no hardcoded mapping of specific events to signal bits.
108  * The meaning of a particular signal bit is defined by an agreement
109  * between the delivering entity and the receiving process.
110  * For instance, a terminal driver may be designed to deliver
111  * a signal bit called SIG_INT when it reads the CTRL-C sequence
112  * from the keyboard, and a process may react to it by quitting.
113  *
114  * \section sig_single SIG_SINGLE
115  *
116  * The SIG_SINGLE bit is reserved as a convenient shortcut in those
117  * simple scenarios where a process needs to wait on just one event
118  * synchronously.  By using SIG_SINGLE, there's no need to allocate
119  * a specific signal from the free pool.  The constraints for safely
120  * accessing SIG_SINGLE are:
121  *  - The process MUST sig_wait() exclusively on SIG_SINGLE
122  *  - SIG_SIGNAL MUST NOT be left pending after use (sig_wait() will reset
123  *        it automatically)
124  *  - Do not sleep between starting the asynchronous task that will fire
125  *    SIG_SINGLE, and the call to  sig_wait().
126  *  - Do not call system functions that may implicitly sleep, such as
127  *    timer_delayTicks().
128  *
129  * \version $Id$
130  * \author Bernie Innocenti <bernie@codewiz.org>
131  */
132
133 #include "signal.h"
134
135 #include "cfg/cfg_timer.h"
136 #include <cfg/debug.h>
137 #include <cfg/depend.h>
138
139 #include <cpu/irq.h>
140 #include <kern/proc.h>
141 #include <kern/proc_p.h>
142
143
144 #if CONFIG_KERN_SIGNALS
145
146 // Check config dependencies
147 CONFIG_DEPEND(CONFIG_KERN_SIGNALS, CONFIG_KERN);
148
149 /**
150  * Check if any of the signals in \a sigs has occurred and clear them.
151  *
152  * \return the signals that have occurred.
153  */
154 sigmask_t sig_check(sigmask_t sigs)
155 {
156         sigmask_t result;
157         cpu_flags_t flags;
158
159         IRQ_SAVE_DISABLE(flags);
160         result = current_process->sig_recv & sigs;
161         current_process->sig_recv &= ~sigs;
162         IRQ_RESTORE(flags);
163
164         return result;
165 }
166
167
168 /**
169  * Sleep until any of the signals in \a sigs occurs.
170  * \return the signal(s) that have awoken the process.
171  */
172 sigmask_t sig_wait(sigmask_t sigs)
173 {
174         sigmask_t result;
175
176         /* Sleeping with IRQs disabled or preemption forbidden is illegal */
177         IRQ_ASSERT_ENABLED();
178         ASSERT(proc_preemptAllowed());
179
180         /*
181          * This is subtle: there's a race condition where a concurrent process
182          * or an interrupt may call sig_send()/sig_post() to set a bit in
183          * Process.sig_recv just after we have checked for it, but before we've
184          * set Process.sig_wait to let them know we want to be awaken.
185          *
186          * In this case, we'd deadlock with the signal bit already set and the
187          * process never being reinserted into the ready list.
188          */
189         IRQ_DISABLE;
190
191         /* Loop until we get at least one of the signals */
192         while (!(result = current_process->sig_recv & sigs))
193         {
194                 /*
195                  * Tell "them" that we want to be awaken when any of these
196                  * signals arrives.
197                  */
198                 current_process->sig_wait = sigs;
199
200                 /* Go to sleep and proc_switch() to another process. */
201                 proc_switch();
202                 /*
203                  * When we come back here, the wait mask must have been
204                  * cleared by someone through sig_send()/sig_post(), and at
205                  * least one of the signals we were expecting must have been
206                  * delivered to us.
207                  */
208                 ASSERT(!current_process->sig_wait);
209                 ASSERT(current_process->sig_recv & sigs);
210         }
211
212         /* Signals found: clear them and return */
213         current_process->sig_recv &= ~sigs;
214
215         IRQ_ENABLE;
216         return result;
217 }
218
219 #if CONFIG_TIMER_EVENTS
220
221 #include <drv/timer.h>
222 /**
223  * Sleep until any of the signals in \a sigs or \a timeout ticks elapse.
224  * If the timeout elapse a SIG_TIMEOUT is added to the received signal(s).
225  * \return the signal(s) that have awoken the process.
226  * \note Caller must check return value to check which signal awoke the process.
227  */
228 sigmask_t sig_waitTimeout(sigmask_t sigs, ticks_t timeout)
229 {
230         Timer t;
231         sigmask_t res;
232         cpu_flags_t flags;
233
234         ASSERT(!sig_check(SIG_TIMEOUT));
235         ASSERT(!(sigs & SIG_TIMEOUT));
236         /* IRQ are needed to run timer */
237         ASSERT(IRQ_ENABLED());
238
239         timer_set_event_signal(&t, proc_current(), SIG_TIMEOUT);
240         timer_setDelay(&t, timeout);
241         timer_add(&t);
242         res = sig_wait(SIG_TIMEOUT | sigs);
243
244         IRQ_SAVE_DISABLE(flags);
245         /* Remove timer if sigs occur before timer signal */
246         if (!(res & SIG_TIMEOUT) && !sig_check(SIG_TIMEOUT))
247                 timer_abort(&t);
248         IRQ_RESTORE(flags);
249         return res;
250 }
251
252 #endif // CONFIG_TIMER_EVENTS
253
254 INLINE void __sig_signal(Process *proc, sigmask_t sigs, bool wakeup)
255 {
256         cpu_flags_t flags;
257
258         if (UNLIKELY(proc == current_process))
259                 return;
260
261         IRQ_SAVE_DISABLE(flags);
262
263         /* Set the signals */
264         proc->sig_recv |= sigs;
265
266         /* Check if process needs to be awoken */
267         if (proc->sig_recv & proc->sig_wait)
268         {
269                 proc->sig_wait = 0;
270                 if (wakeup)
271                         proc_wakeup(proc);
272                 else
273                         SCHED_ENQUEUE_HEAD(proc);
274         }
275         IRQ_RESTORE(flags);
276 }
277
278 /**
279  * Send the signals \a sigs to the process \a proc and immeditaly dispatch it
280  * for execution.
281  *
282  * The process will be awoken if it was waiting for any of them and immediately
283  * dispatched for execution.
284  *
285  * \note This function can't be called from IRQ context, use sig_post()
286  * instead.
287  */
288 void sig_send(Process *proc, sigmask_t sigs)
289 {
290         ASSERT_USER_CONTEXT();
291         IRQ_ASSERT_ENABLED();
292         ASSERT(proc_preemptAllowed());
293
294         __sig_signal(proc, sigs, true);
295 }
296
297 /**
298  * Send the signals \a sigs to the process \a proc.
299  * The process will be awoken if it was waiting for any of them.
300  *
301  * \note This call is interrupt safe.
302  */
303 void sig_post(Process *proc, sigmask_t sigs)
304 {
305         __sig_signal(proc, sigs, false);
306 }
307
308 #endif /* CONFIG_KERN_SIGNALS */