blob: 666dbe3745483f22024d8a26b6e60aabb02b9b51 [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>
Harald Welte8808bb42017-01-07 11:11:03 +010023#include <string.h>
Harald Welte136e7372016-05-29 10:53:17 +090024
25#include <osmocom/core/fsm.h>
26#include <osmocom/core/talloc.h>
27#include <osmocom/core/logging.h>
28#include <osmocom/core/utils.h>
29
30/*! \addtogroup fsm
31 * @{
32 */
33
34/*! \file fsm.c
35 * \brief Finite State Machine abstraction
36 *
37 * This is a generic C-language abstraction for implementing finite
38 * state machines within the Osmocom framework. It is intended to
39 * replace existing hand-coded or even only implicitly existing FSMs
40 * all over the existing code base.
41 *
42 * An libosmocore FSM is described by its \ref osmo_fsm description,
43 * which in turn refers to an array of \ref osmo_fsm_state descriptor,
44 * each describing a single state in the FSM.
45 *
46 * The general idea is that all actions performed within one state are
47 * located at one position in the code (the state's action function),
48 * as opposed to the 'message-centric' view of e.g. the existing
49 * state machines of the LAPD(m) coe, where there is one message for
50 * eahc possible event (primitive), and the function then needs to
51 * concern itself on how to handle that event over all possible states.
52 *
53 * For each state, there is a bit-mask of permitted input events for
54 * this state, as well as a bit-mask of permitted new output states to
55 * which the state can change. Furthermore, there is a function
56 * pointer implementing the actual handling of the input events
57 * occurring whilst in thta state.
58 *
59 * Furthermore, each state offers a function pointer that can be
60 * executed just before leaving a state, and another one just after
61 * entering a state.
62 *
63 * When transitioning into a new state, an optional timer number and
64 * time-out can be passed along. The timer is started just after
65 * entering the new state, and will call the \ref osmo_fsm timer_cb
66 * function once it expires. This is intended to be used in telecom
67 * state machines where a given timer (identified by a certain number)
68 * is started to terminate the fsm or terminate the fsm once expected
69 * events are not happening before timeout expiration.
70 *
71 * As there can often be many concurrent FSMs of one given class, we
72 * introduce the concept of \ref osmo_fsm_inst, i.e. an FSM instance.
73 * The instance keeps the actual state, while the \ref osmo_fsm
74 * descriptor contains the static/const descriptor of the FSM's states
75 * and possible transitions.
76 *
77 * osmo_fsm are integrated with the libosmocore logging system. The
78 * logging sub-system is determined by the FSM descriptor, as we assume
79 * one FSM (let's say one related to a location update procedure) is
80 * inevitably always tied to a sub-system. The logging level however
81 * is configurable for each FSM instance, to ensure that e.g. DEBUG
82 * logging can be used for the LU procedure of one subscriber, while
83 * NOTICE level is used for all other subscribers.
84 *
85 * In order to attach private state to the \ref osmo_fsm_inst, it
86 * offers an opaque priv pointer.
87 *
88 */
89
90static LLIST_HEAD(g_fsms);
91static bool fsm_log_addr = true;
92
93/*! \brief specify if FSM instance addresses should be logged or not
94 *
95 * By default, the FSM name includes the pointer address of the \ref
Neels Hofmeyra3953e02016-12-14 18:34:30 +010096 * osmo_fsm_inst. This behavior can be disabled (and re-enabled)
Harald Welte136e7372016-05-29 10:53:17 +090097 * using this function.
98 *
99 * \param[in] log_addr Indicate if FSM instance address shall be logged
100 */
101void osmo_fsm_log_addr(bool log_addr)
102{
Max61281f42016-11-01 10:49:31 +0100103 fsm_log_addr = log_addr;
Harald Welte136e7372016-05-29 10:53:17 +0900104}
105
Harald Welte8808bb42017-01-07 11:11:03 +0100106struct osmo_fsm *osmo_fsm_find_by_name(const char *name)
107{
108 struct osmo_fsm *fsm;
109 llist_for_each_entry(fsm, &g_fsms, list) {
110 if (!strcmp(name, fsm->name))
111 return fsm;
112 }
113 return NULL;
114}
115
Harald Welte136e7372016-05-29 10:53:17 +0900116/*! \brief register a FSM with the core
117 *
118 * A FSM descriptor needs to be registered with the core before any
119 * instances can be created for it.
120 *
121 * \param[in] fsm Descriptor of Finite State Machine to be registered
122 * \returns 0 on success; negative on error
123 */
124int osmo_fsm_register(struct osmo_fsm *fsm)
125{
Harald Welte8808bb42017-01-07 11:11:03 +0100126 if (osmo_fsm_find_by_name(fsm->name))
127 return -EEXIST;
Harald Welte136e7372016-05-29 10:53:17 +0900128 llist_add_tail(&fsm->list, &g_fsms);
129 INIT_LLIST_HEAD(&fsm->instances);
130
131 return 0;
132}
133
134/*! \brief unregister a FSM from the core
135 *
136 * Once the FSM descriptor is unregistered, active instances can still
137 * use it, but no new instances may be created for it.
138 *
139 * \param[in] fsm Descriptor of Finite State Machine to be removed
140 */
141void osmo_fsm_unregister(struct osmo_fsm *fsm)
142{
143 llist_del(&fsm->list);
144}
145
146/* small wrapper function around timer expiration (for logging) */
147static void fsm_tmr_cb(void *data)
148{
149 struct osmo_fsm_inst *fi = data;
150 struct osmo_fsm *fsm = fi->fsm;
Harald Weltef627c0f2016-06-18 10:36:25 +0200151 uint32_t T = fi->T;
Harald Welte136e7372016-05-29 10:53:17 +0900152
153 LOGPFSM(fi, "Timeout of T%u\n", fi->T);
154
Harald Weltef627c0f2016-06-18 10:36:25 +0200155 if (fsm->timer_cb) {
156 int rc = fsm->timer_cb(fi);
157 if (rc != 1)
158 return;
159 LOGPFSM(fi, "timer_cb requested termination\n");
160 } else
161 LOGPFSM(fi, "No timer_cb, automatic termination\n");
162
163 /* if timer_cb returns 1 or there is no timer_cb */
164 osmo_fsm_inst_term(fi, OSMO_FSM_TERM_TIMEOUT, &T);
Harald Welte136e7372016-05-29 10:53:17 +0900165}
166
167/*! \brief allocate a new instance of a specified FSM
168 * \param[in] fsm Descriptor of the FSM
169 * \param[in] ctx talloc context from which to allocate memory
170 * \param[in] priv private data reference store in fsm instance
171 * \param[in] log_level The log level for events of this FSM
172 * \returns newly-allocated, initialized and registered FSM instance
173 */
174struct osmo_fsm_inst *osmo_fsm_inst_alloc(struct osmo_fsm *fsm, void *ctx, void *priv,
175 int log_level, const char *id)
176{
177 struct osmo_fsm_inst *fi = talloc_zero(ctx, struct osmo_fsm_inst);
178
179 fi->fsm = fsm;
180 fi->priv = priv;
181 fi->log_level = log_level;
182 fi->timer.data = fi;
183 fi->timer.cb = fsm_tmr_cb;
Harald Weltef3239112016-07-10 15:11:45 +0200184 if (id)
185 fi->id = talloc_strdup(fi, id);
Harald Welte136e7372016-05-29 10:53:17 +0900186
187 if (!fsm_log_addr) {
188 if (id)
189 fi->name = talloc_asprintf(fi, "%s(%s)", fsm->name, id);
190 else
191 fi->name = talloc_asprintf(fi, "%s", fsm->name);
192 } else {
193 if (id)
194 fi->name = talloc_asprintf(fi, "%s(%s)[%p]", fsm->name,
195 id, fi);
196 else
197 fi->name = talloc_asprintf(fi, "%s[%p]", fsm->name, fi);
198 }
199
200 INIT_LLIST_HEAD(&fi->proc.children);
201 INIT_LLIST_HEAD(&fi->proc.child);
202 llist_add(&fi->list, &fsm->instances);
203
204 LOGPFSM(fi, "Allocated\n");
205
206 return fi;
207}
208
209/*! \brief allocate a new instance of a specified FSM as child of
210 * other FSM instance
211 *
212 * This is like \ref osmo_fsm_inst_alloc but using the parent FSM as
213 * talloc context, and inheriting the log level of the parent.
214 *
215 * \param[in] fsm Descriptor of the to-be-allocated FSM
216 * \param[in] parent Parent FSM instance
217 * \param[in] parent_term_event Event to be sent to parent when terminating
218 * \returns newly-allocated, initialized and registered FSM instance
219 */
220struct osmo_fsm_inst *osmo_fsm_inst_alloc_child(struct osmo_fsm *fsm,
221 struct osmo_fsm_inst *parent,
222 uint32_t parent_term_event)
223{
224 struct osmo_fsm_inst *fi;
225
226 fi = osmo_fsm_inst_alloc(fsm, parent, NULL, parent->log_level,
227 parent->id);
228 if (!fi) {
229 /* indicate immediate termination to caller */
230 osmo_fsm_inst_dispatch(parent, parent_term_event, NULL);
231 return NULL;
232 }
233
234 LOGPFSM(fi, "is child of %s\n", osmo_fsm_inst_name(parent));
235
236 fi->proc.parent = parent;
237 fi->proc.parent_term_event = parent_term_event;
238 llist_add(&fi->proc.child, &parent->proc.children);
239
240 return fi;
241}
242
243/*! \brief delete a given instance of a FSM
244 * \param[in] fsm The FSM to be un-registered and deleted
245 */
246void osmo_fsm_inst_free(struct osmo_fsm_inst *fi)
247{
Max3de97e12016-11-02 10:37:58 +0100248 LOGPFSM(fi, "Deallocated\n");
Harald Welte136e7372016-05-29 10:53:17 +0900249 osmo_timer_del(&fi->timer);
250 llist_del(&fi->list);
251 talloc_free(fi);
252}
253
254/*! \brief get human-readable name of FSM event
255 * \param[in] fsm FSM descriptor of event
256 * \param[in] event Event integer value
257 * \returns string rendering of the event
258 */
259const char *osmo_fsm_event_name(struct osmo_fsm *fsm, uint32_t event)
260{
261 static char buf[32];
262 if (!fsm->event_names) {
263 snprintf(buf, sizeof(buf), "%u", event);
264 return buf;
265 } else
266 return get_value_string(fsm->event_names, event);
267}
268
269/*! \brief get human-readable name of FSM instance
270 * \param[in] fi FSM instance
271 * \returns string rendering of the FSM identity
272 */
273const char *osmo_fsm_inst_name(struct osmo_fsm_inst *fi)
274{
275 if (!fi)
276 return "NULL";
277
278 if (fi->name)
279 return fi->name;
280 else
281 return fi->fsm->name;
282}
283
284/*! \brief get human-readable name of FSM instance
285 * \param[in] fsm FSM descriptor
286 * \param[in] state FSM state number
287 * \returns string rendering of the FSM state
288 */
289const char *osmo_fsm_state_name(struct osmo_fsm *fsm, uint32_t state)
290{
291 static char buf[32];
292 if (state >= fsm->num_states) {
293 snprintf(buf, sizeof(buf), "unknown %u", state);
294 return buf;
295 } else
296 return fsm->states[state].name;
297}
298
299/*! \brief perform a state change of the given FSM instance
300 *
Neels Hofmeyr725698a2016-12-14 17:24:54 +0100301 * Best invoke via the osmo_fsm_inst_state_chg() macro which logs the source
302 * file where the state change was effected. Alternatively, you may pass \a
303 * file as NULL to use the normal file/line indication instead.
304 *
Harald Welte136e7372016-05-29 10:53:17 +0900305 * All changes to the FSM instance state must be made via this
306 * function. It verifies that the existing state actually permits a
307 * transiiton to new_state.
308 *
309 * timeout_secs and T are optional parameters, and only have any effect
310 * if timeout_secs is not 0. If the timeout function is used, then the
311 * new_state is entered, and the FSM instances timer is set to expire
312 * in timeout_secs functions. At that time, the FSM's timer_cb
313 * function will be called for handling of the timeout by the user.
314 *
315 * \param[in] fi FSM instance whose state is to change
316 * \param[in] new_state The new state into which we should change
317 * \param[in] timeout_secs Timeout in seconds (if !=0)
318 * \param[in] T Timer number (if \ref timeout_secs != 0)
Neels Hofmeyrb805cc12016-12-23 04:23:18 +0100319 * \param[in] file Calling source file (from osmo_fsm_inst_state_chg macro)
320 * \param[in] line Calling source line (from osmo_fsm_inst_state_chg macro)
Harald Welte136e7372016-05-29 10:53:17 +0900321 * \returns 0 on success; negative on error
322 */
Neels Hofmeyr725698a2016-12-14 17:24:54 +0100323int _osmo_fsm_inst_state_chg(struct osmo_fsm_inst *fi, uint32_t new_state,
324 unsigned long timeout_secs, int T,
325 const char *file, int line)
Harald Welte136e7372016-05-29 10:53:17 +0900326{
327 struct osmo_fsm *fsm = fi->fsm;
328 uint32_t old_state = fi->state;
329 const struct osmo_fsm_state *st = &fsm->states[fi->state];
330
331 /* validate if new_state is a valid state */
332 if (!(st->out_state_mask & (1 << new_state))) {
Neels Hofmeyr725698a2016-12-14 17:24:54 +0100333 LOGPFSMLSRC(fi, LOGL_ERROR, file, line,
334 "transition to state %s not permitted!\n",
335 osmo_fsm_state_name(fsm, new_state));
Harald Welte136e7372016-05-29 10:53:17 +0900336 return -EPERM;
337 }
338
Harald Welte02a66722016-07-10 15:13:51 +0200339 /* delete the old timer */
340 osmo_timer_del(&fi->timer);
341
Harald Welte136e7372016-05-29 10:53:17 +0900342 if (st->onleave)
343 st->onleave(fi, new_state);
344
Neels Hofmeyr725698a2016-12-14 17:24:54 +0100345 LOGPFSMSRC(fi, file, line, "state_chg to %s\n",
346 osmo_fsm_state_name(fsm, new_state));
Harald Welte136e7372016-05-29 10:53:17 +0900347 fi->state = new_state;
Harald Welte460f9ef2016-08-01 00:38:36 +0200348 st = &fsm->states[new_state];
Harald Welte136e7372016-05-29 10:53:17 +0900349
Harald Welte136e7372016-05-29 10:53:17 +0900350 if (timeout_secs) {
Harald Weltef627c0f2016-06-18 10:36:25 +0200351 fi->T = T;
352 osmo_timer_schedule(&fi->timer, timeout_secs, 0);
Harald Welte136e7372016-05-29 10:53:17 +0900353 }
354
Harald Welte673018f2016-07-10 15:09:43 +0200355 /* Call 'onenter' last, user might terminate FSM from there */
356 if (st->onenter)
357 st->onenter(fi, old_state);
358
Harald Welte136e7372016-05-29 10:53:17 +0900359 return 0;
360}
361
362/*! \brief dispatch an event to an osmocom finite state machine instance
363 *
Neels Hofmeyr725698a2016-12-14 17:24:54 +0100364 * Best invoke via the osmo_fsm_inst_dispatch() macro which logs the source
365 * file where the event was effected. Alternatively, you may pass \a file as
366 * NULL to use the normal file/line indication instead.
367 *
Harald Welte136e7372016-05-29 10:53:17 +0900368 * Any incoming events to \ref osmo_fsm instances must be dispatched to
369 * them via this function. It verifies, whether the event is permitted
370 * based on the current state of the FSM. If not, -1 is returned.
371 *
372 * \param[in] fi FSM instance
373 * \param[in] event Event to send to FSM instance
374 * \param[in] data Data to pass along with the event
Neels Hofmeyrb805cc12016-12-23 04:23:18 +0100375 * \param[in] file Calling source file (from osmo_fsm_inst_dispatch macro)
376 * \param[in] line Calling source line (from osmo_fsm_inst_dispatch macro)
Harald Welte136e7372016-05-29 10:53:17 +0900377 * \returns 0 in case of success; negative on error
378 */
Neels Hofmeyr725698a2016-12-14 17:24:54 +0100379int _osmo_fsm_inst_dispatch(struct osmo_fsm_inst *fi, uint32_t event, void *data,
380 const char *file, int line)
Harald Welte136e7372016-05-29 10:53:17 +0900381{
382 struct osmo_fsm *fsm;
383 const struct osmo_fsm_state *fs;
384
385 if (!fi) {
Neels Hofmeyrc7155df2016-12-23 04:24:51 +0100386 LOGPSRC(DLGLOBAL, LOGL_ERROR, file, line,
387 "Trying to dispatch event %u to non-existent"
388 " FSM instance!\n", event);
Harald Welte136e7372016-05-29 10:53:17 +0900389 osmo_log_backtrace(DLGLOBAL, LOGL_ERROR);
390 return -ENODEV;
391 }
392
393 fsm = fi->fsm;
394 OSMO_ASSERT(fi->state < fsm->num_states);
395 fs = &fi->fsm->states[fi->state];
396
Neels Hofmeyr725698a2016-12-14 17:24:54 +0100397 LOGPFSMSRC(fi, file, line,
398 "Received Event %s\n", osmo_fsm_event_name(fsm, event));
Harald Welte136e7372016-05-29 10:53:17 +0900399
400 if (((1 << event) & fsm->allstate_event_mask) && fsm->allstate_action) {
401 fsm->allstate_action(fi, event, data);
402 return 0;
403 }
404
405 if (!((1 << event) & fs->in_event_mask)) {
Neels Hofmeyr725698a2016-12-14 17:24:54 +0100406 LOGPFSMLSRC(fi, LOGL_ERROR, file, line,
407 "Event %s not permitted\n",
408 osmo_fsm_event_name(fsm, event));
Harald Welte136e7372016-05-29 10:53:17 +0900409 return -1;
410 }
411 fs->action(fi, event, data);
412
413 return 0;
414}
415
416/*! \brief Terminate FSM instance with given cause
417 *
418 * This safely terminates the given FSM instance by first iterating
419 * over all children and sending them a termination event. Next, it
420 * calls the FSM descriptors cleanup function (if any), followed by
421 * releasing any memory associated with the FSM instance.
422 *
423 * Finally, the parent FSM instance (if any) is notified using the
424 * parent termination event configured at time of FSM instance start.
425 *
426 * \param[in] fi FSM instance to be terminated
427 * \param[in] cause Cause / reason for termination
Neels Hofmeyrb805cc12016-12-23 04:23:18 +0100428 * \param[in] data Opaque event data to be passed with the parent term event
429 * \param[in] file Calling source file (from osmo_fsm_inst_term macro)
430 * \param[in] line Calling source line (from osmo_fsm_inst_term macro)
Harald Welte136e7372016-05-29 10:53:17 +0900431 */
Neels Hofmeyr725698a2016-12-14 17:24:54 +0100432void _osmo_fsm_inst_term(struct osmo_fsm_inst *fi,
433 enum osmo_fsm_term_cause cause, void *data,
434 const char *file, int line)
Harald Welte136e7372016-05-29 10:53:17 +0900435{
Neels Hofmeyr3faa0142016-12-18 23:41:41 +0100436 struct osmo_fsm_inst *parent;
Harald Welte136e7372016-05-29 10:53:17 +0900437 uint32_t parent_term_event = fi->proc.parent_term_event;
438
Neels Hofmeyr5c5c78a2016-12-14 18:35:47 +0100439 LOGPFSMSRC(fi, file, line, "Terminating (cause = %s)\n",
440 osmo_fsm_term_cause_name(cause));
Harald Welte136e7372016-05-29 10:53:17 +0900441
Neels Hofmeyrc014f602016-12-23 04:26:39 +0100442 _osmo_fsm_inst_term_children(fi, OSMO_FSM_TERM_PARENT, NULL,
443 file, line);
444
445 /* delete ourselves from the parent */
Neels Hofmeyr3faa0142016-12-18 23:41:41 +0100446 parent = fi->proc.parent;
Neels Hofmeyrc014f602016-12-23 04:26:39 +0100447 if (parent)
448 LOGPFSMSRC(fi, file, line, "Removing from parent %s\n",
449 osmo_fsm_inst_name(parent));
450 llist_del(&fi->proc.child);
451
452 /* call destructor / clean-up function */
453 if (fi->fsm->cleanup)
454 fi->fsm->cleanup(fi, cause);
455
456 LOGPFSMSRC(fi, file, line, "Freeing instance\n");
Neels Hofmeyr3faa0142016-12-18 23:41:41 +0100457 /* Fetch parent again in case it has changed. */
458 parent = fi->proc.parent;
Neels Hofmeyrc014f602016-12-23 04:26:39 +0100459 osmo_fsm_inst_free(fi);
460
461 /* indicate our termination to the parent */
462 if (parent && cause != OSMO_FSM_TERM_PARENT)
463 _osmo_fsm_inst_dispatch(parent, parent_term_event, data,
464 file, line);
465}
466
467/*! \brief Terminate all child FSM instances of an FSM instance.
468 *
469 * Iterate over all children and send them a termination event, with the given
470 * cause. Pass OSMO_FSM_TERM_PARENT to avoid dispatching events from the
471 * terminated child FSMs.
472 *
473 * \param[in] fi FSM instance that should be cleared of child FSMs
474 * \param[in] cause Cause / reason for termination (OSMO_FSM_TERM_PARENT)
475 * \param[in] data Opaque event data to be passed with the parent term events
476 * \param[in] file Calling source file (from osmo_fsm_inst_term_children macro)
477 * \param[in] line Calling source line (from osmo_fsm_inst_term_children macro)
478 */
479void _osmo_fsm_inst_term_children(struct osmo_fsm_inst *fi,
480 enum osmo_fsm_term_cause cause,
481 void *data,
482 const char *file, int line)
483{
484 struct osmo_fsm_inst *first_child, *last_seen_first_child;
485
Neels Hofmeyr06ac9b42016-12-20 12:05:19 +0100486 /* iterate over all children, starting from the beginning every time:
487 * terminating an FSM may emit events that cause other FSMs to also
488 * terminate and remove themselves from this list. */
489 last_seen_first_child = NULL;
490 while (!llist_empty(&fi->proc.children)) {
491 first_child = llist_entry(fi->proc.children.next,
492 typeof(*first_child),
493 proc.child);
494
495 /* paranoia: do not loop forever */
496 if (first_child == last_seen_first_child) {
497 LOGPFSMLSRC(fi, LOGL_ERROR, file, line,
498 "Internal error while terminating child"
499 " FSMs: a child FSM is stuck\n");
500 break;
501 }
502 last_seen_first_child = first_child;
503
Harald Welte136e7372016-05-29 10:53:17 +0900504 /* terminate child */
Neels Hofmeyrc014f602016-12-23 04:26:39 +0100505 _osmo_fsm_inst_term(first_child, cause, data,
Neels Hofmeyr725698a2016-12-14 17:24:54 +0100506 file, line);
Harald Welte136e7372016-05-29 10:53:17 +0900507 }
Harald Welte136e7372016-05-29 10:53:17 +0900508}
509
Neels Hofmeyr5c5c78a2016-12-14 18:35:47 +0100510const struct value_string osmo_fsm_term_cause_names[] = {
Neels Hofmeyr18080962016-12-16 13:43:54 +0100511 OSMO_VALUE_STRING(OSMO_FSM_TERM_PARENT),
512 OSMO_VALUE_STRING(OSMO_FSM_TERM_REQUEST),
513 OSMO_VALUE_STRING(OSMO_FSM_TERM_REGULAR),
514 OSMO_VALUE_STRING(OSMO_FSM_TERM_ERROR),
515 OSMO_VALUE_STRING(OSMO_FSM_TERM_TIMEOUT),
Neels Hofmeyr5c5c78a2016-12-14 18:35:47 +0100516 { 0, NULL }
517};
518
Harald Welte136e7372016-05-29 10:53:17 +0900519/*! @} */