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

76е. Linked lists on a static pool: intrusive lists, a node pool and container_of

A linked list in a textbook is a malloc for every node and a pointer to the data inside the node. In firmware this is almost never done: the heap fragments, an allocation failure comes after a week of operation, and the extra pointer on every node costs memory. Instead the node is embedded in the object itself — an intrusive list — and the objects are taken from a static fixed-size pool. This is how the task lists in FreeRTOS, message queues in protocol stacks and device lists in drivers are built.

Basis: alg.c with the list, the pool and a message that sits in two lists at once, built with gcc 12.2.0 on the computer (stm-sys:1) — 100000 random steps "take from the pool — put in the queue — send — drop a channel", and after each step all links are checked. The same file built with arm-none-eabi-gcc 12.2.1 (stm-arm:1) at -O2 for Cortex-M4F and Cortex-M0: function sizes, while the sizes and offsets of the structures on ARM are fixed by _Static_assert — the file simply will not build if they are different.

Terms used in the documentation

Original Meaning
intrusive list intrusive list: the node is a field of the object itself
doubly linked circular list doubly linked circular list
sentinel node, list head sentinel node: the list head pointing to the first and the last
container_of a macro: find the start of the object from the address of a field
offsetof the offset of a field from the start of the structure, from stddef.h
object pool, free list object pool, free list: O(1) allocation without a heap
ListItem_t, xListEnd a FreeRTOS list item and its sentinel at the end of the list
_Static_assert a check of a condition at compile time

In plain words. An ordinary list is like a rope with tags to which things are tied: the thing itself knows nothing about the rope. In an intrusive list each thing has its own hooks, and the rope catches right onto them — no tags are needed. If there are two hooks, a thing can hang on two ropes at once. And a pool is a box of things prepared in advance: you can take and return instantly, and the box never "breaks up" into pieces like a heap.


76е.1 Why lists if there are arrays

Action Array Linked list
find the i-th element 1 step i steps
remove an element from the middle, knowing it a shift of the tail 4 pointer writes
insert into the middle a shift of the tail 4 pointer writes
memory per element beyond the data 0 two pointers — 8 bytes on Cortex-M

The array_remove run: removing the 8th element of 16 takes 7 moves, the 128th of 256 takes 127, the first of 256 takes 255. A list removes a node with four pointer writes at any size. Hence the rule: a list is taken when objects are often removed from the middle — a message is cancelled, a task is removed from a wait queue, a device is disconnected — and are almost never accessed by index.

The compiler, by the way, turned the shift loop in array_remove into a call to memmove — a single call in the machine code.


76е.2 An intrusive node and a sentinel node

A node is two pointers, and it is embedded in the object like an ordinary field:

typedef struct dl_node {
    struct dl_node *next, *prev;
} dl_node;

A list is also a node, a sentinel: in an empty list it points to itself, and in a non-empty one its next is the first element, prev the last. The sentinel removes all special cases: every node has both a left neighbour and a right neighbour, and insertion and removal do without NULL checks:

static inline void dl_insert_before(dl_node *pos, dl_node *n)
{
    n->next = pos;
    n->prev = pos->prev;
    pos->prev->next = n;
    pos->prev = n;
}
static inline void dl_remove(dl_node *n)
{
    n->prev->next = n->next;
    n->next->prev = n->prev;
    n->next = n->prev = n;
}

Inserting before the sentinel means inserting at the end, after the sentinel — at the beginning. A removed node is closed onto itself: removing it again will not break anything. On M4 the function msg_drop, which removes a message from two lists and returns it to the pool, has not a single conditional branch.


76е.3 container_of: from the node to the object

A list stores node addresses, but objects are needed. Since the node lies inside the object at a known offset, the object's address is the node's address minus that offset:

#define container_of(ptr, type, member) ((type *)((char *)(ptr) - offsetof(type, member)))

An example is a message that sits in two lists at once: in the queue by deadline and in the list of its channel:

typedef struct {
    uint32_t due;      /* срок отправки */
    uint8_t channel;   /* канал */
    uint8_t len;
    uint8_t data[8];
    dl_node by_time;   /* место в очереди по сроку */
    dl_node by_chan;   /* место в списке своего канала */
} msg_t;

Three msg_t objects of 32 bytes with the fields due, channel, len, data and two embedded nodes by_time at offset 16 and by_chan at offset 24; the queue by deadline passes through by_time of all three, the list of channel 2 through by_chan of the first and the third; below is the container_of formula: the node address minus 16 or minus 24

On Cortex-M msg_t takes 32 bytes: after 14 bytes of data the compiler aligns the nodes to 4, by_time lies at offset 16, by_chan at 24. This is fixed in the source by compile-time checks:

_Static_assert(sizeof(msg_t) == 32, "сообщение с двумя узлами");
_Static_assert(offsetof(msg_t, by_time) == 16 && offsetof(msg_t, by_chan) == 24, "смещения узлов");

On a computer with 8-byte pointers the offsets are different, but container_of does not depend on that: on the bench the object was found correctly through both nodes. A mistake with container_of is dangerous in one way — naming the wrong field: the compiler will not check that a node from the queue by deadline is unwrapped through by_time and not through by_chan.


76е.4 Ordered insertion

The queue by deadline is kept ordered: a new message goes before the first one whose deadline is later. The comparison is by the sign of the difference, as for the timers in 76г, to survive a counter wraparound:

void msg_insert_by_time(dl_node *head, msg_t *m)
{
    dl_node *p = head->next;
    while (p != head) {
        STEP_HOOK();
        if ((int32_t)(container_of(p, msg_t, by_time)->due - m->due) > 0)
            break;
        p = p->next;
    }
    dl_insert_before(p, &m->by_time);
}

This is O(n), but for a queue of 16 messages it is not much: in the run an insertion passed 5.7 nodes on average, 15 at most. If there are dozens of elements and the worst case matters, the heap from 76г is taken instead of a list.


76е.5 A pool: O(1) allocation without a heap

A pool is a static array of objects and a singly linked list of free ones. No separate memory is needed for that list: nobody uses a free object, and its own by_time node serves as a link of the free list:

msg_t *pool_get(msg_pool_t *p)
{
    dl_node *n = p->free;
    if (!n)
        return NULL; /* пул пуст: отказ виден сразу, а не через неделю */
    p->free = n->next;
    if (++p->used > p->peak)
        p->peak = p->used;
    msg_t *m = container_of(n, msg_t, by_time);
    dl_init(&m->by_time);
    dl_init(&m->by_chan);
    return m;
}
void pool_put(msg_pool_t *p, msg_t *m)
{
    m->by_time.next = p->free;
    p->free = &m->by_time;
    p->used--;
}

Allocation and return are a few instructions: pool_put on M4 is 24 bytes and 7 instructions. All objects are the same size, so there is no fragmentation: any returned object suits the next request. The peak counter shows how many objects were needed at the worst moment — the pool size is chosen from it during testing.

A run of 100000 steps with a pool of 16 messages: 47557 handed out, failures — 7461 (the pool was empty, and this is visible at once, at the moment of the request), sent 42300, removed when a channel was disconnected 5241, peak occupancy — 16 of 16. After every step everything matched: the queue is ordered, every channel message sits in its own list, there are as many messages in the queue as in the channels and as were handed out from the pool, and handed out plus free is exactly 16.


76е.6 How this is done in FreeRTOS

The FreeRTOS kernel lists use the same technique with small differences. ListItem_t is an intrusive node embedded in the task control block: a task has two, one for the state list (ready, delayed, suspended), the other for the event wait list. Instead of container_of, the node stores a pointer to the owner pvOwner — four extra bytes per node, but without address arithmetic. The sentinel xListEnd sits in the list structure itself and has the largest key value, so the ordered insertion vListInsert always stops at it. Delayed tasks sit in the list by wake-up time — exactly like the messages in 76е.4.

This also shows why insertion into the delayed list in FreeRTOS is O(n), and why that is not a problem: there are usually a few to a few dozen tasks.


76е.7 Code and memory

Function code bytes M4 code bytes M0
msg_insert_by_time 48 46
pool_get 64 68
pool_put 24 24
msg_drop 56 54
pool_init 38 44

The memory of a pool of 16 messages is 16 × 32 = 512 bytes plus a pointer and two counters. Each message has two nodes — 16 bytes out of 32: an intrusive list is not free, but each node is needed exactly where the object sits in a list.


76е.8 When a list and when something else

Task Choice
objects are often removed from the middle, never accessed by index an intrusive doubly linked list
only a "came — left" queue a ring buffer — no pointers at all
the nearest by deadline is needed, dozens of elements a heap (76г)
lookup by key a hash table (76д)
objects of one size, no heap a pool with a free list

76е.9 Pitfalls

An object was removed from the list twice — the list "broke". After removal the node's pointers looked at the former neighbours, and the second removal overwrote their links. dl_remove closes the node onto itself: a repeated removal is harmless.

container_of with someone else's field. A node from the channel list was unwrapped through by_time — the result was an address 8 bytes off the object. The compiler does not see this; one field name per list and a check in the debug build.

An object was returned to the pool while it still sat in the queue. A couple of steps later the queue walked over a node that already serves as a link of the free list. Return to the pool only through a function that removes the object from everywhere (msg_drop).

The list is touched from a task and from an interrupt. Four pointer writes are not an atomic operation: an interrupt in the middle of an insertion will see a half-linked node. A critical section around insertion and removal (7).

A pool sized by eye. The peak occupancy was not measured, and a pool of 16 turned out too small under peak load: in the run there were 7461 failures. The peak counter and a test on the worst scenario.


76е.10 Summary

Next: section 76ж "A prefix tree for command parsing: AT commands and a console on a tree in flash" — how to recognise a command one byte at a time straight from UART reception without collecting the string in a buffer.

Open in the interactive handbook