Update preset.
[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]____sig_send()____proc_wakeup()____[P2]
79  * </pre>
80  *
81  * In the asynchronous case, the process is scheduled for execution as a
82  * consequence of the delivery, but it will be dispatched by the scheduler as
83  * usual, according to the scheduling policy.
84  *
85  * <pre>
86  * - Asynchronous-signal delivery:
87  *
88  *     [P1]____sig_post()____[P1]____proc_schedule()____[P2]
89  * </pre>
90  *
91  * In this way, any execution context, including an interrupt handler, can
92  * deliver a signal to a process. However, synchronous signal delivery from a
93  * non-sleepable context (like an interrupt handler) is forbidden in order to
94  * avoid potential deadlock conditions. Instead, sig_post() can be used from
95  * any context, expecially from interrupt context or when the preemption is
96  * disabled.
97  *
98  * Multiple independent signals may be delivered at once with a single
99  * invocation of sig_send() or sig_post(), although this is rarely useful.
100  *
101  * \section signal_allocation Signal Allocation
102  *
103  * There's no hardcoded mapping of specific events to signal bits.
104  * The meaning of a particular signal bit is defined by an agreement
105  * between the delivering entity and the receiving process.
106  * For instance, a terminal driver may be designed to deliver
107  * a signal bit called SIG_INT when it reads the CTRL-C sequence
108  * from the keyboard, and a process may react to it by quitting.
109  *
110  * \section sig_single SIG_SINGLE
111  *
112  * The SIG_SINGLE bit is reserved as a convenient shortcut in those
113  * simple scenarios where a process needs to wait on just one event
114  * synchronously.  By using SIG_SINGLE, there's no need to allocate
115  * a specific signal from the free pool.  The constraints for safely
116  * accessing SIG_SINGLE are:
117  *  - The process MUST sig_wait() exclusively on SIG_SINGLE
118  *  - SIG_SIGNAL MUST NOT be left pending after use (sig_wait() will reset
119  *        it automatically)
120  *  - Do not sleep between starting the asynchronous task that will fire
121  *    SIG_SINGLE, and the call to  sig_wait().
122  *  - Do not call system functions that may implicitly sleep, such as
123  *    timer_delayTicks().
124  *
125  * \author Bernie Innocenti <bernie@codewiz.org>
126  */
127
128 #include "signal.h"
129
130 #include "cfg/cfg_timer.h"
131 #include <cfg/debug.h>
132 #include <cfg/depend.h>
133
134 #include <cpu/irq.h>
135 #include <kern/proc.h>
136 #include <kern/proc_p.h>
137
138
139 #if CONFIG_KERN_SIGNALS
140
141 // Check config dependencies
142 CONFIG_DEPEND(CONFIG_KERN_SIGNALS, CONFIG_KERN);
143
144 sigmask_t sig_waitSignal(Signal *s, sigmask_t sigs)
145 {
146         sigmask_t result;
147
148         /* Sleeping with IRQs disabled or preemption forbidden is illegal */
149         IRQ_ASSERT_ENABLED();
150         ASSERT(proc_preemptAllowed());
151
152         /*
153          * This is subtle: there's a race condition where a concurrent process
154          * or an interrupt may call sig_send()/sig_post() to set a bit in
155          * Process.sig_recv just after we have checked for it, but before we've
156          * set Process.sig_wait to let them know we want to be awaken.
157          *
158          * In this case, we'd deadlock with the signal bit already set and the
159          * process never being reinserted into the ready list.
160          */
161         IRQ_DISABLE;
162
163         /* Loop until we get at least one of the signals */
164         while (!(result = s->recv & sigs))
165         {
166                 /*
167                  * Tell "them" that we want to be awaken when any of these
168                  * signals arrives.
169                  */
170                 s->wait = sigs;
171
172                 /* Go to sleep and proc_switch() to another process. */
173                 proc_switch();
174                 /*
175                  * When we come back here, the wait mask must have been
176                  * cleared by someone through sig_send()/sig_post(), and at
177                  * least one of the signals we were expecting must have been
178                  * delivered to us.
179                  */
180                 ASSERT(!s->wait);
181                 ASSERT(s->recv & sigs);
182         }
183
184         /* Signals found: clear them and return */
185         s->recv &= ~sigs;
186
187         IRQ_ENABLE;
188         return result;
189 }
190
191 #if CONFIG_TIMER_EVENTS
192
193 #include <drv/timer.h>
194
195 sigmask_t sig_waitTimeoutSignal(Signal *s, sigmask_t sigs, ticks_t timeout,
196                                 Hook func, iptr_t data)
197 {
198         Timer t;
199         sigmask_t res;
200         cpu_flags_t flags;
201
202         ASSERT(!sig_checkSignal(s, SIG_TIMEOUT));
203         ASSERT(!(sigs & SIG_TIMEOUT));
204         /* IRQ are needed to run timer */
205         ASSERT(IRQ_ENABLED());
206
207         if (func)
208                 timer_setSoftint(&t, func, data);
209         else
210                 timer_set_event_signal(&t, proc_current(), SIG_TIMEOUT);
211         timer_setDelay(&t, timeout);
212         timer_add(&t);
213         res = sig_waitSignal(s, SIG_TIMEOUT | sigs);
214
215         IRQ_SAVE_DISABLE(flags);
216         /* Remove timer if sigs occur before timer signal */
217         if (!(res & SIG_TIMEOUT) && !sig_checkSignal(s, SIG_TIMEOUT))
218                 timer_abort(&t);
219         IRQ_RESTORE(flags);
220         return res;
221 }
222
223 #endif // CONFIG_TIMER_EVENTS
224
225 INLINE void __sig_signal(Signal *s, Process *proc, sigmask_t sigs, bool wakeup)
226 {
227         cpu_flags_t flags;
228
229         IRQ_SAVE_DISABLE(flags);
230
231         /* Set the signals */
232         s->recv |= sigs;
233
234         /* Check if process needs to be awoken */
235         if (s->recv & s->wait)
236         {
237                 ASSERT(proc != current_process);
238
239                 s->wait = 0;
240                 if (wakeup)
241                         proc_wakeup(proc);
242                 else
243                         SCHED_ENQUEUE_HEAD(proc);
244         }
245         IRQ_RESTORE(flags);
246 }
247
248 void sig_sendSignal(Signal *s, Process *proc, sigmask_t sigs)
249 {
250         ASSERT_USER_CONTEXT();
251         IRQ_ASSERT_ENABLED();
252         ASSERT(proc_preemptAllowed());
253
254         __sig_signal(s, proc, sigs, true);
255 }
256
257 void sig_postSignal(Signal *s, Process *proc, sigmask_t sigs)
258 {
259         __sig_signal(s, proc, sigs, false);
260 }
261
262 #endif /* CONFIG_KERN_SIGNALS */