Search code examples
linuxkernelmmapdynamic-memory-allocation

Proper freeing and unmapping of kernel memory


I am writing a Linux driver that allocates some memory and the user space application mmap()s that memory.

Now I am writing the exit handler for that module, and I am trying to figure out what are some safe assumptions.

First of all, is it safe to assume when a kernel module exit handler is called that all of the memory is unmapped (whether by the application or by the kernel)? Or do I have to do a manually unmap in the kernel driver before freeing the memory?

I ask this since the kernel should know if the module is exiting and the kernel also handles the unmapping process. If the kernel handles the unmapping before the exit handler is called, then I can just free up the memory. If this is true and if the userspace application tried to access that memory, then the application would segmentation fault. This would be because the virtual addresses either no longer point to valid physical memory or the process does not have permission to access the virtual addresses on that page (Assuming the kernel unmapped the memory). The same would occur if the kernel driver unmapped the memory. Is this true?


Solution

  • It is not safe to exit at this stage. Just deny unloading.

    This is not automatic, you have to increase your module use count when process do a mmap().

    If you want to be rude, kill the user process.