Especially useful for device drivers, the kernel provides a few managed APIs for memory allocation. These are formally referred to as the device resource-managed or devres APIs (the link to kernel documentation on this is https://www.kernel.org/doc/Documentation/driver-model/devres.txt). They are all prefixed with devm_; though there are several of them, we will focus on only one common use case here – that of using these APIs in place of the usual k[m|z]alloc() ones. They are as follows:
- void * devm_kmalloc(struct device *dev, size_t size, gfp_t gfp);
- void * devm_kzalloc(struct device *dev, size_t size, gfp_t gfp);
The reason why these resource-managed APIs are useful is that there is no need for the developer to explicitly free the memory allocated by them. The kernel resource management framework guarantees that it will automatically free the memory buffer upon driver detach, or if a kernel...