检查 Linux 中 struct mutex 的所有者字段
Checking the owner field of struct mutex in Linux
我想检查一个锁定在内核中的 struct mutex
,谁是那个互斥量的所有者。
struct mutex {
atomic_long_t owner;
spinlock_t wait_lock;
#ifdef CONFIG_MUTEX_SPIN_ON_OWNER
struct optimistic_spin_queue osq; /* Spinner MCS lock */
#endif
struct list_head wait_list;
#ifdef CONFIG_DEBUG_MUTEXES
void *magic;
#endif
#ifdef CONFIG_DEBUG_LOCK_ALLOC
struct lockdep_map dep_map;
#endif
};
我从 kernel documentation 了解到:
Field owner actually contains struct task_struct * to the current lock
owner and it is therefore NULL if not currently owned.
是否有任何安全的方法将该字段与 current
进行比较?
Is there any way to compare that field to current?
从kernel/locking/mutex.c开始你可以使用这个功能:
/*
* Internal helper function; C doesn't allow us to hide it :/
*
* DO NOT USE (outside of mutex code).
*/
static inline struct task_struct *__mutex_owner(struct mutex *lock)
{
return (struct task_struct *)(atomic_long_read(&lock->owner) & ~MUTEX_FLAGS);
}
那我猜:
extern struct mutex *some_mutex;
extern struct task_struct *current;
__mutex_owner(some_mutex) == current;
如果你想实现递归互斥锁,那么你可以使用mutex_trylock_recursive函数:它的行为类似于mutex_trylock
,但是互斥锁的当前所有者允许调用这个函数。在那种情况下,它 returns 一个特殊值。
与__mutex_owner
一样,函数mutex_trylock_recursive
被标记为已弃用/"do not use"。可能有人不喜欢内核中递归互斥锁的想法。
我想检查一个锁定在内核中的 struct mutex
,谁是那个互斥量的所有者。
struct mutex {
atomic_long_t owner;
spinlock_t wait_lock;
#ifdef CONFIG_MUTEX_SPIN_ON_OWNER
struct optimistic_spin_queue osq; /* Spinner MCS lock */
#endif
struct list_head wait_list;
#ifdef CONFIG_DEBUG_MUTEXES
void *magic;
#endif
#ifdef CONFIG_DEBUG_LOCK_ALLOC
struct lockdep_map dep_map;
#endif
};
我从 kernel documentation 了解到:
Field owner actually contains struct task_struct * to the current lock owner and it is therefore NULL if not currently owned.
是否有任何安全的方法将该字段与 current
进行比较?
Is there any way to compare that field to current?
从kernel/locking/mutex.c开始你可以使用这个功能:
/*
* Internal helper function; C doesn't allow us to hide it :/
*
* DO NOT USE (outside of mutex code).
*/
static inline struct task_struct *__mutex_owner(struct mutex *lock)
{
return (struct task_struct *)(atomic_long_read(&lock->owner) & ~MUTEX_FLAGS);
}
那我猜:
extern struct mutex *some_mutex;
extern struct task_struct *current;
__mutex_owner(some_mutex) == current;
如果你想实现递归互斥锁,那么你可以使用mutex_trylock_recursive函数:它的行为类似于mutex_trylock
,但是互斥锁的当前所有者允许调用这个函数。在那种情况下,它 returns 一个特殊值。
与__mutex_owner
一样,函数mutex_trylock_recursive
被标记为已弃用/"do not use"。可能有人不喜欢内核中递归互斥锁的想法。