Embedded HandbookApps
All sections › IX. The C language: from basics to advanced
STM32F103, STM32F407, STM32G031 · level intermediate · 8 min read
Open in the interactive handbook

76к. Topological sort: module initialisation order and detecting circular dependencies

In firmware of a dozen modules the start-up order is usually written by hand in main: clocks, then pins, then DMA, then UART… While there are few modules, this works. When there are twenty and every developer adds their own, the order starts to break: the log was enabled before the UART, the settings are read from flash before SPI is up. The task "arrange them so that each comes after everyone it depends on" is solved by topological sorting, and along the way it also finds cycles — modules that wait for each other.

Basis: alg.c with Kahn's algorithm and cycle search built with gcc 12.2.0 on the computer (stm-sys:1) — 12 modules listed in an arbitrary order; the order is checked at every step, then one extra dependency forming a cycle is added to the graph. The same file built with arm-none-eabi-gcc 12.2.1 (stm-arm:1) at -O2 for Cortex-M4F and Cortex-M0 — sizes, stack frames and the library functions called.

Terms used in the documentation

Original Meaning
topological sort topological sort: an order in which each node comes after its dependencies
directed acyclic graph (DAG) a directed graph without cycles
dependency graph dependency graph: who cannot start without whom
Kahn's algorithm Kahn's algorithm: take nodes with no unmet dependencies
in-degree in-degree: how many dependencies are still unmet
dependency cycle dependency cycle: modules wait for each other in a circle
initialization level initialisation level: the length of the longest chain up to the module

In plain words. When dressing, you cannot put on shoes before socks or a jacket before a shirt, but socks and a shirt — in any order. Topological sorting means making such an order for the whole wardrobe at once: at each step take any item for which everything needed is already on. If at some moment there is nothing to take, but items are still left — then somewhere there is a circular condition: "shoes after socks, socks after shoes".


76к.1 Modules and their dependencies

Each module knows only its direct suppliers. There are fewer than 32 modules, so the dependencies are a uint32_t bit mask: bit j means "depends on module j". The whole table is const in flash:

typedef struct {
    const char *name;
    uint32_t deps;     /* бит j — модуль зависит от модуля j */
} module_t;

The example has 12 modules, and in the table they are deliberately listed "any old way": the application first, the clock last. The algorithm has to find the order:

Module depends on
app sensor, config, rtc
config flash, log
sensor i2c, log
log uart
rtc clock, config
flash spi
uart, i2c, spi gpio, dma
dma, gpio clock
clock —

76к.2 Kahn's algorithm

For each module count how many of its dependencies have not started yet — the in-degree. Modules with zero are ready. Take a ready one, put it in the order and decrement the counter of everyone who was waiting for it; whoever reaches zero is ready too:

while (ready) {
    int j = __builtin_ctz(ready); /* из готовых — с наименьшим номером: порядок воспроизводим */
    ready &= ready - 1;
    order[k++] = (uint8_t)j;
    for (uint32_t u = users[j]; u; u &= u - 1) {
        int i = __builtin_ctz(u);
        if (level[j] + 1 > level[i])
            level[i] = (uint8_t)(level[j] + 1); /* уровень — длина самой длинной цепочки зависимостей */
        if (--indeg[i] == 0)
            ready |= 1u << i;
    }
}

The set of ready modules is also a mask, and the module with the lowest number is always taken from it (__builtin_ctz): the order comes out the same at every start, not dependent on chance. The reverse links "who waits for module j" are collected from the table once before the loop. The work is O(n + e), where e is the number of dependencies: each module and each dependency is processed once.

The run: all 12 modules are ordered, and the check confirmed that each comes after all its dependencies:

clock, dma, gpio, uart, log, i2c, sensor, spi, flash, config, rtc, app


76к.3 Levels: what can be started at the same time

Along the way the algorithm computes the level — the length of the longest chain of dependencies up to the module. Modules of one level do not depend on each other:

Level modules
0 clock
1 dma, gpio
2 uart, i2c, spi
3 log, flash
4 sensor, config
5 rtc
6 app

A graph of 12 modules laid out on seven levels from left to right: clock; dma and gpio; uart, i2c and spi; log and flash; sensor and config; rtc; app; the arrows go from a dependency to the module; a red dashed line from config to log shows the extra dependency that forms the cycle log → config → log

Levels are useful in two cases. If a module's initialisation waits — for example, for an oscillator to stabilise or for a sensor to answer — modules of one level can be started and waited for at the same time, not one by one. And the device must be switched off in reverse order: app first, clock last — otherwise a module is left without its supplier in the middle of work.


76к.4 A cycle: when no order is possible

Let us make one plausible change: the log takes its verbosity level from the settings, that is log now depends on config. But config already depends on log — it writes flash read errors to the log. The result is a cycle.

Kahn's algorithm notices this by itself: the ready modules run out before all modules are ordered. In the run 7 modules out of 12 were ordered; app, config, sensor, log, rtc remained — each has an unmet dependency. But not all of them are in the cycle: app, sensor and rtc simply wait for modules from the cycle. The cycle itself is found by a walk along the dependencies among the remaining ones until a module repeats:

while (pos[v] < 0) {
    pos[v] = (int8_t)len;
    cyc[len++] = (uint8_t)v;
    v = __builtin_ctz(m[v].deps & left); /* у неупорядоченного всегда есть неупорядоченная зависимость */
}

The run found a cycle of length 2: config → log → config. This is exactly what must be shown to the developer — not "initialisation failed" but "these two modules wait for each other". The cycle is broken by taking out the common part: for example, the log starts with a default level, and the level from the settings is applied later, as a separate step after config.


76к.5 When to sort: at start-up or at build time

Where Pros Cons
at every start, in firmware the module table is the single source of truth sorting code and stack in firmware; a cycle error shows only on the device
at build time, by a generator a ready order array in firmware; a cycle breaks the build a generation step is needed in the build

For a device the second is better: a dependency cycle is a programmer's error, and the build should find it, not the customer. The same alg.c compiles on the computer too — in an order generator or in a unit test — so the code is one. But if modules are attached at run time (replaceable expansion boards), sorting at start-up is justified.


76к.6 Code and stack

Function code bytes M4 stack frame M4 code bytes M0 stack frame M0
topo_kahn 268 208 300 216
topo_cycle 184 56 174 64

The topo_kahn frame is 208 bytes: the reverse link array users[32] is 128 bytes, the counters indeg[32] are 32. On M4 __builtin_popcount became a call to the library __popcountsi2 — Cortex-M has no population count instruction (76.8). On M0 __ctzsi2 was added to it: Thumb-1 has neither clz nor rbit, and the number of the lowest set bit is also computed by the library. For twelve modules this does not matter; in a hot loop it does.


76к.7 Where else a topological order is needed

Task Nodes Dependency
initialisation and shutdown order firmware modules "needed earlier"
recomputing linked parameters computed settings parameters "is computed from"
build order files, libraries "is built from"
running test steps on a bench check steps "makes sense only after"
evaluation order in a block diagram (filters, controllers) signal processing blocks "takes the output of"

76к.8 Without bit masks

Masks are good up to 32 modules (or 64 with uint64_t). For more, dependencies are stored as a list of "who — from whom" pairs in one array, and the reverse links as in 76е, but without pointers: an array of numbers where for each module those waiting for it are written. The algorithm is the same; instead of __builtin_ctz over the ready mask — a queue of ready modules in a ring buffer. If a reproducible order with the lowest number is needed, the queue is replaced by the heap from 76г.


76к.9 Pitfalls

The order in main diverged from the dependencies. A new module was added at the end, but it is needed earlier. The order is computed from the dependency table, not written by hand.

The order changes from build to build. Any ready module was taken, for example the first by memory address. Take the lowest number — the order is reproducible.

The device "hung" at start-up. A dependency cycle, and each module waits for another. Kahn reports this by itself: fewer are ordered than there are modules; report the cycle by names.

Innocent modules got into the cycle report. Modules that simply wait for the cycle (app, sensor, rtc) also remained unordered. Extract the cycle itself by walking the dependencies.

Shutdown broke the flash. The modules were switched off in start-up order, and spi went off before config, which was still writing the settings. Switch off in reverse order.


76к.10 Summary

Next: section 76л "Dijkstra's algorithm: the shortest path in a mesh network and on a grid for a robot on static arrays" — how to choose a route by link cost and plan a robot path without a single malloc.

Open in the interactive handbook