linux驱动程序编程中的devm_kzalloc()和kzalloc()有什么区别 [英] What is the difference between devm_kzalloc() and kzalloc() in linux driver programming

查看:1729
本文介绍了linux驱动程序编程中的devm_kzalloc()和kzalloc()有什么区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在设备驱动程序programmong中找到了devm_kzalloc()kzalloc().但是我不知道何时/何地使用这些功能.任何人都可以指定这些功能及其用法的重要性.

解决方案

kzalloc()kmalloc()一样分配内核内存,但是它也会对初始化的内存进行零初始化. devm_kzalloc()被管理kzalloc().分配有托管功能的内存与设备关联.从系统上卸下设备或卸载设备驱动程序后,该内存将自动释放.如果为设备分配了多个托管资源(内存或其他资源),则最后释放的资源将首先释放.

受管资源对于确保驱动程序正确运行(无论在任何时候初始化失败还是在成功移除设备之后成功进行初始化)方面都非常有帮助.

请注意,托管资源(无论是内存还是其他资源)应在负责探测设备的代码中使用.对于用于打开设备的代码,它们通常是错误的选择,因为可以在不断开系统连接的情况下关闭设备.关闭设备需要手动释放资源,这违反了托管资源的目的.

使用kfree()释放使用kzalloc()分配的内存.用devm_kzalloc()分配的内存会自动释放.可以使用devm_kfree()释放它,但是通常这表明托管内存分配不适合该任务.

I have found devm_kzalloc() and kzalloc() in device driver programmong. But I don't know when/where to use these functions. Can anyone please specify the importance of these functions and their usage.

解决方案

kzalloc() allocates kernel memory like kmalloc(), but it also zero-initializes the allocated memory. devm_kzalloc() is managed kzalloc(). The memory allocated with managed functions is associated with the device. When the device is detached from the system or the driver for the device is unloaded, that memory is freed automatically. If multiple managed resources (memory or some other resource) were allocated for the device, the resource allocated last is freed first.

Managed resources are very helpful to ensure correct operation of the driver both for initialization failure at any point and for successful initialization followed by the device removal.

Please note that managed resources (whether it's memory or some other resource) are meant to be used in code responsible for the probing the device. They are generally a wrong choice for the code used for opening the device, as the device can be closed without being disconnected from the system. Closing the device requires freeing the resources manually, which defeats the purpose of managed resources.

The memory allocated with kzalloc() should be freed with kfree(). The memory allocated with devm_kzalloc() is freed automatically. It can be freed with devm_kfree(), but it's usually a sign that the managed memory allocation is not a good fit for the task.

这篇关于linux驱动程序编程中的devm_kzalloc()和kzalloc()有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆