Linux中的devm_kmalloc()是设备驱动程序用来向内核申请一块内存,当设备驱动程序被卸载时,内存会被自动释放。devm_kfree()用来释放由devm_kmalloc()分配的内存。
1、devm_kmalloc()
#define __malloc __attribute__((__malloc__))
/* managed devm_k.alloc/kfree for device drivers */
extern void *devm_kmalloc(struct device *dev, size_t size, gfp_t gfp) __malloc;
static inline void *devm_kzalloc(struct device *dev, size_t size, gfp_t gfp)
{/*向内核申请一块内存,当设备驱动程序被卸载时,内存会被自动释放*/
return devm_kmalloc(dev, size, gfp | __GFP_ZERO);
}
2、devm_kfree()
//检查addr,若addr位于“.rodata”中,则返回TRUE;
static inline bool is_kernel_rodata(unsigned long addr)
{
return addr >= (unsigned long)__start_rodata && addr < (unsigned long)__end_rodata;
}
#define likely(x) __builtin_expect(!!(x), 1) /*如果x是1,则返回1*/
#define unlikely(x) __builtin_expect(!!(x), 0) /*如果x是0,则返回1*/
int devres_destroy(struct device *dev, dr_release_t release, dr_match_t match, void *match_data)
{
void *res;
res = devres_remove(dev, release, match, match_data);//找到一个设备资源并删除它
if (unlikely(!res)) return -ENOENT;
devres_free(res);//释放设备资源数据
return 0;
}
//释放由devm_kmalloc()分配的内存,p指向要释放的内存,这个内存属于dev设备
void devm_kfree(struct device *dev, const void *p)
{
int rc;
/* Special case: pointer to a string in .rodata returned by devm_kstrdup_const().*/
if (unlikely(is_kernel_rodata((unsigned long)p))) return;
//检查p,若p位于“.rodata”中,则返回TRUE,unlikely(TRUE)不执行;
rc = devres_destroy(dev, devm_kmalloc_release,devm_kmalloc_match, (void *)p);
WARN_ON(rc);
}