Modules can be removed using the rmmod command but demand loaded modules are automatically removed from the system by kerneld when they are no longer being used. Every time its idle timer expires, kerneld makes a system call requesting that all unused demand loaded modules are removed from the system. The timer's value is set when you start kerneld, my kerneld checks every 180 seconds. So, for example, if you mount an iso9660 CD ROM and your iso9660 filesystem is a loadable module, then shortly after the CD ROM is unmounted, the iso9660 module will be removed from the kernel.
A module cannot be unloaded so long as other components of the kernel are depending on it. For example, you cannot unload the VFAT module if you have one or more VFAT file systems mounted. If you look at the output of lsmod , you will see that each module has a count associated with it. For example:
Module: #pages: Used by: msdos 5 1 vfat 4 1 (autoclean) fat 6 [vfat msdos] 2 (autoclean)The count is the number of kernel entities that are dependent on this module. In the above example, the vfat and msdos modules are both dependent on the fat module and so it has a count of 1. Both the vfat and msdos modules have 1 dependent, which is a mounted file system. If I were to load another VFAT file system then the vfat module's count would become 2. A module's count is held in the first longword of its image.
This field is slightly overloaded as it also holds the AUTOCLEAN and VISITED flags. Both of these flags are used for demand loaded modules. These modules are marked as AUTOCLEAN so that the system can recognize which ones it may automatically unload. The VISITED flag marks the module as in use by one or more other system components; it is set whenever another component makes use of the module. Each time the system is asked by kerneld to remove unused demand loaded modules it looks through all of the modules in the system for likely candidates. It only looks at modules marked as AUTOCLEAN and in the state RUNNING. If the candidate has its VISITED flag cleared then it will remove the module, otherwise it will clear the VISITED flag and go on to look at the next module in the system.
Assuming that a module can be unloaded, its cleanup routine is called to allow it to free up the kernel resources that it has allocated.
The module data structure is marked as DELETED and it is unlinked from the list of kernel modules. Any other modules that it is dependent on have their reference lists modified so that they no longer have it as a dependent. All of the kernel memory that the module needed is deallocated.