【问题标题】:Regarding semaphore up() and mutex_unlock() in linux kernel关于linux内核中的信号量up()和mutex_unlock()
【发布时间】:2018-02-09 09:49:30
【问题描述】:

我想知道为什么我们可以在中断上下文中使用信号量 up() 而互斥锁的相同变体,即 mutex_unlock() 不能在中断上下文中使用。 下面是来自内核的 sn-p

/**
* mutex_unlock - release the mutex
* @lock: the mutex to be released
*
* Unlock a mutex that has been locked by this task previously.
*
* This function must not be used in interrupt context. Unlocking
* of a not locked mutex is not allowed.
*
* This function is similar to (but not equivalent to) up().
*/
void __sched mutex_unlock(struct mutex *lock)
{
  #ifndef CONFIG_DEBUG_LOCK_ALLOC
  if (__mutex_unlock_fast(lock))
    return;
#endif
__mutex_unlock_slowpath(lock, _RET_IP_);
}EXPORT_SYMBOL(mutex_unlock);


 /**
 * up - release the semaphore
* @sem: the semaphore to release
*
* Release the semaphore.  Unlike mutexes, up() may be called from any
* context and even by tasks which have never called down().
*/
void up(struct semaphore *sem)
{
  unsigned long flags;

  raw_spin_lock_irqsave(&sem->lock, flags);
  if (likely(list_empty(&sem->wait_list)))
    sem->count++;
  else
     __up(sem);
  raw_spin_unlock_irqrestore(&sem->lock, flags);
}
EXPORT_SYMBOL(up);

【问题讨论】:

    标签: linux-kernel mutex semaphore


    【解决方案1】:

    mutex_unlock 采用 mutex-internal spinlock in a non-irq-safe fashion - 例如如果设置了CONFIG_PREEMPT_RTraw_spin_lock 可能会休眠 - 因此,如果时机合适,您在 IRQ 上下文中的 mutex_unlock 将死锁。

    【讨论】:

    • raw_spin_lock may sleep if CONFIG_PREEMPT_RT is set - 如果我没记错的话,spin_lock 函数根本不会禁用中断,并且禁止从 IRQ 调用它(因为死锁,你是对的)。配置CONFIG_PREEMPT_RT与此处无关。
    • mutex_unlock 通常不是 irq-safe。我只是举了一个例子。
    猜你喜欢
    • 2017-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-02
    • 2012-11-19
    • 1970-01-01
    • 1970-01-01
    • 2019-07-27
    相关资源
    最近更新 更多