blob: 5c47a4452b82bee4ffb18ca58d0bf87efb386df9 [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
Neels Hofmeyra3953e02016-12-14 18:34:30 +010095 * osmo_fsm_inst. This behavior can be disabled (and re-enabled)
Harald Welte136e7372016-05-29 10:53:17 +090096 * 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{
Max61281f42016-11-01 10:49:31 +0100102 fsm_log_addr = log_addr;
Harald Welte136e7372016-05-29 10:53:17 +0900103}
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;
Harald Weltef627c0f2016-06-18 10:36:25 +0200139 uint32_t T = fi->T;
Harald Welte136e7372016-05-29 10:53:17 +0900140
141 LOGPFSM(fi, "Timeout of T%u\n", fi->T);
142
Harald Weltef627c0f2016-06-18 10:36:25 +0200143 if (fsm->timer_cb) {
144 int rc = fsm->timer_cb(fi);
145 if (rc != 1)
146 return;
147 LOGPFSM(fi, "timer_cb requested termination\n");
148 } else
149 LOGPFSM(fi, "No timer_cb, automatic termination\n");
150
151 /* if timer_cb returns 1 or there is no timer_cb */
152 osmo_fsm_inst_term(fi, OSMO_FSM_TERM_TIMEOUT, &T);
Harald Welte136e7372016-05-29 10:53:17 +0900153}
154
155/*! \brief allocate a new instance of a specified FSM
156 * \param[in] fsm Descriptor of the FSM
157 * \param[in] ctx talloc context from which to allocate memory
158 * \param[in] priv private data reference store in fsm instance
159 * \param[in] log_level The log level for events of this FSM
160 * \returns newly-allocated, initialized and registered FSM instance
161 */
162struct osmo_fsm_inst *osmo_fsm_inst_alloc(struct osmo_fsm *fsm, void *ctx, void *priv,
163 int log_level, const char *id)
164{
165 struct osmo_fsm_inst *fi = talloc_zero(ctx, struct osmo_fsm_inst);
166
167 fi->fsm = fsm;
168 fi->priv = priv;
169 fi->log_level = log_level;
170 fi->timer.data = fi;
171 fi->timer.cb = fsm_tmr_cb;
Harald Weltef3239112016-07-10 15:11:45 +0200172 if (id)
173 fi->id = talloc_strdup(fi, id);
Harald Welte136e7372016-05-29 10:53:17 +0900174
175 if (!fsm_log_addr) {
176 if (id)
177 fi->name = talloc_asprintf(fi, "%s(%s)", fsm->name, id);
178 else
179 fi->name = talloc_asprintf(fi, "%s", fsm->name);
180 } else {
181 if (id)
182 fi->name = talloc_asprintf(fi, "%s(%s)[%p]", fsm->name,
183 id, fi);
184 else
185 fi->name = talloc_asprintf(fi, "%s[%p]", fsm->name, fi);
186 }
187
188 INIT_LLIST_HEAD(&fi->proc.children);
189 INIT_LLIST_HEAD(&fi->proc.child);
190 llist_add(&fi->list, &fsm->instances);
191
192 LOGPFSM(fi, "Allocated\n");
193
194 return fi;
195}
196
197/*! \brief allocate a new instance of a specified FSM as child of
198 * other FSM instance
199 *
200 * This is like \ref osmo_fsm_inst_alloc but using the parent FSM as
201 * talloc context, and inheriting the log level of the parent.
202 *
203 * \param[in] fsm Descriptor of the to-be-allocated FSM
204 * \param[in] parent Parent FSM instance
205 * \param[in] parent_term_event Event to be sent to parent when terminating
206 * \returns newly-allocated, initialized and registered FSM instance
207 */
208struct osmo_fsm_inst *osmo_fsm_inst_alloc_child(struct osmo_fsm *fsm,
209 struct osmo_fsm_inst *parent,
210 uint32_t parent_term_event)
211{
212 struct osmo_fsm_inst *fi;
213
214 fi = osmo_fsm_inst_alloc(fsm, parent, NULL, parent->log_level,
215 parent->id);
216 if (!fi) {
217 /* indicate immediate termination to caller */
218 osmo_fsm_inst_dispatch(parent, parent_term_event, NULL);
219 return NULL;
220 }
221
222 LOGPFSM(fi, "is child of %s\n", osmo_fsm_inst_name(parent));
223
224 fi->proc.parent = parent;
225 fi->proc.parent_term_event = parent_term_event;
226 llist_add(&fi->proc.child, &parent->proc.children);
227
228 return fi;
229}
230
231/*! \brief delete a given instance of a FSM
232 * \param[in] fsm The FSM to be un-registered and deleted
233 */
234void osmo_fsm_inst_free(struct osmo_fsm_inst *fi)
235{
Max3de97e12016-11-02 10:37:58 +0100236 LOGPFSM(fi, "Deallocated\n");
Harald Welte136e7372016-05-29 10:53:17 +0900237 osmo_timer_del(&fi->timer);
238 llist_del(&fi->list);
239 talloc_free(fi);
240}
241
242/*! \brief get human-readable name of FSM event
243 * \param[in] fsm FSM descriptor of event
244 * \param[in] event Event integer value
245 * \returns string rendering of the event
246 */
247const char *osmo_fsm_event_name(struct osmo_fsm *fsm, uint32_t event)
248{
249 static char buf[32];
250 if (!fsm->event_names) {
251 snprintf(buf, sizeof(buf), "%u", event);
252 return buf;
253 } else
254 return get_value_string(fsm->event_names, event);
255}
256
257/*! \brief get human-readable name of FSM instance
258 * \param[in] fi FSM instance
259 * \returns string rendering of the FSM identity
260 */
261const char *osmo_fsm_inst_name(struct osmo_fsm_inst *fi)
262{
263 if (!fi)
264 return "NULL";
265
266 if (fi->name)
267 return fi->name;
268 else
269 return fi->fsm->name;
270}
271
272/*! \brief get human-readable name of FSM instance
273 * \param[in] fsm FSM descriptor
274 * \param[in] state FSM state number
275 * \returns string rendering of the FSM state
276 */
277const char *osmo_fsm_state_name(struct osmo_fsm *fsm, uint32_t state)
278{
279 static char buf[32];
280 if (state >= fsm->num_states) {
281 snprintf(buf, sizeof(buf), "unknown %u", state);
282 return buf;
283 } else
284 return fsm->states[state].name;
285}
286
287/*! \brief perform a state change of the given FSM instance
288 *
Neels Hofmeyr725698a2016-12-14 17:24:54 +0100289 * Best invoke via the osmo_fsm_inst_state_chg() macro which logs the source
290 * file where the state change was effected. Alternatively, you may pass \a
291 * file as NULL to use the normal file/line indication instead.
292 *
Harald Welte136e7372016-05-29 10:53:17 +0900293 * All changes to the FSM instance state must be made via this
294 * function. It verifies that the existing state actually permits a
295 * transiiton to new_state.
296 *
297 * timeout_secs and T are optional parameters, and only have any effect
298 * if timeout_secs is not 0. If the timeout function is used, then the
299 * new_state is entered, and the FSM instances timer is set to expire
300 * in timeout_secs functions. At that time, the FSM's timer_cb
301 * function will be called for handling of the timeout by the user.
302 *
303 * \param[in] fi FSM instance whose state is to change
304 * \param[in] new_state The new state into which we should change
305 * \param[in] timeout_secs Timeout in seconds (if !=0)
306 * \param[in] T Timer number (if \ref timeout_secs != 0)
Neels Hofmeyrb805cc12016-12-23 04:23:18 +0100307 * \param[in] file Calling source file (from osmo_fsm_inst_state_chg macro)
308 * \param[in] line Calling source line (from osmo_fsm_inst_state_chg macro)
Harald Welte136e7372016-05-29 10:53:17 +0900309 * \returns 0 on success; negative on error
310 */
Neels Hofmeyr725698a2016-12-14 17:24:54 +0100311int _osmo_fsm_inst_state_chg(struct osmo_fsm_inst *fi, uint32_t new_state,
312 unsigned long timeout_secs, int T,
313 const char *file, int line)
Harald Welte136e7372016-05-29 10:53:17 +0900314{
315 struct osmo_fsm *fsm = fi->fsm;
316 uint32_t old_state = fi->state;
317 const struct osmo_fsm_state *st = &fsm->states[fi->state];
318
319 /* validate if new_state is a valid state */
320 if (!(st->out_state_mask & (1 << new_state))) {
Neels Hofmeyr725698a2016-12-14 17:24:54 +0100321 LOGPFSMLSRC(fi, LOGL_ERROR, file, line,
322 "transition to state %s not permitted!\n",
323 osmo_fsm_state_name(fsm, new_state));
Harald Welte136e7372016-05-29 10:53:17 +0900324 return -EPERM;
325 }
326
Harald Welte02a66722016-07-10 15:13:51 +0200327 /* delete the old timer */
328 osmo_timer_del(&fi->timer);
329
Harald Welte136e7372016-05-29 10:53:17 +0900330 if (st->onleave)
331 st->onleave(fi, new_state);
332
Neels Hofmeyr725698a2016-12-14 17:24:54 +0100333 LOGPFSMSRC(fi, file, line, "state_chg to %s\n",
334 osmo_fsm_state_name(fsm, new_state));
Harald Welte136e7372016-05-29 10:53:17 +0900335 fi->state = new_state;
Harald Welte460f9ef2016-08-01 00:38:36 +0200336 st = &fsm->states[new_state];
Harald Welte136e7372016-05-29 10:53:17 +0900337
Harald Welte136e7372016-05-29 10:53:17 +0900338 if (timeout_secs) {
Harald Weltef627c0f2016-06-18 10:36:25 +0200339 fi->T = T;
340 osmo_timer_schedule(&fi->timer, timeout_secs, 0);
Harald Welte136e7372016-05-29 10:53:17 +0900341 }
342
Harald Welte673018f2016-07-10 15:09:43 +0200343 /* Call 'onenter' last, user might terminate FSM from there */
344 if (st->onenter)
345 st->onenter(fi, old_state);
346
Harald Welte136e7372016-05-29 10:53:17 +0900347 return 0;
348}
349
350/*! \brief dispatch an event to an osmocom finite state machine instance
351 *
Neels Hofmeyr725698a2016-12-14 17:24:54 +0100352 * Best invoke via the osmo_fsm_inst_dispatch() macro which logs the source
353 * file where the event was effected. Alternatively, you may pass \a file as
354 * NULL to use the normal file/line indication instead.
355 *
Harald Welte136e7372016-05-29 10:53:17 +0900356 * Any incoming events to \ref osmo_fsm instances must be dispatched to
357 * them via this function. It verifies, whether the event is permitted
358 * based on the current state of the FSM. If not, -1 is returned.
359 *
360 * \param[in] fi FSM instance
361 * \param[in] event Event to send to FSM instance
362 * \param[in] data Data to pass along with the event
Neels Hofmeyrb805cc12016-12-23 04:23:18 +0100363 * \param[in] file Calling source file (from osmo_fsm_inst_dispatch macro)
364 * \param[in] line Calling source line (from osmo_fsm_inst_dispatch macro)
Harald Welte136e7372016-05-29 10:53:17 +0900365 * \returns 0 in case of success; negative on error
366 */
Neels Hofmeyr725698a2016-12-14 17:24:54 +0100367int _osmo_fsm_inst_dispatch(struct osmo_fsm_inst *fi, uint32_t event, void *data,
368 const char *file, int line)
Harald Welte136e7372016-05-29 10:53:17 +0900369{
370 struct osmo_fsm *fsm;
371 const struct osmo_fsm_state *fs;
372
373 if (!fi) {
Neels Hofmeyrc7155df2016-12-23 04:24:51 +0100374 LOGPSRC(DLGLOBAL, LOGL_ERROR, file, line,
375 "Trying to dispatch event %u to non-existent"
376 " FSM instance!\n", event);
Harald Welte136e7372016-05-29 10:53:17 +0900377 osmo_log_backtrace(DLGLOBAL, LOGL_ERROR);
378 return -ENODEV;
379 }
380
381 fsm = fi->fsm;
382 OSMO_ASSERT(fi->state < fsm->num_states);
383 fs = &fi->fsm->states[fi->state];
384
Neels Hofmeyr725698a2016-12-14 17:24:54 +0100385 LOGPFSMSRC(fi, file, line,
386 "Received Event %s\n", osmo_fsm_event_name(fsm, event));
Harald Welte136e7372016-05-29 10:53:17 +0900387
388 if (((1 << event) & fsm->allstate_event_mask) && fsm->allstate_action) {
389 fsm->allstate_action(fi, event, data);
390 return 0;
391 }
392
393 if (!((1 << event) & fs->in_event_mask)) {
Neels Hofmeyr725698a2016-12-14 17:24:54 +0100394 LOGPFSMLSRC(fi, LOGL_ERROR, file, line,
395 "Event %s not permitted\n",
396 osmo_fsm_event_name(fsm, event));
Harald Welte136e7372016-05-29 10:53:17 +0900397 return -1;
398 }
399 fs->action(fi, event, data);
400
401 return 0;
402}
403
404/*! \brief Terminate FSM instance with given cause
405 *
406 * This safely terminates the given FSM instance by first iterating
407 * over all children and sending them a termination event. Next, it
408 * calls the FSM descriptors cleanup function (if any), followed by
409 * releasing any memory associated with the FSM instance.
410 *
411 * Finally, the parent FSM instance (if any) is notified using the
412 * parent termination event configured at time of FSM instance start.
413 *
414 * \param[in] fi FSM instance to be terminated
415 * \param[in] cause Cause / reason for termination
Neels Hofmeyrb805cc12016-12-23 04:23:18 +0100416 * \param[in] data Opaque event data to be passed with the parent term event
417 * \param[in] file Calling source file (from osmo_fsm_inst_term macro)
418 * \param[in] line Calling source line (from osmo_fsm_inst_term macro)
Harald Welte136e7372016-05-29 10:53:17 +0900419 */
Neels Hofmeyr725698a2016-12-14 17:24:54 +0100420void _osmo_fsm_inst_term(struct osmo_fsm_inst *fi,
421 enum osmo_fsm_term_cause cause, void *data,
422 const char *file, int line)
Harald Welte136e7372016-05-29 10:53:17 +0900423{
Harald Welte136e7372016-05-29 10:53:17 +0900424 struct osmo_fsm_inst *parent = fi->proc.parent;
425 uint32_t parent_term_event = fi->proc.parent_term_event;
426
Neels Hofmeyr5c5c78a2016-12-14 18:35:47 +0100427 LOGPFSMSRC(fi, file, line, "Terminating (cause = %s)\n",
428 osmo_fsm_term_cause_name(cause));
Harald Welte136e7372016-05-29 10:53:17 +0900429
Neels Hofmeyrc014f602016-12-23 04:26:39 +0100430 _osmo_fsm_inst_term_children(fi, OSMO_FSM_TERM_PARENT, NULL,
431 file, line);
432
433 /* delete ourselves from the parent */
434 if (parent)
435 LOGPFSMSRC(fi, file, line, "Removing from parent %s\n",
436 osmo_fsm_inst_name(parent));
437 llist_del(&fi->proc.child);
438
439 /* call destructor / clean-up function */
440 if (fi->fsm->cleanup)
441 fi->fsm->cleanup(fi, cause);
442
443 LOGPFSMSRC(fi, file, line, "Freeing instance\n");
444 osmo_fsm_inst_free(fi);
445
446 /* indicate our termination to the parent */
447 if (parent && cause != OSMO_FSM_TERM_PARENT)
448 _osmo_fsm_inst_dispatch(parent, parent_term_event, data,
449 file, line);
450}
451
452/*! \brief Terminate all child FSM instances of an FSM instance.
453 *
454 * Iterate over all children and send them a termination event, with the given
455 * cause. Pass OSMO_FSM_TERM_PARENT to avoid dispatching events from the
456 * terminated child FSMs.
457 *
458 * \param[in] fi FSM instance that should be cleared of child FSMs
459 * \param[in] cause Cause / reason for termination (OSMO_FSM_TERM_PARENT)
460 * \param[in] data Opaque event data to be passed with the parent term events
461 * \param[in] file Calling source file (from osmo_fsm_inst_term_children macro)
462 * \param[in] line Calling source line (from osmo_fsm_inst_term_children macro)
463 */
464void _osmo_fsm_inst_term_children(struct osmo_fsm_inst *fi,
465 enum osmo_fsm_term_cause cause,
466 void *data,
467 const char *file, int line)
468{
469 struct osmo_fsm_inst *first_child, *last_seen_first_child;
470
Neels Hofmeyr06ac9b42016-12-20 12:05:19 +0100471 /* iterate over all children, starting from the beginning every time:
472 * terminating an FSM may emit events that cause other FSMs to also
473 * terminate and remove themselves from this list. */
474 last_seen_first_child = NULL;
475 while (!llist_empty(&fi->proc.children)) {
476 first_child = llist_entry(fi->proc.children.next,
477 typeof(*first_child),
478 proc.child);
479
480 /* paranoia: do not loop forever */
481 if (first_child == last_seen_first_child) {
482 LOGPFSMLSRC(fi, LOGL_ERROR, file, line,
483 "Internal error while terminating child"
484 " FSMs: a child FSM is stuck\n");
485 break;
486 }
487 last_seen_first_child = first_child;
488
Harald Welte136e7372016-05-29 10:53:17 +0900489 /* terminate child */
Neels Hofmeyrc014f602016-12-23 04:26:39 +0100490 _osmo_fsm_inst_term(first_child, cause, data,
Neels Hofmeyr725698a2016-12-14 17:24:54 +0100491 file, line);
Harald Welte136e7372016-05-29 10:53:17 +0900492 }
Harald Welte136e7372016-05-29 10:53:17 +0900493}
494
Neels Hofmeyr5c5c78a2016-12-14 18:35:47 +0100495const struct value_string osmo_fsm_term_cause_names[] = {
Neels Hofmeyr18080962016-12-16 13:43:54 +0100496 OSMO_VALUE_STRING(OSMO_FSM_TERM_PARENT),
497 OSMO_VALUE_STRING(OSMO_FSM_TERM_REQUEST),
498 OSMO_VALUE_STRING(OSMO_FSM_TERM_REGULAR),
499 OSMO_VALUE_STRING(OSMO_FSM_TERM_ERROR),
500 OSMO_VALUE_STRING(OSMO_FSM_TERM_TIMEOUT),
Neels Hofmeyr5c5c78a2016-12-14 18:35:47 +0100501 { 0, NULL }
502};
503
Harald Welte136e7372016-05-29 10:53:17 +0900504/*! @} */