I saw many times that kernel keeps kernel module with reference count of 0 in a
running system until explicit rmmod command is entered/
Is there any way to require that unused module will be removed from kernel by
the kernel itself ?
No, because that's a really good way to shoot yourself in the foot.
Hint 1: What's the refcount the instant after modprobe finishes? Even if it's being
auto-probed by modprobe because it's a pre-req module for the one that modprobe
has been asked to load, there's a race condition.
lsmod | grep dell
dell_laptop 32768 0
dell_smbios 20480 1 dell_laptop
So if smbios got loaded due to a 'modprobe dell_laptop', the refcount will
still be 0 for an instant, and it gets auto-rmmod'ed before dell_laptop can try
(and then fail) to load)
Hint 2:
What will break if that dell_laptop module gets auto-rmmod'ed?
The *correct* solution here is to have a userspace daemon that cleans up if you *really*
care about a module being unloaded. Except for the beached-whale module from NVidia
that's 14M in size, most modules are only 8K to 200K or so in size - if you're really that
stressed for RAM, you're probably an embedded system and have *bigger* things to worry
about.
Now, there's *other* good reasons to want to remove a module - for instance, only have
certain security-related modules loaded when a security USB widget is plugged in, for
example, or time-of-day restrictions on when the feature(s) provided by a module are
available. But that sort of thing is best done from userspace, not "when the refcount
reaches zero".
So the question becomes: What actual problem are you trying to solve by doing an
auto-rmmod of a module? There's almost certainly a better solution....