blob: f1dbb412030585562f5fa543b4c56710ca9be7dc [file] [log] [blame]
Neels Hofmeyr17518fe2017-06-20 04:35:06 +02001/*! \file fsm.c
2 * Osmocom generic Finite State Machine implementation. */
3/*
Harald Welte7b745512019-05-18 21:03:55 +02004 * (C) 2016-2019 by Harald Welte <laforge@gnumonks.org>
Harald Welte136e7372016-05-29 10:53:17 +09005 *
Harald Weltee08da972017-11-13 01:00:26 +09006 * SPDX-License-Identifier: GPL-2.0+
7 *
Harald Welte136e7372016-05-29 10:53:17 +09008 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
21 * MA 02110-1301, USA.
22 */
23
24#include <errno.h>
25#include <stdbool.h>
Harald Welte8808bb42017-01-07 11:11:03 +010026#include <string.h>
Pau Espin Pedrol4f8857e2017-06-18 12:23:00 +020027#include <inttypes.h>
Harald Welte136e7372016-05-29 10:53:17 +090028
29#include <osmocom/core/fsm.h>
30#include <osmocom/core/talloc.h>
31#include <osmocom/core/logging.h>
32#include <osmocom/core/utils.h>
33
34/*! \addtogroup fsm
35 * @{
Neels Hofmeyr87e45502017-06-20 00:17:59 +020036 * Finite State Machine abstraction
Harald Welte136e7372016-05-29 10:53:17 +090037 *
38 * This is a generic C-language abstraction for implementing finite
39 * state machines within the Osmocom framework. It is intended to
40 * replace existing hand-coded or even only implicitly existing FSMs
41 * all over the existing code base.
42 *
43 * An libosmocore FSM is described by its \ref osmo_fsm description,
44 * which in turn refers to an array of \ref osmo_fsm_state descriptor,
45 * each describing a single state in the FSM.
46 *
47 * The general idea is that all actions performed within one state are
48 * located at one position in the code (the state's action function),
49 * as opposed to the 'message-centric' view of e.g. the existing
Kévin Redonc9a28a62019-05-09 18:31:13 +020050 * state machines of the LAPD(m) core, where there is one message for
51 * each possible event (primitive), and the function then needs to
Harald Welte136e7372016-05-29 10:53:17 +090052 * concern itself on how to handle that event over all possible states.
53 *
54 * For each state, there is a bit-mask of permitted input events for
55 * this state, as well as a bit-mask of permitted new output states to
56 * which the state can change. Furthermore, there is a function
57 * pointer implementing the actual handling of the input events
Kévin Redonc9a28a62019-05-09 18:31:13 +020058 * occurring whilst in that state.
Harald Welte136e7372016-05-29 10:53:17 +090059 *
60 * Furthermore, each state offers a function pointer that can be
61 * executed just before leaving a state, and another one just after
62 * entering a state.
63 *
64 * When transitioning into a new state, an optional timer number and
65 * time-out can be passed along. The timer is started just after
66 * entering the new state, and will call the \ref osmo_fsm timer_cb
67 * function once it expires. This is intended to be used in telecom
68 * state machines where a given timer (identified by a certain number)
69 * is started to terminate the fsm or terminate the fsm once expected
70 * events are not happening before timeout expiration.
71 *
72 * As there can often be many concurrent FSMs of one given class, we
73 * introduce the concept of \ref osmo_fsm_inst, i.e. an FSM instance.
74 * The instance keeps the actual state, while the \ref osmo_fsm
75 * descriptor contains the static/const descriptor of the FSM's states
76 * and possible transitions.
77 *
78 * osmo_fsm are integrated with the libosmocore logging system. The
79 * logging sub-system is determined by the FSM descriptor, as we assume
80 * one FSM (let's say one related to a location update procedure) is
81 * inevitably always tied to a sub-system. The logging level however
82 * is configurable for each FSM instance, to ensure that e.g. DEBUG
83 * logging can be used for the LU procedure of one subscriber, while
84 * NOTICE level is used for all other subscribers.
85 *
86 * In order to attach private state to the \ref osmo_fsm_inst, it
Kévin Redonc9a28a62019-05-09 18:31:13 +020087 * offers an opaque private pointer.
Neels Hofmeyr17518fe2017-06-20 04:35:06 +020088 *
89 * \file fsm.c */
Harald Welte96e2a002017-06-12 21:44:18 +020090
Harald Welte34193912017-01-07 11:49:55 +010091LLIST_HEAD(osmo_g_fsms);
Harald Welte136e7372016-05-29 10:53:17 +090092static bool fsm_log_addr = true;
Neels Hofmeyr050f2d32018-05-31 15:30:15 +020093static bool fsm_log_timeouts = false;
Neels Hofmeyr1f9cc012019-03-24 05:56:21 +010094/*! See osmo_fsm_term_safely(). */
95static bool fsm_term_safely_enabled = false;
96
97/*! Internal state for FSM instance termination cascades. */
98static __thread struct {
99 /*! The first FSM instance that invoked osmo_fsm_inst_term() in the current cascade. */
100 struct osmo_fsm_inst *root_fi;
101 /*! 2 if a secondary FSM terminates, 3 if a secondary FSM causes a tertiary FSM to terminate, and so on. */
102 unsigned int depth;
103 /*! Talloc context to collect all deferred deallocations (FSM instances, and talloc objects if any). */
104 void *collect_ctx;
Neels Hofmeyr988f6d72019-10-04 20:37:17 +0200105 /*! See osmo_fsm_set_dealloc_ctx() */
106 void *fsm_dealloc_ctx;
Neels Hofmeyr1f9cc012019-03-24 05:56:21 +0100107} fsm_term_safely;
Harald Welte136e7372016-05-29 10:53:17 +0900108
Neels Hofmeyr988f6d72019-10-04 20:37:17 +0200109/*! Internal call to free an FSM instance, which redirects to the context set by osmo_fsm_set_dealloc_ctx() if any.
110 */
111static void fsm_free_or_steal(void *talloc_object)
112{
113 if (fsm_term_safely.fsm_dealloc_ctx)
114 talloc_steal(fsm_term_safely.fsm_dealloc_ctx, talloc_object);
115 else
116 talloc_free(talloc_object);
117}
118
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200119/*! specify if FSM instance addresses should be logged or not
Harald Welte136e7372016-05-29 10:53:17 +0900120 *
121 * By default, the FSM name includes the pointer address of the \ref
Neels Hofmeyra3953e02016-12-14 18:34:30 +0100122 * osmo_fsm_inst. This behavior can be disabled (and re-enabled)
Harald Welte136e7372016-05-29 10:53:17 +0900123 * using this function.
124 *
125 * \param[in] log_addr Indicate if FSM instance address shall be logged
126 */
127void osmo_fsm_log_addr(bool log_addr)
128{
Max61281f42016-11-01 10:49:31 +0100129 fsm_log_addr = log_addr;
Harald Welte136e7372016-05-29 10:53:17 +0900130}
131
Neels Hofmeyr050f2d32018-05-31 15:30:15 +0200132/*! Enable or disable logging of timeout values for FSM instance state changes.
133 *
134 * By default, state changes are logged by state name only, omitting the timeout. When passing true, each state change
Neels Hofmeyr5734bff2019-02-21 02:27:48 +0100135 * will also log the T number (or Osmocom-specific X number) and the chosen timeout in seconds.
136 * osmo_fsm_inst_state_chg_keep_timer() will log remaining timeout in millisecond precision.
Neels Hofmeyr050f2d32018-05-31 15:30:15 +0200137 *
138 * The default for this is false to reflect legacy behavior. Since various C tests that verify logging output already
139 * existed prior to this option, keeping timeout logging off makes sure that they continue to pass. Particularly,
140 * osmo_fsm_inst_state_chg_keep_timer() may cause non-deterministic logging of remaining timeout values.
141 *
142 * For any program that does not explicitly require deterministic logging output, i.e. anything besides regression tests
143 * involving FSM instances, it is recommended to call osmo_fsm_log_timeouts(true).
144 *
145 * \param[in] log_timeouts Pass true to log timeouts on state transitions, false to omit timeouts.
146 */
147void osmo_fsm_log_timeouts(bool log_timeouts)
148{
149 fsm_log_timeouts = log_timeouts;
150}
151
Neels Hofmeyr1f9cc012019-03-24 05:56:21 +0100152/*! Enable safer way to deallocate cascades of terminating FSM instances.
153 *
Neels Hofmeyr988f6d72019-10-04 20:37:17 +0200154 * Note, using osmo_fsm_set_dealloc_ctx() is a more general solution to this same problem.
155 * Particularly, in a program using osmo_select_main_ctx(), the simplest solution to avoid most use-after-free problems
156 * from FSM instance deallocation is using osmo_fsm_set_dealloc_ctx(OTC_SELECT).
Neels Hofmeyr1f9cc012019-03-24 05:56:21 +0100157 *
158 * When enabled, an FSM instance termination detects whether another FSM instance is already terminating, and instead of
159 * deallocating immediately, collects all terminating FSM instances in a talloc context, to be bulk deallocated once all
160 * event handling and termination cascades are done.
161 *
162 * For example, if an FSM's cleanup() sends an event to some "other" FSM, which in turn causes the FSM's parent to
163 * deallocate, then the parent would talloc_free() the child's memory, causing a use-after-free. There are infinite
164 * constellations like this, which all are trivially solved with this feature enabled.
165 *
166 * For illustration, see fsm_dealloc_test.c.
167 *
Neels Hofmeyr988f6d72019-10-04 20:37:17 +0200168 * When enabled, this feature changes the order of logging, which may break legacy unit test expectations, and changes
169 * the order of deallocation to after the parent term event is dispatched.
170 *
Neels Hofmeyr1f9cc012019-03-24 05:56:21 +0100171 * \param[in] term_safely Pass true to switch to safer FSM instance termination behavior.
172 */
173void osmo_fsm_term_safely(bool term_safely)
174{
175 fsm_term_safely_enabled = term_safely;
176}
177
Neels Hofmeyr988f6d72019-10-04 20:37:17 +0200178/*! Instead of deallocating FSM instances, move them to the given talloc context.
179 *
180 * It is the caller's responsibility to clear this context to actually free the memory of terminated FSM instances.
181 * Make sure to not talloc_free(ctx) itself before setting a different osmo_fsm_set_dealloc_ctx(). To clear a ctx
182 * without the need to call osmo_fsm_set_dealloc_ctx() again, rather use talloc_free_children(ctx).
183 *
184 * For example, to defer deallocation to the next osmo_select_main_ctx() iteration, set this to OTC_SELECT.
185 *
186 * Deferring deallocation is the simplest solution to avoid most use-after-free problems from FSM instance deallocation.
187 * This is a simpler and more general solution than osmo_fsm_term_safely().
188 *
189 * To disable the feature again, pass NULL as ctx.
190 *
191 * Both osmo_fsm_term_safely() and osmo_fsm_set_dealloc_ctx() can be enabled at the same time, which will result in
192 * first collecting deallocated FSM instances in fsm_term_safely.collect_ctx, and finally reparenting that to the ctx
193 * passed here. However, in practice, it does not really make sense to enable both at the same time.
194 *
195 * \param ctx[in] Instead of talloc_free()int, talloc_steal() all future deallocated osmo_fsm_inst instances to this
196 * ctx. If NULL, go back to talloc_free() as usual.
197 */
198void osmo_fsm_set_dealloc_ctx(void *ctx)
199{
200 fsm_term_safely.fsm_dealloc_ctx = ctx;
201}
202
Neels Hofmeyr1f9cc012019-03-24 05:56:21 +0100203/*! talloc_free() the given object immediately, or once ongoing FSM terminations are done.
204 *
205 * If an FSM deallocation cascade is ongoing, talloc_steal() the given talloc_object into the talloc context that is
206 * freed once the cascade is done. If no FSM deallocation cascade is ongoing, or if osmo_fsm_term_safely() is disabled,
207 * immediately talloc_free the object.
208 *
209 * This can be useful if some higher order talloc object, which is the talloc parent for FSM instances or their priv
210 * objects, is not itself tied to an FSM instance. This function allows safely freeing it without affecting ongoing FSM
211 * termination cascades.
212 *
213 * Once passed to this function, the talloc_object should be considered as already freed. Only FSM instance pre_term()
214 * and cleanup() functions as well as event handling caused by these may safely assume that it is still valid memory.
215 *
216 * The talloc_object should not have multiple parents.
217 *
218 * (This function may some day move to public API, which might be redundant if we introduce a select-loop volatile
219 * context mechanism to defer deallocation instead.)
220 *
221 * \param[in] talloc_object Object pointer to free.
222 */
223static void osmo_fsm_defer_free(void *talloc_object)
224{
225 if (!fsm_term_safely.depth) {
Neels Hofmeyr988f6d72019-10-04 20:37:17 +0200226 fsm_free_or_steal(talloc_object);
Neels Hofmeyr1f9cc012019-03-24 05:56:21 +0100227 return;
228 }
229
230 if (!fsm_term_safely.collect_ctx) {
231 /* This is actually the first other object / FSM instance besides the root terminating inst. Create the
232 * ctx to collect this and possibly more objects to free. Avoid talloc parent loops: don't make this ctx
233 * the child of the root inst or anything like that. */
234 fsm_term_safely.collect_ctx = talloc_named_const(NULL, 0, "fsm_term_safely.collect_ctx");
235 OSMO_ASSERT(fsm_term_safely.collect_ctx);
236 }
237 talloc_steal(fsm_term_safely.collect_ctx, talloc_object);
238}
239
Harald Welte8808bb42017-01-07 11:11:03 +0100240struct osmo_fsm *osmo_fsm_find_by_name(const char *name)
241{
242 struct osmo_fsm *fsm;
Harald Welte34193912017-01-07 11:49:55 +0100243 llist_for_each_entry(fsm, &osmo_g_fsms, list) {
Harald Welte8808bb42017-01-07 11:11:03 +0100244 if (!strcmp(name, fsm->name))
245 return fsm;
246 }
247 return NULL;
248}
249
Harald Welte4585e672017-04-16 17:23:56 +0200250struct osmo_fsm_inst *osmo_fsm_inst_find_by_name(const struct osmo_fsm *fsm,
251 const char *name)
252{
253 struct osmo_fsm_inst *fi;
254
Neels Hofmeyr2bcc8732018-04-09 01:35:02 +0200255 if (!name)
256 return NULL;
257
Harald Welte4585e672017-04-16 17:23:56 +0200258 llist_for_each_entry(fi, &fsm->instances, list) {
Neels Hofmeyr2bcc8732018-04-09 01:35:02 +0200259 if (!fi->name)
260 continue;
Harald Welte4585e672017-04-16 17:23:56 +0200261 if (!strcmp(name, fi->name))
262 return fi;
263 }
264 return NULL;
265}
266
267struct osmo_fsm_inst *osmo_fsm_inst_find_by_id(const struct osmo_fsm *fsm,
268 const char *id)
269{
270 struct osmo_fsm_inst *fi;
271
272 llist_for_each_entry(fi, &fsm->instances, list) {
273 if (!strcmp(id, fi->id))
274 return fi;
275 }
276 return NULL;
277}
278
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200279/*! register a FSM with the core
Harald Welte136e7372016-05-29 10:53:17 +0900280 *
281 * A FSM descriptor needs to be registered with the core before any
282 * instances can be created for it.
283 *
284 * \param[in] fsm Descriptor of Finite State Machine to be registered
285 * \returns 0 on success; negative on error
286 */
287int osmo_fsm_register(struct osmo_fsm *fsm)
288{
Harald Welte8c4f5452017-10-03 17:44:03 +0800289 if (!osmo_identifier_valid(fsm->name)) {
290 LOGP(DLGLOBAL, LOGL_ERROR, "Attempting to register FSM with illegal identifier '%s'\n", fsm->name);
291 return -EINVAL;
292 }
Harald Welte8808bb42017-01-07 11:11:03 +0100293 if (osmo_fsm_find_by_name(fsm->name))
294 return -EEXIST;
Stefan Sperling888dc7d2018-02-26 19:17:02 +0100295 if (fsm->event_names == NULL)
296 LOGP(DLGLOBAL, LOGL_ERROR, "FSM '%s' has no event names! Please fix!\n", fsm->name);
Harald Welte34193912017-01-07 11:49:55 +0100297 llist_add_tail(&fsm->list, &osmo_g_fsms);
Harald Welte136e7372016-05-29 10:53:17 +0900298 INIT_LLIST_HEAD(&fsm->instances);
299
300 return 0;
301}
302
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200303/*! unregister a FSM from the core
Harald Welte136e7372016-05-29 10:53:17 +0900304 *
305 * Once the FSM descriptor is unregistered, active instances can still
306 * use it, but no new instances may be created for it.
307 *
308 * \param[in] fsm Descriptor of Finite State Machine to be removed
309 */
310void osmo_fsm_unregister(struct osmo_fsm *fsm)
311{
312 llist_del(&fsm->list);
313}
314
315/* small wrapper function around timer expiration (for logging) */
316static void fsm_tmr_cb(void *data)
317{
318 struct osmo_fsm_inst *fi = data;
319 struct osmo_fsm *fsm = fi->fsm;
Neels Hofmeyr5734bff2019-02-21 02:27:48 +0100320 int32_t T = fi->T;
Harald Welte136e7372016-05-29 10:53:17 +0900321
Neels Hofmeyr5734bff2019-02-21 02:27:48 +0100322 LOGPFSM(fi, "Timeout of " OSMO_T_FMT "\n", OSMO_T_FMT_ARGS(fi->T));
Harald Welte136e7372016-05-29 10:53:17 +0900323
Harald Weltef627c0f2016-06-18 10:36:25 +0200324 if (fsm->timer_cb) {
325 int rc = fsm->timer_cb(fi);
Neels Hofmeyr19ec7b92017-11-18 23:10:24 +0100326 if (rc != 1)
327 /* We don't actually know whether fi exists anymore.
328 * Make sure to not access it and return right away. */
Harald Weltef627c0f2016-06-18 10:36:25 +0200329 return;
Neels Hofmeyr19ec7b92017-11-18 23:10:24 +0100330 /* The timer_cb told us to terminate, so we can safely assume
331 * that fi still exists. */
Harald Weltef627c0f2016-06-18 10:36:25 +0200332 LOGPFSM(fi, "timer_cb requested termination\n");
333 } else
334 LOGPFSM(fi, "No timer_cb, automatic termination\n");
335
336 /* if timer_cb returns 1 or there is no timer_cb */
337 osmo_fsm_inst_term(fi, OSMO_FSM_TERM_TIMEOUT, &T);
Harald Welte136e7372016-05-29 10:53:17 +0900338}
339
Daniel Willmannb0c43a62018-02-08 18:00:37 +0100340/*! Change id of the FSM instance
341 * \param[in] fi FSM instance
342 * \param[in] id new ID
343 * \returns 0 if the ID was updated, otherwise -EINVAL
344 */
345int osmo_fsm_inst_update_id(struct osmo_fsm_inst *fi, const char *id)
346{
Neels Hofmeyra64c45a2018-03-31 16:34:49 +0200347 if (!id)
348 return osmo_fsm_inst_update_id_f(fi, NULL);
349 else
350 return osmo_fsm_inst_update_id_f(fi, "%s", id);
351}
352
353static void update_name(struct osmo_fsm_inst *fi)
354{
355 if (fi->name)
356 talloc_free((char*)fi->name);
357
358 if (!fsm_log_addr) {
359 if (fi->id)
360 fi->name = talloc_asprintf(fi, "%s(%s)", fi->fsm->name, fi->id);
361 else
362 fi->name = talloc_asprintf(fi, "%s", fi->fsm->name);
363 } else {
364 if (fi->id)
365 fi->name = talloc_asprintf(fi, "%s(%s)[%p]", fi->fsm->name, fi->id, fi);
366 else
367 fi->name = talloc_asprintf(fi, "%s[%p]", fi->fsm->name, fi);
368 }
369}
370
371/*! Change id of the FSM instance using a string format.
372 * \param[in] fi FSM instance.
373 * \param[in] fmt format string to compose new ID.
374 * \param[in] ... variable argument list for format string.
375 * \returns 0 if the ID was updated, otherwise -EINVAL.
376 */
377int osmo_fsm_inst_update_id_f(struct osmo_fsm_inst *fi, const char *fmt, ...)
378{
379 char *id = NULL;
380
381 if (fmt) {
382 va_list ap;
383
384 va_start(ap, fmt);
385 id = talloc_vasprintf(fi, fmt, ap);
386 va_end(ap);
387
Daniel Willmannb0c43a62018-02-08 18:00:37 +0100388 if (!osmo_identifier_valid(id)) {
Neels Hofmeyr6e8c0882018-04-09 02:28:34 +0200389 LOGP(DLGLOBAL, LOGL_ERROR,
390 "Attempting to set illegal id for FSM instance of type '%s': %s\n",
391 fi->fsm->name, osmo_quote_str(id, -1));
Neels Hofmeyra64c45a2018-03-31 16:34:49 +0200392 talloc_free(id);
Daniel Willmannb0c43a62018-02-08 18:00:37 +0100393 return -EINVAL;
394 }
Daniel Willmannb0c43a62018-02-08 18:00:37 +0100395 }
Daniel Willmann04a2a322018-03-14 18:31:33 +0100396
397 if (fi->id)
Neels Hofmeyra64c45a2018-03-31 16:34:49 +0200398 talloc_free((char*)fi->id);
399 fi->id = id;
Daniel Willmann04a2a322018-03-14 18:31:33 +0100400
Neels Hofmeyra64c45a2018-03-31 16:34:49 +0200401 update_name(fi);
Daniel Willmann04a2a322018-03-14 18:31:33 +0100402 return 0;
Daniel Willmannb0c43a62018-02-08 18:00:37 +0100403}
404
Neels Hofmeyrb480b742019-04-11 06:58:44 +0200405/*! Change id of the FSM instance using a string format, and ensuring a valid id.
406 * Replace any characters that are not permitted as FSM identifier with replace_with.
407 * \param[in] fi FSM instance.
408 * \param[in] replace_with Character to use instead of non-permitted FSM id characters.
409 * Make sure to choose a legal character, e.g. '-'.
410 * \param[in] fmt format string to compose new ID.
411 * \param[in] ... variable argument list for format string.
412 * \returns 0 if the ID was updated, otherwise -EINVAL.
413 */
414int osmo_fsm_inst_update_id_f_sanitize(struct osmo_fsm_inst *fi, char replace_with, const char *fmt, ...)
415{
416 char *id = NULL;
417 va_list ap;
418 int rc;
419
420 if (!fmt)
421 return osmo_fsm_inst_update_id(fi, NULL);
422
423 va_start(ap, fmt);
424 id = talloc_vasprintf(fi, fmt, ap);
425 va_end(ap);
426
427 osmo_identifier_sanitize_buf(id, NULL, replace_with);
428
429 rc = osmo_fsm_inst_update_id(fi, id);
430 talloc_free(id);
431 return rc;
432}
433
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200434/*! allocate a new instance of a specified FSM
Harald Welte136e7372016-05-29 10:53:17 +0900435 * \param[in] fsm Descriptor of the FSM
436 * \param[in] ctx talloc context from which to allocate memory
437 * \param[in] priv private data reference store in fsm instance
438 * \param[in] log_level The log level for events of this FSM
Daniel Willmannb0c43a62018-02-08 18:00:37 +0100439 * \param[in] id The name/ID of the FSM instance
Harald Welte136e7372016-05-29 10:53:17 +0900440 * \returns newly-allocated, initialized and registered FSM instance
441 */
442struct osmo_fsm_inst *osmo_fsm_inst_alloc(struct osmo_fsm *fsm, void *ctx, void *priv,
443 int log_level, const char *id)
444{
445 struct osmo_fsm_inst *fi = talloc_zero(ctx, struct osmo_fsm_inst);
446
447 fi->fsm = fsm;
448 fi->priv = priv;
449 fi->log_level = log_level;
Pablo Neira Ayuso44f423f2017-05-08 18:00:28 +0200450 osmo_timer_setup(&fi->timer, fsm_tmr_cb, fi);
Daniel Willmannb0c43a62018-02-08 18:00:37 +0100451
Neels Hofmeyr71f76a12018-03-31 16:30:25 +0200452 if (osmo_fsm_inst_update_id(fi, id) < 0) {
Neels Hofmeyr988f6d72019-10-04 20:37:17 +0200453 fsm_free_or_steal(fi);
Neels Hofmeyr71f76a12018-03-31 16:30:25 +0200454 return NULL;
Harald Welte8c4f5452017-10-03 17:44:03 +0800455 }
Harald Welte136e7372016-05-29 10:53:17 +0900456
Harald Welte136e7372016-05-29 10:53:17 +0900457 INIT_LLIST_HEAD(&fi->proc.children);
458 INIT_LLIST_HEAD(&fi->proc.child);
459 llist_add(&fi->list, &fsm->instances);
460
461 LOGPFSM(fi, "Allocated\n");
462
463 return fi;
464}
465
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200466/*! allocate a new instance of a specified FSM as child of
Harald Welte136e7372016-05-29 10:53:17 +0900467 * other FSM instance
468 *
469 * This is like \ref osmo_fsm_inst_alloc but using the parent FSM as
470 * talloc context, and inheriting the log level of the parent.
471 *
472 * \param[in] fsm Descriptor of the to-be-allocated FSM
473 * \param[in] parent Parent FSM instance
474 * \param[in] parent_term_event Event to be sent to parent when terminating
475 * \returns newly-allocated, initialized and registered FSM instance
476 */
477struct osmo_fsm_inst *osmo_fsm_inst_alloc_child(struct osmo_fsm *fsm,
478 struct osmo_fsm_inst *parent,
479 uint32_t parent_term_event)
480{
481 struct osmo_fsm_inst *fi;
482
483 fi = osmo_fsm_inst_alloc(fsm, parent, NULL, parent->log_level,
484 parent->id);
485 if (!fi) {
486 /* indicate immediate termination to caller */
487 osmo_fsm_inst_dispatch(parent, parent_term_event, NULL);
488 return NULL;
489 }
490
491 LOGPFSM(fi, "is child of %s\n", osmo_fsm_inst_name(parent));
492
Philipp Maier2a06a492018-01-16 18:45:56 +0100493 osmo_fsm_inst_change_parent(fi, parent, parent_term_event);
Harald Welte136e7372016-05-29 10:53:17 +0900494
495 return fi;
496}
497
Philipp Maier2a06a492018-01-16 18:45:56 +0100498/*! unlink child FSM from its parent FSM.
499 * \param[in] fi Descriptor of the child FSM to unlink.
Philipp Maierd1f57932018-02-14 18:20:07 +0100500 * \param[in] ctx New talloc context
501 *
502 * Never call this function from the cleanup callback, because at that time
503 * the child FSMs will already be terminated. If unlinking should be performed
504 * on FSM termination, use the grace callback instead. */
Philipp Maier2a06a492018-01-16 18:45:56 +0100505void osmo_fsm_inst_unlink_parent(struct osmo_fsm_inst *fi, void *ctx)
506{
507 if (fi->proc.parent) {
508 talloc_steal(ctx, fi);
509 fi->proc.parent = NULL;
510 fi->proc.parent_term_event = 0;
511 llist_del(&fi->proc.child);
512 }
513}
514
515/*! change parent instance of an FSM.
516 * \param[in] fi Descriptor of the to-be-allocated FSM.
517 * \param[in] new_parent New parent FSM instance.
Philipp Maierd1f57932018-02-14 18:20:07 +0100518 * \param[in] new_parent_term_event Event to be sent to parent when terminating.
519 *
520 * Never call this function from the cleanup callback!
521 * (see also osmo_fsm_inst_unlink_parent()).*/
Philipp Maier2a06a492018-01-16 18:45:56 +0100522void osmo_fsm_inst_change_parent(struct osmo_fsm_inst *fi,
523 struct osmo_fsm_inst *new_parent,
524 uint32_t new_parent_term_event)
525{
526 /* Make sure a possibly existing old parent is unlinked first
527 * (new_parent can be NULL) */
528 osmo_fsm_inst_unlink_parent(fi, new_parent);
529
530 /* Add new parent */
531 if (new_parent) {
532 fi->proc.parent = new_parent;
533 fi->proc.parent_term_event = new_parent_term_event;
534 llist_add(&fi->proc.child, &new_parent->proc.children);
535 }
536}
537
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200538/*! delete a given instance of a FSM
Vadim Yanitskiy2f65bb12019-03-25 15:57:09 +0700539 * \param[in] fi FSM instance to be un-registered and deleted
Harald Welte136e7372016-05-29 10:53:17 +0900540 */
541void osmo_fsm_inst_free(struct osmo_fsm_inst *fi)
542{
543 osmo_timer_del(&fi->timer);
544 llist_del(&fi->list);
Neels Hofmeyr1f9cc012019-03-24 05:56:21 +0100545
546 if (fsm_term_safely.depth) {
547 /* Another FSM instance has caused this one to free and is still busy with its termination. Don't free
548 * yet, until the other FSM instance is done. */
549 osmo_fsm_defer_free(fi);
550 /* The root_fi can't go missing really, but to be safe... */
551 if (fsm_term_safely.root_fi)
552 LOGPFSM(fi, "Deferring: will deallocate with %s\n", fsm_term_safely.root_fi->name);
553 else
554 LOGPFSM(fi, "Deferring deallocation\n");
555
556 /* Don't free anything yet. Exit. */
557 return;
558 }
559
560 /* fsm_term_safely.depth == 0.
561 * - If fsm_term_safely is enabled, this is the original FSM instance that started terminating first. Free this
562 * and along with it all other collected terminated FSM instances.
563 * - If fsm_term_safely is disabled, this is just any FSM instance deallocating. */
564
565 if (fsm_term_safely.collect_ctx) {
566 /* The fi may be a child of any other FSM instances or objects collected in the collect_ctx. Don't
567 * deallocate separately to avoid use-after-free errors, put it in there and deallocate all at once. */
568 LOGPFSM(fi, "Deallocated, including all deferred deallocations\n");
569 osmo_fsm_defer_free(fi);
Neels Hofmeyr988f6d72019-10-04 20:37:17 +0200570 fsm_free_or_steal(fsm_term_safely.collect_ctx);
Neels Hofmeyr1f9cc012019-03-24 05:56:21 +0100571 fsm_term_safely.collect_ctx = NULL;
572 } else {
573 LOGPFSM(fi, "Deallocated\n");
Neels Hofmeyr988f6d72019-10-04 20:37:17 +0200574 fsm_free_or_steal(fi);
Neels Hofmeyr1f9cc012019-03-24 05:56:21 +0100575 }
576 fsm_term_safely.root_fi = NULL;
Harald Welte136e7372016-05-29 10:53:17 +0900577}
578
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200579/*! get human-readable name of FSM event
Harald Welte136e7372016-05-29 10:53:17 +0900580 * \param[in] fsm FSM descriptor of event
581 * \param[in] event Event integer value
582 * \returns string rendering of the event
583 */
584const char *osmo_fsm_event_name(struct osmo_fsm *fsm, uint32_t event)
585{
Harald Welte171ef822019-03-28 10:49:05 +0100586 static __thread char buf[32];
Harald Welte136e7372016-05-29 10:53:17 +0900587 if (!fsm->event_names) {
Pau Espin Pedrol4f8857e2017-06-18 12:23:00 +0200588 snprintf(buf, sizeof(buf), "%"PRIu32, event);
Harald Welte136e7372016-05-29 10:53:17 +0900589 return buf;
590 } else
591 return get_value_string(fsm->event_names, event);
592}
593
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200594/*! get human-readable name of FSM instance
Harald Welte136e7372016-05-29 10:53:17 +0900595 * \param[in] fi FSM instance
596 * \returns string rendering of the FSM identity
597 */
598const char *osmo_fsm_inst_name(struct osmo_fsm_inst *fi)
599{
600 if (!fi)
601 return "NULL";
602
603 if (fi->name)
604 return fi->name;
605 else
606 return fi->fsm->name;
607}
608
Philipp Maieraf6710f2018-11-16 17:45:40 +0100609/*! get human-readable name of FSM state
Harald Welte136e7372016-05-29 10:53:17 +0900610 * \param[in] fsm FSM descriptor
611 * \param[in] state FSM state number
612 * \returns string rendering of the FSM state
613 */
614const char *osmo_fsm_state_name(struct osmo_fsm *fsm, uint32_t state)
615{
Harald Welte171ef822019-03-28 10:49:05 +0100616 static __thread char buf[32];
Harald Welte136e7372016-05-29 10:53:17 +0900617 if (state >= fsm->num_states) {
Pau Espin Pedrol4f8857e2017-06-18 12:23:00 +0200618 snprintf(buf, sizeof(buf), "unknown %"PRIu32, state);
Harald Welte136e7372016-05-29 10:53:17 +0900619 return buf;
620 } else
621 return fsm->states[state].name;
622}
623
Neels Hofmeyr407df022018-05-25 18:20:06 +0200624static int state_chg(struct osmo_fsm_inst *fi, uint32_t new_state,
Harald Welte7b745512019-05-18 21:03:55 +0200625 bool keep_timer, unsigned long timeout_ms, int T,
Neels Hofmeyr407df022018-05-25 18:20:06 +0200626 const char *file, int line)
627{
628 struct osmo_fsm *fsm = fi->fsm;
629 uint32_t old_state = fi->state;
630 const struct osmo_fsm_state *st = &fsm->states[fi->state];
Neels Hofmeyr050f2d32018-05-31 15:30:15 +0200631 struct timeval remaining;
Neels Hofmeyr407df022018-05-25 18:20:06 +0200632
Neels Hofmeyrb1bbe242019-10-05 05:13:23 +0200633 if (fi->proc.terminating) {
634 LOGPFSMSRC(fi, file, line,
635 "FSM instance already terminating, not changing state to %s\n",
636 osmo_fsm_state_name(fsm, new_state));
637 return -EINVAL;
638 }
639
Neels Hofmeyr407df022018-05-25 18:20:06 +0200640 /* validate if new_state is a valid state */
641 if (!(st->out_state_mask & (1 << new_state))) {
642 LOGPFSMLSRC(fi, LOGL_ERROR, file, line,
643 "transition to state %s not permitted!\n",
644 osmo_fsm_state_name(fsm, new_state));
645 return -EPERM;
646 }
647
648 if (!keep_timer) {
649 /* delete the old timer */
650 osmo_timer_del(&fi->timer);
651 }
652
653 if (st->onleave)
654 st->onleave(fi, new_state);
655
Neels Hofmeyr050f2d32018-05-31 15:30:15 +0200656 if (fsm_log_timeouts) {
Harald Weltecb5e8312019-06-04 12:10:11 +0200657 char trailer[64];
658 trailer[0] = '\0';
Neels Hofmeyrd4b79c82019-03-06 05:43:23 +0100659 if (keep_timer && fi->timer.active) {
660 /* This should always give us a timeout, but just in case the return value indicates error, omit
661 * logging the remaining time. */
662 if (osmo_timer_remaining(&fi->timer, NULL, &remaining))
Harald Weltecb5e8312019-06-04 12:10:11 +0200663 snprintf(trailer, sizeof(trailer), "(keeping " OSMO_T_FMT ")",
664 OSMO_T_FMT_ARGS(fi->T));
Neels Hofmeyrd4b79c82019-03-06 05:43:23 +0100665 else
Harald Weltecb5e8312019-06-04 12:10:11 +0200666 snprintf(trailer, sizeof(trailer), "(keeping " OSMO_T_FMT
667 ", %ld.%03lds remaining)", OSMO_T_FMT_ARGS(fi->T),
Harald Weltedbdd4f02019-07-31 09:55:04 +0200668 (long) remaining.tv_sec, remaining.tv_usec / 1000);
Harald Welte7b745512019-05-18 21:03:55 +0200669 } else if (timeout_ms) {
Harald Weltecb5e8312019-06-04 12:10:11 +0200670 if (timeout_ms % 1000 == 0)
Harald Welte7b745512019-05-18 21:03:55 +0200671 /* keep log output legacy compatible to avoid autotest failures */
Harald Weltecb5e8312019-06-04 12:10:11 +0200672 snprintf(trailer, sizeof(trailer), "(" OSMO_T_FMT ", %lus)",
Harald Welte7b745512019-05-18 21:03:55 +0200673 OSMO_T_FMT_ARGS(T), timeout_ms/1000);
Harald Weltecb5e8312019-06-04 12:10:11 +0200674 else
675 snprintf(trailer, sizeof(trailer), "(" OSMO_T_FMT ", %lums)",
Harald Welte7b745512019-05-18 21:03:55 +0200676 OSMO_T_FMT_ARGS(T), timeout_ms);
Harald Welte7b745512019-05-18 21:03:55 +0200677 } else
Harald Weltecb5e8312019-06-04 12:10:11 +0200678 snprintf(trailer, sizeof(trailer), "(no timeout)");
679
680 LOGPFSMSRC(fi, file, line, "State change to %s %s\n",
681 osmo_fsm_state_name(fsm, new_state), trailer);
Neels Hofmeyr050f2d32018-05-31 15:30:15 +0200682 } else {
683 LOGPFSMSRC(fi, file, line, "state_chg to %s\n",
684 osmo_fsm_state_name(fsm, new_state));
685 }
686
Neels Hofmeyr407df022018-05-25 18:20:06 +0200687 fi->state = new_state;
688 st = &fsm->states[new_state];
689
Neels Hofmeyrd4b79c82019-03-06 05:43:23 +0100690 if (!keep_timer
691 || (keep_timer && !osmo_timer_pending(&fi->timer))) {
Neels Hofmeyr407df022018-05-25 18:20:06 +0200692 fi->T = T;
Harald Welte7b745512019-05-18 21:03:55 +0200693 if (timeout_ms)
694 osmo_timer_schedule(&fi->timer, timeout_ms / 1000, timeout_ms % 1000);
Neels Hofmeyr407df022018-05-25 18:20:06 +0200695 }
696
697 /* Call 'onenter' last, user might terminate FSM from there */
698 if (st->onenter)
699 st->onenter(fi, old_state);
700
701 return 0;
702}
703
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200704/*! perform a state change of the given FSM instance
Harald Welte136e7372016-05-29 10:53:17 +0900705 *
Neels Hofmeyr725698a2016-12-14 17:24:54 +0100706 * Best invoke via the osmo_fsm_inst_state_chg() macro which logs the source
707 * file where the state change was effected. Alternatively, you may pass \a
708 * file as NULL to use the normal file/line indication instead.
709 *
Neels Hofmeyr407df022018-05-25 18:20:06 +0200710 * All changes to the FSM instance state must be made via an osmo_fsm_inst_state_chg_*
Harald Welte136e7372016-05-29 10:53:17 +0900711 * function. It verifies that the existing state actually permits a
Neels Hofmeyr407df022018-05-25 18:20:06 +0200712 * transition to new_state.
Harald Welte136e7372016-05-29 10:53:17 +0900713 *
Neels Hofmeyrbd5a1dc2019-01-28 15:38:09 +0100714 * If timeout_secs is 0, stay in the new state indefinitely, without a timeout
715 * (stop the FSM instance's timer if it was runnning).
716 *
717 * If timeout_secs > 0, start or reset the FSM instance's timer with this
718 * timeout. On expiry, invoke the FSM instance's timer_cb -- if no timer_cb is
719 * set, an expired timer immediately terminates the FSM instance with
720 * OSMO_FSM_TERM_TIMEOUT.
721 *
722 * The value of T is stored in fi->T and is then available for query in
723 * timer_cb. If passing timeout_secs == 0, it is recommended to also pass T ==
724 * 0, so that fi->T is reset to 0 when no timeout is invoked.
Harald Welte136e7372016-05-29 10:53:17 +0900725 *
Neels Hofmeyr5734bff2019-02-21 02:27:48 +0100726 * Positive values for T are considered to be 3GPP spec compliant and appear in
727 * logging and VTY as "T1234", while negative values are considered to be
728 * Osmocom specific timers, represented in logging and VTY as "X1234".
729 *
Neels Hofmeyr0fd615f2019-01-26 20:36:12 +0100730 * See also osmo_tdef_fsm_inst_state_chg() from the osmo_tdef API, which
731 * provides a unified way to configure and apply GSM style Tnnnn timers to FSM
732 * state transitions.
733 *
Harald Welte136e7372016-05-29 10:53:17 +0900734 * \param[in] fi FSM instance whose state is to change
735 * \param[in] new_state The new state into which we should change
Neels Hofmeyr89991fd2019-01-28 19:06:53 +0100736 * \param[in] timeout_secs Timeout in seconds (if !=0), maximum-clamped to 2147483647 seconds.
Neels Hofmeyr5734bff2019-02-21 02:27:48 +0100737 * \param[in] T Timer number, where positive numbers are considered to be 3GPP spec compliant timer numbers and are
738 * logged as "T1234", while negative numbers are considered Osmocom specific timer numbers logged as
739 * "X1234".
Neels Hofmeyrb805cc12016-12-23 04:23:18 +0100740 * \param[in] file Calling source file (from osmo_fsm_inst_state_chg macro)
741 * \param[in] line Calling source line (from osmo_fsm_inst_state_chg macro)
Harald Welte136e7372016-05-29 10:53:17 +0900742 * \returns 0 on success; negative on error
743 */
Neels Hofmeyr725698a2016-12-14 17:24:54 +0100744int _osmo_fsm_inst_state_chg(struct osmo_fsm_inst *fi, uint32_t new_state,
745 unsigned long timeout_secs, int T,
746 const char *file, int line)
Harald Welte136e7372016-05-29 10:53:17 +0900747{
Harald Welte7b745512019-05-18 21:03:55 +0200748 return state_chg(fi, new_state, false, timeout_secs*1000, T, file, line);
749}
750int _osmo_fsm_inst_state_chg_ms(struct osmo_fsm_inst *fi, uint32_t new_state,
751 unsigned long timeout_ms, int T,
752 const char *file, int line)
753{
754 return state_chg(fi, new_state, false, timeout_ms, T, file, line);
Neels Hofmeyr407df022018-05-25 18:20:06 +0200755}
Harald Welte136e7372016-05-29 10:53:17 +0900756
Neels Hofmeyr407df022018-05-25 18:20:06 +0200757/*! perform a state change while keeping the current timer running.
758 *
759 * This is useful to keep a timeout across several states (without having to round the
760 * remaining time to seconds).
761 *
762 * Best invoke via the osmo_fsm_inst_state_chg_keep_timer() macro which logs the source
763 * file where the state change was effected. Alternatively, you may pass \a
764 * file as NULL to use the normal file/line indication instead.
765 *
766 * All changes to the FSM instance state must be made via an osmo_fsm_inst_state_chg_*
767 * function. It verifies that the existing state actually permits a
768 * transition to new_state.
769 *
770 * \param[in] fi FSM instance whose state is to change
771 * \param[in] new_state The new state into which we should change
772 * \param[in] file Calling source file (from osmo_fsm_inst_state_chg macro)
773 * \param[in] line Calling source line (from osmo_fsm_inst_state_chg macro)
774 * \returns 0 on success; negative on error
775 */
776int _osmo_fsm_inst_state_chg_keep_timer(struct osmo_fsm_inst *fi, uint32_t new_state,
777 const char *file, int line)
778{
779 return state_chg(fi, new_state, true, 0, 0, file, line);
Harald Welte136e7372016-05-29 10:53:17 +0900780}
781
Neels Hofmeyrd4b79c82019-03-06 05:43:23 +0100782/*! perform a state change while keeping the current timer if running, or starting a timer otherwise.
783 *
784 * This is useful to keep a timeout across several states, but to make sure that some timeout is actually running.
785 *
786 * Best invoke via the osmo_fsm_inst_state_chg_keep_or_start_timer() macro which logs the source file where the state
787 * change was effected. Alternatively, you may pass file as NULL to use the normal file/line indication instead.
788 *
789 * All changes to the FSM instance state must be made via an osmo_fsm_inst_state_chg_*
790 * function. It verifies that the existing state actually permits a
791 * transition to new_state.
792 *
793 * \param[in] fi FSM instance whose state is to change
794 * \param[in] new_state The new state into which we should change
795 * \param[in] timeout_secs If no timer is running yet, set this timeout in seconds (if !=0), maximum-clamped to
796 * 2147483647 seconds.
797 * \param[in] T Timer number, where positive numbers are considered to be 3GPP spec compliant timer numbers and are
798 * logged as "T1234", while negative numbers are considered Osmocom specific timer numbers logged as
799 * "X1234".
800 * \param[in] file Calling source file (from osmo_fsm_inst_state_chg macro)
801 * \param[in] line Calling source line (from osmo_fsm_inst_state_chg macro)
802 * \returns 0 on success; negative on error
803 */
804int _osmo_fsm_inst_state_chg_keep_or_start_timer(struct osmo_fsm_inst *fi, uint32_t new_state,
805 unsigned long timeout_secs, int T,
806 const char *file, int line)
807{
Harald Welte7b745512019-05-18 21:03:55 +0200808 return state_chg(fi, new_state, true, timeout_secs*1000, T, file, line);
Neels Hofmeyrd4b79c82019-03-06 05:43:23 +0100809}
Harald Welte7b745512019-05-18 21:03:55 +0200810int _osmo_fsm_inst_state_chg_keep_or_start_timer_ms(struct osmo_fsm_inst *fi, uint32_t new_state,
811 unsigned long timeout_ms, int T,
812 const char *file, int line)
813{
814 return state_chg(fi, new_state, true, timeout_ms, T, file, line);
815}
816
Neels Hofmeyrd4b79c82019-03-06 05:43:23 +0100817
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200818/*! dispatch an event to an osmocom finite state machine instance
Harald Welte136e7372016-05-29 10:53:17 +0900819 *
Neels Hofmeyr725698a2016-12-14 17:24:54 +0100820 * Best invoke via the osmo_fsm_inst_dispatch() macro which logs the source
821 * file where the event was effected. Alternatively, you may pass \a file as
822 * NULL to use the normal file/line indication instead.
823 *
Harald Welte136e7372016-05-29 10:53:17 +0900824 * Any incoming events to \ref osmo_fsm instances must be dispatched to
825 * them via this function. It verifies, whether the event is permitted
826 * based on the current state of the FSM. If not, -1 is returned.
827 *
828 * \param[in] fi FSM instance
829 * \param[in] event Event to send to FSM instance
830 * \param[in] data Data to pass along with the event
Neels Hofmeyrb805cc12016-12-23 04:23:18 +0100831 * \param[in] file Calling source file (from osmo_fsm_inst_dispatch macro)
832 * \param[in] line Calling source line (from osmo_fsm_inst_dispatch macro)
Harald Welte136e7372016-05-29 10:53:17 +0900833 * \returns 0 in case of success; negative on error
834 */
Neels Hofmeyr725698a2016-12-14 17:24:54 +0100835int _osmo_fsm_inst_dispatch(struct osmo_fsm_inst *fi, uint32_t event, void *data,
836 const char *file, int line)
Harald Welte136e7372016-05-29 10:53:17 +0900837{
838 struct osmo_fsm *fsm;
839 const struct osmo_fsm_state *fs;
840
841 if (!fi) {
Neels Hofmeyrc7155df2016-12-23 04:24:51 +0100842 LOGPSRC(DLGLOBAL, LOGL_ERROR, file, line,
Pau Espin Pedrol4f8857e2017-06-18 12:23:00 +0200843 "Trying to dispatch event %"PRIu32" to non-existent"
Neels Hofmeyrc7155df2016-12-23 04:24:51 +0100844 " FSM instance!\n", event);
Harald Welte136e7372016-05-29 10:53:17 +0900845 osmo_log_backtrace(DLGLOBAL, LOGL_ERROR);
846 return -ENODEV;
847 }
848
849 fsm = fi->fsm;
Neels Hofmeyrb1bbe242019-10-05 05:13:23 +0200850
851 if (fi->proc.terminating) {
852 LOGPFSMSRC(fi, file, line,
853 "FSM instance already terminating, not dispatching event %s\n",
854 osmo_fsm_event_name(fsm, event));
855 return -EINVAL;
856 }
857
Harald Welte136e7372016-05-29 10:53:17 +0900858 OSMO_ASSERT(fi->state < fsm->num_states);
859 fs = &fi->fsm->states[fi->state];
860
Neels Hofmeyr725698a2016-12-14 17:24:54 +0100861 LOGPFSMSRC(fi, file, line,
862 "Received Event %s\n", osmo_fsm_event_name(fsm, event));
Harald Welte136e7372016-05-29 10:53:17 +0900863
864 if (((1 << event) & fsm->allstate_event_mask) && fsm->allstate_action) {
865 fsm->allstate_action(fi, event, data);
866 return 0;
867 }
868
869 if (!((1 << event) & fs->in_event_mask)) {
Neels Hofmeyr725698a2016-12-14 17:24:54 +0100870 LOGPFSMLSRC(fi, LOGL_ERROR, file, line,
871 "Event %s not permitted\n",
872 osmo_fsm_event_name(fsm, event));
Harald Welte136e7372016-05-29 10:53:17 +0900873 return -1;
874 }
Philipp Maier3d4fb592018-05-15 10:06:22 +0200875
876 if (fs->action)
877 fs->action(fi, event, data);
Harald Welte136e7372016-05-29 10:53:17 +0900878
879 return 0;
880}
881
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200882/*! Terminate FSM instance with given cause
Harald Welte136e7372016-05-29 10:53:17 +0900883 *
884 * This safely terminates the given FSM instance by first iterating
885 * over all children and sending them a termination event. Next, it
886 * calls the FSM descriptors cleanup function (if any), followed by
887 * releasing any memory associated with the FSM instance.
888 *
889 * Finally, the parent FSM instance (if any) is notified using the
890 * parent termination event configured at time of FSM instance start.
891 *
892 * \param[in] fi FSM instance to be terminated
893 * \param[in] cause Cause / reason for termination
Neels Hofmeyrb805cc12016-12-23 04:23:18 +0100894 * \param[in] data Opaque event data to be passed with the parent term event
895 * \param[in] file Calling source file (from osmo_fsm_inst_term macro)
896 * \param[in] line Calling source line (from osmo_fsm_inst_term macro)
Harald Welte136e7372016-05-29 10:53:17 +0900897 */
Neels Hofmeyr725698a2016-12-14 17:24:54 +0100898void _osmo_fsm_inst_term(struct osmo_fsm_inst *fi,
899 enum osmo_fsm_term_cause cause, void *data,
900 const char *file, int line)
Harald Welte136e7372016-05-29 10:53:17 +0900901{
Neels Hofmeyr3faa0142016-12-18 23:41:41 +0100902 struct osmo_fsm_inst *parent;
Harald Welte136e7372016-05-29 10:53:17 +0900903 uint32_t parent_term_event = fi->proc.parent_term_event;
904
Neels Hofmeyr3b414a42019-04-08 00:33:53 +0200905 if (fi->proc.terminating) {
906 LOGPFSMSRC(fi, file, line, "Ignoring trigger to terminate: already terminating\n");
907 return;
908 }
909 fi->proc.terminating = true;
910
Neels Hofmeyr1f9cc012019-03-24 05:56:21 +0100911 /* Start termination cascade handling only if the feature is enabled. Also check the current depth: though
912 * unlikely, theoretically the fsm_term_safely_enabled flag could be toggled in the middle of a cascaded
913 * termination, so make sure to continue if it already started. */
914 if (fsm_term_safely_enabled || fsm_term_safely.depth) {
915 fsm_term_safely.depth++;
916 /* root_fi is just for logging, so no need to be extra careful about it. */
917 if (!fsm_term_safely.root_fi)
918 fsm_term_safely.root_fi = fi;
919 }
920
921 if (fsm_term_safely.depth > 1) {
922 /* fsm_term_safely is enabled and this is a secondary FSM instance terminated, caused by the root_fi. */
923 LOGPFSMSRC(fi, file, line, "Terminating in cascade, depth %d (cause = %s, caused by: %s)\n",
924 fsm_term_safely.depth, osmo_fsm_term_cause_name(cause),
925 fsm_term_safely.root_fi ? fsm_term_safely.root_fi->name : "unknown");
926 /* The root_fi can't go missing really, but to be safe, log "unknown" in that case. */
927 } else {
928 /* fsm_term_safely is disabled, or this is the root_fi. */
929 LOGPFSMSRC(fi, file, line, "Terminating (cause = %s)\n", osmo_fsm_term_cause_name(cause));
930 }
Harald Welte136e7372016-05-29 10:53:17 +0900931
Philipp Maierd1f57932018-02-14 18:20:07 +0100932 /* graceful exit (optional) */
933 if (fi->fsm->pre_term)
934 fi->fsm->pre_term(fi, cause);
935
Harald Welte65900442018-02-09 09:58:57 +0000936 _osmo_fsm_inst_term_children(fi, OSMO_FSM_TERM_PARENT, NULL,
937 file, line);
938
Neels Hofmeyrc014f602016-12-23 04:26:39 +0100939 /* delete ourselves from the parent */
Neels Hofmeyr3faa0142016-12-18 23:41:41 +0100940 parent = fi->proc.parent;
Philipp Maier23d31612018-01-16 18:50:23 +0100941 if (parent) {
Neels Hofmeyrc014f602016-12-23 04:26:39 +0100942 LOGPFSMSRC(fi, file, line, "Removing from parent %s\n",
943 osmo_fsm_inst_name(parent));
Philipp Maier23d31612018-01-16 18:50:23 +0100944 llist_del(&fi->proc.child);
945 }
Neels Hofmeyrc014f602016-12-23 04:26:39 +0100946
947 /* call destructor / clean-up function */
948 if (fi->fsm->cleanup)
949 fi->fsm->cleanup(fi, cause);
950
Neels Hofmeyr3faa0142016-12-18 23:41:41 +0100951 /* Fetch parent again in case it has changed. */
952 parent = fi->proc.parent;
Neels Hofmeyr1f9cc012019-03-24 05:56:21 +0100953
954 /* Legacy behavior if fsm_term_safely is disabled: free before dispatching parent event. (If fsm_term_safely is
955 * enabled, depth will *always* be > 0 here.) Pivot on depth instead of the enabled flag in case the enabled
956 * flag is toggled in the middle of an FSM term. */
957 if (!fsm_term_safely.depth) {
958 LOGPFSMSRC(fi, file, line, "Freeing instance\n");
959 osmo_fsm_inst_free(fi);
960 }
Neels Hofmeyrc014f602016-12-23 04:26:39 +0100961
962 /* indicate our termination to the parent */
963 if (parent && cause != OSMO_FSM_TERM_PARENT)
964 _osmo_fsm_inst_dispatch(parent, parent_term_event, data,
965 file, line);
Neels Hofmeyr1f9cc012019-03-24 05:56:21 +0100966
967 /* Newer, safe deallocation: free only after the parent_term_event was dispatched, to catch all termination
968 * cascades, and free all FSM instances at once. (If fsm_term_safely is enabled, depth will *always* be > 0
969 * here.) osmo_fsm_inst_free() will do the defer magic depending on the fsm_term_safely.depth. */
970 if (fsm_term_safely.depth) {
971 fsm_term_safely.depth--;
972 osmo_fsm_inst_free(fi);
973 }
Neels Hofmeyrc014f602016-12-23 04:26:39 +0100974}
975
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200976/*! Terminate all child FSM instances of an FSM instance.
Neels Hofmeyrc014f602016-12-23 04:26:39 +0100977 *
978 * Iterate over all children and send them a termination event, with the given
979 * cause. Pass OSMO_FSM_TERM_PARENT to avoid dispatching events from the
980 * terminated child FSMs.
981 *
982 * \param[in] fi FSM instance that should be cleared of child FSMs
983 * \param[in] cause Cause / reason for termination (OSMO_FSM_TERM_PARENT)
984 * \param[in] data Opaque event data to be passed with the parent term events
985 * \param[in] file Calling source file (from osmo_fsm_inst_term_children macro)
986 * \param[in] line Calling source line (from osmo_fsm_inst_term_children macro)
987 */
988void _osmo_fsm_inst_term_children(struct osmo_fsm_inst *fi,
989 enum osmo_fsm_term_cause cause,
990 void *data,
991 const char *file, int line)
992{
993 struct osmo_fsm_inst *first_child, *last_seen_first_child;
994
Neels Hofmeyr06ac9b42016-12-20 12:05:19 +0100995 /* iterate over all children, starting from the beginning every time:
996 * terminating an FSM may emit events that cause other FSMs to also
997 * terminate and remove themselves from this list. */
998 last_seen_first_child = NULL;
999 while (!llist_empty(&fi->proc.children)) {
1000 first_child = llist_entry(fi->proc.children.next,
1001 typeof(*first_child),
1002 proc.child);
1003
1004 /* paranoia: do not loop forever */
1005 if (first_child == last_seen_first_child) {
1006 LOGPFSMLSRC(fi, LOGL_ERROR, file, line,
1007 "Internal error while terminating child"
1008 " FSMs: a child FSM is stuck\n");
1009 break;
1010 }
1011 last_seen_first_child = first_child;
1012
Harald Welte136e7372016-05-29 10:53:17 +09001013 /* terminate child */
Neels Hofmeyrc014f602016-12-23 04:26:39 +01001014 _osmo_fsm_inst_term(first_child, cause, data,
Neels Hofmeyr725698a2016-12-14 17:24:54 +01001015 file, line);
Harald Welte136e7372016-05-29 10:53:17 +09001016 }
Harald Welte136e7372016-05-29 10:53:17 +09001017}
1018
Harald Welte4eb0f162020-12-21 12:34:46 +01001019/*! Broadcast an event to all the FSMs children.
1020 *
1021 * Iterate over all children and send them the specified event.
1022 *
1023 * \param[in] fi FSM instance of the parent
1024 * \param[in] event Event to send to children of FSM instance
1025 * \param[in] data Data to pass along with the event
1026 * \param[in] file Calling source file (from osmo_fsm_inst_dispatch macro)
1027 * \param[in] line Calling source line (from osmo_fsm_inst_dispatch macro)
1028 */
1029void _osmo_fsm_inst_broadcast_children(struct osmo_fsm_inst *fi,
1030 uint32_t event, void *data,
1031 const char *file, int line)
1032{
1033 struct osmo_fsm_inst *child, *tmp;
1034 llist_for_each_entry_safe(child, tmp, &fi->proc.children, proc.child) {
1035 _osmo_fsm_inst_dispatch(child, event, data, file, line);
1036 }
1037}
1038
Neels Hofmeyr5c5c78a2016-12-14 18:35:47 +01001039const struct value_string osmo_fsm_term_cause_names[] = {
Neels Hofmeyr18080962016-12-16 13:43:54 +01001040 OSMO_VALUE_STRING(OSMO_FSM_TERM_PARENT),
1041 OSMO_VALUE_STRING(OSMO_FSM_TERM_REQUEST),
1042 OSMO_VALUE_STRING(OSMO_FSM_TERM_REGULAR),
1043 OSMO_VALUE_STRING(OSMO_FSM_TERM_ERROR),
1044 OSMO_VALUE_STRING(OSMO_FSM_TERM_TIMEOUT),
Neels Hofmeyr5c5c78a2016-12-14 18:35:47 +01001045 { 0, NULL }
1046};
1047
Harald Welte136e7372016-05-29 10:53:17 +09001048/*! @} */