Wednesday, January 13, 2016

Linux Mutex Internals

http://linuxkernelarticles.blogspot.in/2013/02/mutex-implementation-in-arm-architecture.html

Refer above blog for mutex implementation in ARM architecture. Here we will see the rest,

Basic Condition of Mutex:-
1) Only one task can hold the mutex at a time.
      struct mutex {
         ....
                     atomic_t count; //1: unlocked, 0: locked, negative: locked, possible waiters 
         ....
  }
2) Only the owner can unlock the mutex.
      struct mutex {
         struct task_struct *owner;
   }
3) Multiple unlocks are not permitted,
4) Recursive locking is not permitted,
5) A mutex object must be initialized via the API(mutex_init),
6) A mutex object must not be initialized via memset or copying,
7) Task may not exit with mutex held,
8) Memory areas where held locks reside must not be freed,
9) Held mutexes must not be reinitialized,
10) Mutexes may not be used in hardware or software interrupt contexts such as tasklets and timers.

How to Wakeup Other Process waiting for this mutex ?
1) All process waiting for this mutex lock, will be in struct mutex_waiter.list.
2) Get the 1st entry from the waist list & call wake_up_process(waiter->task);  {

           // Wakeup specific process
          p->state = TASK_WAKING;
          ttwu_queue(p, cpu); {

                    ttwu_do_activate(struct rq *rq, struct task_struct *p, int wake_flags) {
                               ttwu_activate(rq, p, ENQUEUE_WAKEUP | ENQUEUE_WAKING); {
                                     activate_task(rq, p, en_flags); // Enqueue the task in run queue
                                     p->on_rq = 1;
                               }
                   }
                   ttwu_do_wakeup(rq, p, wake_flags); {
                              p->state = TASK_RUNNING;
                   }

         }
}

Common Questions:-
1) Why spinlock variable(spinlock_t wait_lock;) is required in mutex structure?
     To avoid concurrent access to the mutex structure.

2) After holding the mutex that process can be preempted/process can sleep ?
     Yes. Holding mutex process can sleep.

3) Mutex held by process-1 executing in CPU-0, process-2 want the same mutex executing in CPU-1. How mutex unlock will wakeup process-2 ?
When kernel try to wakeup waiting process-2, first it will get CPU on which the process is executing

try_to_wake_up(struct task_struct *p, unsigned int state, int wake_flags) {
                    cpu = select_task_rq(p, p->wake_cpu, SD_BALANCE_WAKE, wake_flags);
                    ttwu_queue(p, cpu);
}

4) What is the difference b/w mutex, semaphore & spinlock ?


No comments:

Post a Comment