2010年8月17日星期二

Kernel Locking

  1. semaphores and mutex
    mechanism:
    the initial value of sema decides the most client can share the lock.
    Lock: if sema>0, sema--; else wait till sema>0 and lock
    Unlock: sema++,and if necessary, wake up waiting processes.
    --Zero: indicate that it can NOT be locked again.
    Mutex:
    initialize the sema to 1, so once one process lock the semaphore, it can not be access again.

  2. Spinlocks:
    mechanism(intended for multi-processor, but can be used in preemptive kernel system) :
    mutual, only have two status: “locked” and “unlocked”, operation must be in atomic mode.
    Caution:
    1.Any code must, be atomic while holding a spinlock.It cannot sleep.
    2.It's safe to disable interrupts( on local CPU only) while holding a spinlock.
    3.Spinlcok must be hold for the minimum time possible.

    Safe way to use spinlock:
    static DEFINE_SPINLOCK(xxx_lock);
    unsigned long flags;
    spin_lock_irqsave(&xxx_lock, flags);
    ... critical section here ..
    spin_unlock_irqrestore(&xxx_lock, flags);
  3. Mutex-- a new type
    compared to semaphore, the mutex consume less memory and cpu.
    Based on spinlocks, it can NOT be used from an interrput context, nor can they be unlocked from a different context that which acquire it.

API of Mutex:
DEFINE_MUTEX(name);

mutex_init(mutex);

void mutex_lock(struct mutex *lock);
int mutex_lock_interruptible(struct mutex *lock);
int mutex_trylock(struct mutex *lock);
void mutex_unlock(struct mutex *lock);
int mutex_is_locked(struct mutex *lock);
void mutex_lock_nested(struct mutex *lock, unsigned int subclass);
int mutex_lock_interruptible_nested(struct mutex *lock,
unsigned int subclass);

没有评论:

发表评论