Linux kref使用简介

博客介绍了在Linux内核中,kref_get和kref_put操作必须交替进行以确保线程安全。通过一个简单的锁机制(如disconnect_sem)来防止open()和disconnect()之间的竞态条件,从而保证kref引用计数的正确性。该规则对于内核代码的正确执行至关重要。
摘要由CSDN通过智能技术生成

作者:Greg Kroah-Hartman

原文地址:http://www.kroah.com/linux/talks/ols_2004_kref_talk/

3 rules of use中关于第3点使用规则的说明:

If the code wanting to access the variable,
does not have a valid reference, then it
needs to serialize with a place within the
code where the last call to kref_put put
could happen.(红色表示断句)
对上面这段英文简要解释就是:一个内核
线程调用 kref_get之前一定要有kref_put的
调用(本线程或其他共享kref的线程),使得
kref_get和kref_put调用呈交替串行的状态。
 
This third rule can not be emphasized enough.
The only reason that the struct kref can
work without any internal locks is because a
call to kref_get can not happen at the same
time that kref_put is happening. In order to
ensure this, a simple lock for the driver or sub
system that owns the specifific struct kref
reference can be used.See the Exapmle blow.
 
/* prevent races between open() and disconnect() */
static DECLARE_MUTEX (disconnect_sem);
static int skel_open(struct inode *inode, struct file *file)
{
    struct usb_skel *dev;
    struct usb_interface *interface;
    /* prevent disconnects */
    down (&disconnect_sem);
    interface = usb_find_interface(&skel_driver, iminor(inode));
    dev = usb_get_intfdata(interface);
    /* increment our usage count for the device */
    kref_get(&dev->kref);
    up(&disconnect_sem);
    ...
}
static void skel_disconnect(struct usb_interface *interface)
{
    struct usb_skel *dev;
    int minor = interface->minor;
    /* prevent skel_open() from racing skel_disconnect() */
    down (&disconnect_sem);
    dev = usb_get_intfdata(interface);
    usb_set_intfdata(interface, NULL);
    /* give back our minor */
    usb_deregister_dev(interface, &skel_class);
    /* decrement our usage count */
    kref_put(&dev->kref);
    up(&disconnect_sem);
}
Example: Using a lock to ensure safe access to kref_put

 

 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

denglin12315

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值