Search code examples
linux-kernellinux-device-driverdevice-driver

how do we use kmalloc in linux driver code


How will I come to know that where exactly or at what point I should use the kmalloc() to allocate a memory to the device in the device driver?

Is it during initialization or during open? As in malloc,wil kmalloc allocates memory dynamically?


Solution

  • In general, you can use kmalloc() when you need physically contigous memory in kernel space. You can use this during init/open depending on your use case. If you kmalloc in init() but never use the device, then memory allocated is waste. If kmalloc is used in open(), memory allocated is actually used because memory is allocated only if device is used.

    Also, note that you can use vmalloc() in kernel in case you are not in need of physically contigous memory allocation.