Skip to content
Advertisement

Prevent removal of busy kernel module

I have a simple kernel module that creates a character devices and does nothing with it.

I wrote this user-space program that tests the character device.

int main()
{
    int fd;

    fd = open("/dev/ebbchar", O_RDWR);
    if (fd < 0)
        err(1, "open");

    sleep(10);

    ret = close(fd);
    if (ret < 0)
        err(1, "close");
}

The program exits after 10 seconds.

But if in the meantime I remove the module with rmmod or modprobe, then after 10 seconds the program segfaults or hangs, and there is a kernel oops.

How can I cause rmmod to fail, or is there a method to safely remove a module?

Could my module, in its __exit function, close the file descriptor?

I assume that the crash is caused by the close() function which indirectly calls the release callback in the characters file operations, with that release function not existing anymore because the module was removed.

The source of the kernel module can be found here (search for Listing 2).

Advertisement

Answer

IIRC you need to set .owner = THIS_MODULE in the file operations structure so that the module’s reference count gets handled correctly.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement