3
votes

Lets say my kernel module have the init and exit function bellow:

module_init(init_module);
module_exit(cleanup_module);

Can the kernel module be removed, thus calling cleanup_module(), before the module init has completed/while init_module() is being executed?

3

3 Answers

2
votes

In module.c do_init_module does a module_put AFTER calling init_module, so I assume somewhere it has a reference to the module. https://elixir.bootlin.com/linux/v5.9-rc7/source/kernel/module.c#L3658

delete_module checks the refcount in try_stop_module BEFORE calling free_module. https://elixir.bootlin.com/linux/v5.9-rc7/source/kernel/module.c#L1025 module_mutex prevents simultaneous changes to the structures involved.

It looks like root can certainly call rmmod while init is running. If it happens before the put, it will fail. If it happens after the put, it will succeed. Either way, no incorrect operation will occur in the kernel (unless force operation is used, as Vijay points out).

0
votes

i believe that if the option CONFIG_MODULE_FORCE_UNLOAD was set when you built your kernel then it is possible to forcefully remove the module using rmmod -f or modprobe

0
votes

If the module init handler returns an error, the module exit handler won't be called. This implies that the module init handler has to return before the module exit handler can be called.