作用 函數(shù) devm_kzalloc() 和kzalloc()一樣都是內(nèi)核內(nèi)存分配函數(shù),但是devm_kzalloc()是跟設(shè)備(device)有關(guān)的,, 當(dāng)設(shè)備(device)被detached或者驅(qū)動(driver)卸載(unloaded)時,,內(nèi)存會被自動釋放。另外,,也可以通過函數(shù) devm_kfree()手動釋放,。 而kzalloc()則需要手動釋放(使用kfree()),但如果工程師檢查不仔細(xì),,則有可能造成內(nèi)存泄漏,。 格式 static inline void * devm_kzalloc(struct device * dev,,size_t size,gfp_t gfp) { return devm_kmalloc(dev,,size,,gfp | __GFP_ZERO); } void * devm_kmalloc(struct device *dev, size_t size, gfp_t gfp) { struct devres *dr;
dr = alloc_dr(devm_kmalloc_release, size, gfp, dev_to_node(dev)); if (unlikely(!dr)) return NULL; set_node_dbginfo(&dr->node, "devm_kzalloc_release", size); devres_add(dev, dr->data); return dr->data; } EXPORT_SYMBOL_GPL(devm_kmalloc); void devm_kfree(struct device * dev,void * p) { int rc; rc = devres_destroy(dev,,devm_kmalloc_release,,devm_kmalloc_match,p); WARN_ON(RC); } EXPORT_SYMBOL_GPL(devm_kfree); 示例 struct s3c2440_i2c_dev { struct device *dev; void __iomem *base; struct i2c_msg *msg; u32 frequency; int speed_mode; int slave_addr; struct i2c_adapter adap; }; static int s3c2440_i2c_probe(struct platform_device *pdev) { struct s3c2440_i2c_dev *i2c_dev; struct i2c_adapter *adap; struct device *dev = &pdev->dev; struct resource *res; i2c_dev = devm_kzalloc(&pdev->dev, sizeof(struct s3c2440_i2c_dev), GFP_KERNEL); if(!i2c_dev) return -ENOMEM;
... } |
|