Welcome to the Linux Foundation Forum!

26. Modules - Refcount Trigger?


Watching through the demonstration video, I wonder, how does a module know or detect that it is being used by a process? I can't image that a process has 'I need module X' compiled into it, like an entry in the dynamic elf section.

Is that always just some heuristic, or is there a hard way to tell? Is it detected by syscalls the process makes? Or is it some resource count, ie. the kernel module counts when it allocates resources for a process?

Does the module get notified for each process that exits? Is the module responsible for the process refcount, or is it the kernel?

I probably don't need the fully-detailed explanation, but some more hints would be great. Thanks!

Best Answers

  • coop
    coop Posts: 915
    Answer ✓

    It varies a little bit according to what kind of module it is, but in most cases there is an "open(..)" call in the application when it first accesses the module (say to /dev/sd?? for example) which increases a reference count embedded in the "struct module" in the kernel for that device. The reference counter is decreased upon use of the system call "close()" or "release()" and the module cannot be unloaded when the reference count is not zero. There are exceptions. For example, the Ethernet drivers for you network card will generally show "0" for the number of applications in use. This permits you to shortly restart your network say without stopping every application that is using the network, as the network can handle interruptions.. The struct module also keeps track of every other module it references or that references it.

  • cfuchs
    cfuchs Posts: 15
    edited February 2022 Answer ✓

    Thanks, that makes sense for device drivers (I think the only module ever loaded/unloaded recently was nbd for qemu disk images). I've also found https://github.com/torvalds/linux/blob/master/include/linux/module.h#L529, where the refcount and dependency lists are declared, that looks like what you pointed at in the last sentence.

    Thanks again!


Upcoming Training