Skip to content
systemcoding.dev
Kernels

Declare a mutex statically with DEFINE_MUTEX

Define a file-scope kernel mutex with DEFINE_MUTEX(name), which needs no mutex_init() call and is ready before module init runs, on Linux 6.x.

1 min read
Summarize in AI

A lock that protects a global list or a module-wide counter exists for the whole life of the module, so there is nothing to initialise at run time. DEFINE_MUTEX(name) declares and initialises a struct mutex at compile time. There is no mutex_init() to forget and no window between load and init in which another path could use an uninitialised lock.

c
#include <linux/module.h>
#include <linux/mutex.h>

static DEFINE_MUTEX(demo_lock);
static int demo_counter;

static int demo_bump(void)
{
	int v;

	mutex_lock(&demo_lock);
	v = ++demo_counter;
	mutex_unlock(&demo_lock);
	pr_info("demo: counter is now %d\n", v);
	return v;
}
Text
demo: counter is now 1

For a mutex that lives inside a dynamically allocated structure the static form is not available, and mutex_init(&d->lock) is required before first use. That is the line people miss when they convert a global into a per-device field. With CONFIG_DEBUG_MUTEXES or lockdep, a mutex used without being initialised is reported at the first lock.

A mutex may sleep, so you cannot take it in an interrupt handler or under a spinlock, and the task that locked it must be the one that unlocks it. For those cases use a spinlock, declared the same way with DEFINE_SPINLOCK(name). See mutex design.

Share

More snippets

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.