blob: ede769d8b9bb67982f841589d14790df18d8aa10 [file] [log] [blame]
Harald Welte136e7372016-05-29 10:53:17 +09001/* Osmocom generic Finite State Machine implementation
2 *
3 * (C) 2016 by Harald Welte <laforge@gnumonks.org>
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
18 * MA 02110-1301, USA.
19 */
20
21#include <errno.h>
22#include <stdbool.h>
23
24#include <osmocom/core/fsm.h>
25#include <osmocom/core/talloc.h>
26#include <osmocom/core/logging.h>
27#include <osmocom/core/utils.h>
28
29/*! \addtogroup fsm
30 * @{
31 */
32
33/*! \file fsm.c
34 * \brief Finite State Machine abstraction
35 *
36 * This is a generic C-language abstraction for implementing finite
37 * state machines within the Osmocom framework. It is intended to
38 * replace existing hand-coded or even only implicitly existing FSMs
39 * all over the existing code base.
40 *
41 * An libosmocore FSM is described by its \ref osmo_fsm description,
42 * which in turn refers to an array of \ref osmo_fsm_state descriptor,
43 * each describing a single state in the FSM.
44 *
45 * The general idea is that all actions performed within one state are
46 * located at one position in the code (the state's action function),
47 * as opposed to the 'message-centric' view of e.g. the existing
48 * state machines of the LAPD(m) coe, where there is one message for
49 * eahc possible event (primitive), and the function then needs to
50 * concern itself on how to handle that event over all possible states.
51 *
52 * For each state, there is a bit-mask of permitted input events for
53 * this state, as well as a bit-mask of permitted new output states to
54 * which the state can change. Furthermore, there is a function
55 * pointer implementing the actual handling of the input events
56 * occurring whilst in thta state.
57 *
58 * Furthermore, each state offers a function pointer that can be
59 * executed just before leaving a state, and another one just after
60 * entering a state.
61 *
62 * When transitioning into a new state, an optional timer number and
63 * time-out can be passed along. The timer is started just after
64 * entering the new state, and will call the \ref osmo_fsm timer_cb
65 * function once it expires. This is intended to be used in telecom
66 * state machines where a given timer (identified by a certain number)
67 * is started to terminate the fsm or terminate the fsm once expected
68 * events are not happening before timeout expiration.
69 *
70 * As there can often be many concurrent FSMs of one given class, we
71 * introduce the concept of \ref osmo_fsm_inst, i.e. an FSM instance.
72 * The instance keeps the actual state, while the \ref osmo_fsm
73 * descriptor contains the static/const descriptor of the FSM's states
74 * and possible transitions.
75 *
76 * osmo_fsm are integrated with the libosmocore logging system. The
77 * logging sub-system is determined by the FSM descriptor, as we assume
78 * one FSM (let's say one related to a location update procedure) is
79 * inevitably always tied to a sub-system. The logging level however
80 * is configurable for each FSM instance, to ensure that e.g. DEBUG
81 * logging can be used for the LU procedure of one subscriber, while
82 * NOTICE level is used for all other subscribers.
83 *
84 * In order to attach private state to the \ref osmo_fsm_inst, it
85 * offers an opaque priv pointer.
86 *
87 */
88
89static LLIST_HEAD(g_fsms);
90static bool fsm_log_addr = true;
91
92/*! \brief specify if FSM instance addresses should be logged or not
93 *
94 * By default, the FSM name includes the pointer address of the \ref
95 * osmo_fsm_inst. This behaviro can be disabled (and re-enabled)
96 * using this function.
97 *
98 * \param[in] log_addr Indicate if FSM instance address shall be logged
99 */
100void osmo_fsm_log_addr(bool log_addr)
101{
102 fsm_log_addr = false;
103}
104
105/*! \brief register a FSM with the core
106 *
107 * A FSM descriptor needs to be registered with the core before any
108 * instances can be created for it.
109 *
110 * \param[in] fsm Descriptor of Finite State Machine to be registered
111 * \returns 0 on success; negative on error
112 */
113int osmo_fsm_register(struct osmo_fsm *fsm)
114{
115 /* FIXME:check for duplicate name? */
116 llist_add_tail(&fsm->list, &g_fsms);
117 INIT_LLIST_HEAD(&fsm->instances);
118
119 return 0;
120}
121
122/*! \brief unregister a FSM from the core
123 *
124 * Once the FSM descriptor is unregistered, active instances can still
125 * use it, but no new instances may be created for it.
126 *
127 * \param[in] fsm Descriptor of Finite State Machine to be removed
128 */
129void osmo_fsm_unregister(struct osmo_fsm *fsm)
130{
131 llist_del(&fsm->list);
132}
133
134/* small wrapper function around timer expiration (for logging) */
135static void fsm_tmr_cb(void *data)
136{
137 struct osmo_fsm_inst *fi = data;
138 struct osmo_fsm *fsm = fi->fsm;
139
140 LOGPFSM(fi, "Timeout of T%u\n", fi->T);
141
142 fsm->timer_cb(fi);
143}
144
145/*! \brief allocate a new instance of a specified FSM
146 * \param[in] fsm Descriptor of the FSM
147 * \param[in] ctx talloc context from which to allocate memory
148 * \param[in] priv private data reference store in fsm instance
149 * \param[in] log_level The log level for events of this FSM
150 * \returns newly-allocated, initialized and registered FSM instance
151 */
152struct osmo_fsm_inst *osmo_fsm_inst_alloc(struct osmo_fsm *fsm, void *ctx, void *priv,
153 int log_level, const char *id)
154{
155 struct osmo_fsm_inst *fi = talloc_zero(ctx, struct osmo_fsm_inst);
156
157 fi->fsm = fsm;
158 fi->priv = priv;
159 fi->log_level = log_level;
160 fi->timer.data = fi;
161 fi->timer.cb = fsm_tmr_cb;
162 fi->id = id;
163
164 if (!fsm_log_addr) {
165 if (id)
166 fi->name = talloc_asprintf(fi, "%s(%s)", fsm->name, id);
167 else
168 fi->name = talloc_asprintf(fi, "%s", fsm->name);
169 } else {
170 if (id)
171 fi->name = talloc_asprintf(fi, "%s(%s)[%p]", fsm->name,
172 id, fi);
173 else
174 fi->name = talloc_asprintf(fi, "%s[%p]", fsm->name, fi);
175 }
176
177 INIT_LLIST_HEAD(&fi->proc.children);
178 INIT_LLIST_HEAD(&fi->proc.child);
179 llist_add(&fi->list, &fsm->instances);
180
181 LOGPFSM(fi, "Allocated\n");
182
183 return fi;
184}
185
186/*! \brief allocate a new instance of a specified FSM as child of
187 * other FSM instance
188 *
189 * This is like \ref osmo_fsm_inst_alloc but using the parent FSM as
190 * talloc context, and inheriting the log level of the parent.
191 *
192 * \param[in] fsm Descriptor of the to-be-allocated FSM
193 * \param[in] parent Parent FSM instance
194 * \param[in] parent_term_event Event to be sent to parent when terminating
195 * \returns newly-allocated, initialized and registered FSM instance
196 */
197struct osmo_fsm_inst *osmo_fsm_inst_alloc_child(struct osmo_fsm *fsm,
198 struct osmo_fsm_inst *parent,
199 uint32_t parent_term_event)
200{
201 struct osmo_fsm_inst *fi;
202
203 fi = osmo_fsm_inst_alloc(fsm, parent, NULL, parent->log_level,
204 parent->id);
205 if (!fi) {
206 /* indicate immediate termination to caller */
207 osmo_fsm_inst_dispatch(parent, parent_term_event, NULL);
208 return NULL;
209 }
210
211 LOGPFSM(fi, "is child of %s\n", osmo_fsm_inst_name(parent));
212
213 fi->proc.parent = parent;
214 fi->proc.parent_term_event = parent_term_event;
215 llist_add(&fi->proc.child, &parent->proc.children);
216
217 return fi;
218}
219
220/*! \brief delete a given instance of a FSM
221 * \param[in] fsm The FSM to be un-registered and deleted
222 */
223void osmo_fsm_inst_free(struct osmo_fsm_inst *fi)
224{
225 osmo_timer_del(&fi->timer);
226 llist_del(&fi->list);
227 talloc_free(fi);
228}
229
230/*! \brief get human-readable name of FSM event
231 * \param[in] fsm FSM descriptor of event
232 * \param[in] event Event integer value
233 * \returns string rendering of the event
234 */
235const char *osmo_fsm_event_name(struct osmo_fsm *fsm, uint32_t event)
236{
237 static char buf[32];
238 if (!fsm->event_names) {
239 snprintf(buf, sizeof(buf), "%u", event);
240 return buf;
241 } else
242 return get_value_string(fsm->event_names, event);
243}
244
245/*! \brief get human-readable name of FSM instance
246 * \param[in] fi FSM instance
247 * \returns string rendering of the FSM identity
248 */
249const char *osmo_fsm_inst_name(struct osmo_fsm_inst *fi)
250{
251 if (!fi)
252 return "NULL";
253
254 if (fi->name)
255 return fi->name;
256 else
257 return fi->fsm->name;
258}
259
260/*! \brief get human-readable name of FSM instance
261 * \param[in] fsm FSM descriptor
262 * \param[in] state FSM state number
263 * \returns string rendering of the FSM state
264 */
265const char *osmo_fsm_state_name(struct osmo_fsm *fsm, uint32_t state)
266{
267 static char buf[32];
268 if (state >= fsm->num_states) {
269 snprintf(buf, sizeof(buf), "unknown %u", state);
270 return buf;
271 } else
272 return fsm->states[state].name;
273}
274
275/*! \brief perform a state change of the given FSM instance
276 *
277 * All changes to the FSM instance state must be made via this
278 * function. It verifies that the existing state actually permits a
279 * transiiton to new_state.
280 *
281 * timeout_secs and T are optional parameters, and only have any effect
282 * if timeout_secs is not 0. If the timeout function is used, then the
283 * new_state is entered, and the FSM instances timer is set to expire
284 * in timeout_secs functions. At that time, the FSM's timer_cb
285 * function will be called for handling of the timeout by the user.
286 *
287 * \param[in] fi FSM instance whose state is to change
288 * \param[in] new_state The new state into which we should change
289 * \param[in] timeout_secs Timeout in seconds (if !=0)
290 * \param[in] T Timer number (if \ref timeout_secs != 0)
291 * \returns 0 on success; negative on error
292 */
293int osmo_fsm_inst_state_chg(struct osmo_fsm_inst *fi, uint32_t new_state,
294 unsigned long timeout_secs, int T)
295{
296 struct osmo_fsm *fsm = fi->fsm;
297 uint32_t old_state = fi->state;
298 const struct osmo_fsm_state *st = &fsm->states[fi->state];
299
300 /* validate if new_state is a valid state */
301 if (!(st->out_state_mask & (1 << new_state))) {
302 LOGP(fsm->log_subsys, LOGL_ERROR, "%s(%s): transition to "
303 "state %s not permitted!\n",
304 osmo_fsm_inst_name(fi),
305 osmo_fsm_state_name(fsm, fi->state),
306 osmo_fsm_state_name(fsm, new_state));
307 return -EPERM;
308 }
309
310 if (st->onleave)
311 st->onleave(fi, new_state);
312
313 LOGPFSM(fi, "state_chg to %s\n", osmo_fsm_state_name(fsm, new_state));
314 fi->state = new_state;
315
316 if (st->onenter)
317 st->onenter(fi, old_state);
318
319 if (timeout_secs) {
320 if (!fsm->timer_cb)
321 LOGP(fsm->log_subsys, LOGL_ERROR, "cannot start "
322 "timer for FSM without timer call-back\n");
323 else {
324 fi->T = T;
325 osmo_timer_schedule(&fi->timer, timeout_secs, 0);
326 }
327 }
328
329 return 0;
330}
331
332/*! \brief dispatch an event to an osmocom finite state machine instance
333 *
334 * Any incoming events to \ref osmo_fsm instances must be dispatched to
335 * them via this function. It verifies, whether the event is permitted
336 * based on the current state of the FSM. If not, -1 is returned.
337 *
338 * \param[in] fi FSM instance
339 * \param[in] event Event to send to FSM instance
340 * \param[in] data Data to pass along with the event
341 * \returns 0 in case of success; negative on error
342 */
343int osmo_fsm_inst_dispatch(struct osmo_fsm_inst *fi, uint32_t event, void *data)
344{
345 struct osmo_fsm *fsm;
346 const struct osmo_fsm_state *fs;
347
348 if (!fi) {
349 LOGP(DLGLOBAL, LOGL_ERROR, "Trying to dispatch event %u to "
350 "non-existing FSM Instance!\n", event);
351 osmo_log_backtrace(DLGLOBAL, LOGL_ERROR);
352 return -ENODEV;
353 }
354
355 fsm = fi->fsm;
356 OSMO_ASSERT(fi->state < fsm->num_states);
357 fs = &fi->fsm->states[fi->state];
358
359 LOGPFSM(fi, "Received Event %s\n", osmo_fsm_event_name(fsm, event));
360
361 if (((1 << event) & fsm->allstate_event_mask) && fsm->allstate_action) {
362 fsm->allstate_action(fi, event, data);
363 return 0;
364 }
365
366 if (!((1 << event) & fs->in_event_mask)) {
367 LOGP(fsm->log_subsys, LOGL_ERROR, "%s(%s): Event %s not "
368 "permitted\n", osmo_fsm_inst_name(fi),
369 osmo_fsm_state_name(fsm, fi->state),
370 osmo_fsm_event_name(fsm, event));
371 return -1;
372 }
373 fs->action(fi, event, data);
374
375 return 0;
376}
377
378/*! \brief Terminate FSM instance with given cause
379 *
380 * This safely terminates the given FSM instance by first iterating
381 * over all children and sending them a termination event. Next, it
382 * calls the FSM descriptors cleanup function (if any), followed by
383 * releasing any memory associated with the FSM instance.
384 *
385 * Finally, the parent FSM instance (if any) is notified using the
386 * parent termination event configured at time of FSM instance start.
387 *
388 * \param[in] fi FSM instance to be terminated
389 * \param[in] cause Cause / reason for termination
390 * \param[in] data Opaqueevent data to be passed to parent
391 */
392void osmo_fsm_inst_term(struct osmo_fsm_inst *fi,
393 enum osmo_fsm_term_cause cause, void *data)
394{
395 struct osmo_fsm_inst *child, *child2;
396 struct osmo_fsm_inst *parent = fi->proc.parent;
397 uint32_t parent_term_event = fi->proc.parent_term_event;
398
399 LOGPFSM(fi, "Terminating (cause = %u)\n", cause);
400
401 /* iterate over all children */
402 llist_for_each_entry_safe(child, child2, &fi->proc.children, proc.child) {
403 /* terminate child */
404 osmo_fsm_inst_term(child, OSMO_FSM_TERM_PARENT, NULL);
405 }
406
407 /* delete ourselves from the parent */
408 llist_del(&fi->proc.child);
409
410 /* call destructor / clean-up function */
411 if (fi->fsm->cleanup)
412 fi->fsm->cleanup(fi, cause);
413
414 LOGPFSM(fi, "Release\n");
415 osmo_fsm_inst_free(fi);
416
417 /* indicate our termination to the parent */
418 if (parent && cause != OSMO_FSM_TERM_PARENT)
419 osmo_fsm_inst_dispatch(parent, parent_term_event, data);
420}
421
422/*! @} */