What is the significance of THIS_MODULE in Linux kernel module drivers?

流过昼夜 提交于 2019-12-09 10:34:03

问题


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?

回答1:


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




回答2:


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.




回答3:


[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.



来源:https://stackoverflow.com/questions/19467150/what-is-the-significance-of-this-module-in-linux-kernel-module-drivers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!