Merge branch "preempt" in "trunk".
[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  * Any execution context, including an interrupt handler, can deliver
69  * a signal to a process using sig_signal().  Multiple independent signals
70  * may be delivered at once with a single invocation of sig_signal(),
71  * although this is rarely useful.
72  *
73  * \section signal_allocation Signal Allocation
74  *
75  * There's no hardcoded mapping of specific events to signal bits.
76  * The meaning of a particular signal bit is defined by an agreement
77  * between the delivering entity and the receiving process.
78  * For instance, a terminal driver may be designed to deliver
79  * a signal bit called SIG_INT when it reads the CTRL-C sequence
80  * from the keyboard, and a process may react to it by quitting.
81  *
82  * \section sig_single SIG_SINGLE
83  *
84  * The SIG_SINGLE bit is reserved as a convenient shortcut in those
85  * simple scenarios where a process needs to wait on just one event
86  * synchronously.  By using SIG_SINGLE, there's no need to allocate
87  * a specific signal from the free pool.  The constraints for safely
88  * accessing SIG_SINGLE are:
89  *  - The process MUST sig_wait() exclusively on SIG_SINGLE
90  *  - SIG_SIGNAL MUST NOT be left pending after use (sig_wait() will reset
91  *        it automatically)
92  *  - Do not sleep between starting the asynchronous task that will fire
93  *    SIG_SINGLE, and the call to  sig_wait().
94  *  - Do not call system functions that may implicitly sleep, such as
95  *    timer_delayTicks().
96  *
97  * \version $Id$
98  * \author Bernie Innocenti <bernie@codewiz.org>
99  */
100
101 #include "signal.h"
102
103 #include "cfg/cfg_timer.h"
104 #include <cfg/debug.h>
105 #include <cfg/depend.h>
106
107 #include <cpu/irq.h>
108 #include <kern/proc.h>
109 #include <kern/proc_p.h>
110
111
112 #if CONFIG_KERN_SIGNALS
113
114 // Check config dependencies
115 CONFIG_DEPEND(CONFIG_KERN_SIGNALS, CONFIG_KERN);
116
117 /**
118  * Check if any of the signals in \a sigs has occurred and clear them.
119  *
120  * \return the signals that have occurred.
121  */
122 sigmask_t sig_check(sigmask_t sigs)
123 {
124         sigmask_t result;
125         cpu_flags_t flags;
126
127         IRQ_SAVE_DISABLE(flags);
128         result = current_process->sig_recv & sigs;
129         current_process->sig_recv &= ~sigs;
130         IRQ_RESTORE(flags);
131
132         return result;
133 }
134
135
136 /**
137  * Sleep until any of the signals in \a sigs occurs.
138  * \return the signal(s) that have awoken the process.
139  */
140 sigmask_t sig_wait(sigmask_t sigs)
141 {
142         sigmask_t result;
143
144         /* Sleeping with IRQs disabled or preemption forbidden is illegal */
145         IRQ_ASSERT_ENABLED();
146         ASSERT(proc_preemptAllowed());
147
148         /*
149          * This is subtle: there's a race condition where a concurrent
150          * process or an interrupt may call sig_signal() to set a bit in
151          * Process.sig_recv just after we have checked for it, but before
152          * we've set Process.sig_wait to let them know we want to be awaken.
153          *
154          * In this case, we'd deadlock with the signal bit already set
155          * and the process never being reinserted into the ready list.
156          */
157         IRQ_DISABLE;
158
159         /* Loop until we get at least one of the signals */
160         while (!(result = current_process->sig_recv & sigs))
161         {
162                 /*
163                  * Tell "them" that we want to be awaken when any of these
164                  * signals arrives.
165                  */
166                 current_process->sig_wait = sigs;
167
168                 /*
169                  * Go to sleep and proc_switch() to another process.
170                  *
171                  * We re-enable IRQs because proc_switch() does not
172                  * guarantee to save and restore the interrupt mask.
173                  */
174                 IRQ_ENABLE;
175                 proc_switch();
176                 IRQ_DISABLE;
177
178                 /*
179                  * When we come back here, the wait mask must have been
180                  * cleared by someone through sig_signal(), and at least
181                  * one of the signals we were expecting must have been
182                  * delivered to us.
183                  */
184                 ASSERT(!current_process->sig_wait);
185                 ASSERT(current_process->sig_recv & sigs);
186         }
187
188         /* Signals found: clear them and return */
189         current_process->sig_recv &= ~sigs;
190
191         IRQ_ENABLE;
192         return result;
193 }
194
195 #if CONFIG_TIMER_EVENTS
196
197 #include <drv/timer.h>
198 /**
199  * Sleep until any of the signals in \a sigs or \a timeout ticks elapse.
200  * If the timeout elapse a SIG_TIMEOUT is added to the received signal(s).
201  * \return the signal(s) that have awoken the process.
202  * \note Caller must check return value to check which signal awoke the process.
203  */
204 sigmask_t sig_waitTimeout(sigmask_t sigs, ticks_t timeout)
205 {
206         Timer t;
207         sigmask_t res;
208         cpu_flags_t flags;
209
210         ASSERT(!sig_check(SIG_TIMEOUT));
211         ASSERT(!(sigs & SIG_TIMEOUT));
212         /* IRQ are needed to run timer */
213         ASSERT(IRQ_ENABLED());
214
215         timer_set_event_signal(&t, proc_current(), SIG_TIMEOUT);
216         timer_setDelay(&t, timeout);
217         timer_add(&t);
218         res = sig_wait(SIG_TIMEOUT | sigs);
219
220         IRQ_SAVE_DISABLE(flags);
221         /* Remove timer if sigs occur before timer signal */
222         if (!(res & SIG_TIMEOUT) && !sig_check(SIG_TIMEOUT))
223                 timer_abort(&t);
224         IRQ_RESTORE(flags);
225         return res;
226 }
227
228 #endif // CONFIG_TIMER_EVENTS
229
230
231 /**
232  * Send the signals \a sigs to the process \a proc.
233  * The process will be awoken if it was waiting for any of them.
234  *
235  * \note This call is interrupt safe.
236  */
237 void sig_signal(Process *proc, sigmask_t sigs)
238 {
239         cpu_flags_t flags;
240
241         /* See comment in sig_wait() for why this protection is necessary */
242         IRQ_SAVE_DISABLE(flags);
243
244         /* Set the signals */
245         proc->sig_recv |= sigs;
246
247         /* Check if process needs to be awoken */
248         if (proc->sig_recv & proc->sig_wait)
249         {
250                 /*
251                  * Wake up process and enqueue in ready list.
252                  *
253                  * Move this process to the head of the ready list, so that it
254                  * will be chosen at the next scheduling point.
255                  */
256                 proc->sig_wait = 0;
257                 SCHED_ENQUEUE_HEAD(proc);
258         }
259
260         IRQ_RESTORE(flags);
261 }
262
263 #endif /* CONFIG_KERN_SIGNALS */