In Linux device driver development, the file_operations
structure uses struct module *owner
.
- What is the use of this structure when we always initialize it with
THIS_MODULE
? - When can this field be set to
NULL
?
In Linux device driver development, the file_operations
structure uses struct module *owner
.
THIS_MODULE
?NULL
?This field tells who is owner of struct file_operations
. This prevents module to get unloaded when it is in operation. When initialized with THIS_MODULE
current module holds the ownership on it.
Minimal runnable example
Whenever you create a kernel module, the kernel's build machinery generates a struct module
object for you, and makes THIS_MODULE
point to it.
This struct contains many fields, some of which can be set with module macros such as MODULE_VERSION
.
This example shows how to access that information: module_info.c
:
#include <linux/module.h>
#include <linux/kernel.h>
static int myinit(void)
{
/* Set by default based on the module file name. */
pr_info("name = %s\n", THIS_MODULE->name);
pr_info("version = %s\n", THIS_MODULE->version);
return 0;
}
static void myexit(void) {}
module_init(myinit)
module_exit(myexit)
MODULE_VERSION("1.0");
MODULE_LICENSE("GPL");
Dmesg outputs:
name = module_info
version = 1.0
Some MODULE_INFO
fields can also be "accessed" in the following ways:
cat /sys/module/module_info/version
modinfo /module_info.ko | grep -E '^version:'
Since the address of that struct module
object must be unique across all modules, it serves as a good argument for fops.owner
as mentioned at: https://stackoverflow.com/a/19468893/895245. Here is a minimal example of that usage.
Tested in Linux kernel 4.16 with this QEMU + Buildroot setup.
[1] struct module *owner is commonly used at some structures and is not an operation at all; it is a pointer to the module that "owns"the structure. This field is used to prevent the module from being unloaded while its operations are in use. Almost all the time, it is simply initialized to THIS_MODULE, a macro defined in < linux/module.h> .
.
[2] I would not recommend you to set it to null, because it may lead to driver malfunction and other problems. Instead, use the good practices of linux kernel development.
In some architectures the ".owner" was removed, so, make sure your distro and architecture still using it.
I hope it helps your understanding.
References: LDD3, kernel newbies.
file_operation
is one of the main structures that used to connect the device numbers and the file operations of a driver.
struct module *owner
which is not a function pointer at all but points to a structure module defined in the <linux/module.h>
.THIS_MODULE
, it holds the ownership of the module.struct module *owner
to THIS_MODULE
to prevent the module from getting unloaded while in use.