mutex-design.txt 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  1. Generic Mutex Subsystem
  2. started by Ingo Molnar <mingo@redhat.com>
  3. updated by Davidlohr Bueso <davidlohr@hp.com>
  4. What are mutexes?
  5. -----------------
  6. In the Linux kernel, mutexes refer to a particular locking primitive
  7. that enforces serialization on shared memory systems, and not only to
  8. the generic term referring to 'mutual exclusion' found in academia
  9. or similar theoretical text books. Mutexes are sleeping locks which
  10. behave similarly to binary semaphores, and were introduced in 2006[1]
  11. as an alternative to these. This new data structure provided a number
  12. of advantages, including simpler interfaces, and at that time smaller
  13. code (see Disadvantages).
  14. [1] http://lwn.net/Articles/164802/
  15. Implementation
  16. --------------
  17. Mutexes are represented by 'struct mutex', defined in include/linux/mutex.h
  18. and implemented in kernel/locking/mutex.c. These locks use an atomic variable
  19. (->owner) to keep track of the lock state during its lifetime. Field owner
  20. actually contains 'struct task_struct *' to the current lock owner and it is
  21. therefore NULL if not currently owned. Since task_struct pointers are aligned
  22. at at least L1_CACHE_BYTES, low bits (3) are used to store extra state (e.g.,
  23. if waiter list is non-empty). In its most basic form it also includes a
  24. wait-queue and a spinlock that serializes access to it. Furthermore,
  25. CONFIG_MUTEX_SPIN_ON_OWNER=y systems use a spinner MCS lock (->osq), described
  26. below in (ii).
  27. When acquiring a mutex, there are three possible paths that can be
  28. taken, depending on the state of the lock:
  29. (i) fastpath: tries to atomically acquire the lock by cmpxchg()ing the owner with
  30. the current task. This only works in the uncontended case (cmpxchg() checks
  31. against 0UL, so all 3 state bits above have to be 0). If the lock is
  32. contended it goes to the next possible path.
  33. (ii) midpath: aka optimistic spinning, tries to spin for acquisition
  34. while the lock owner is running and there are no other tasks ready
  35. to run that have higher priority (need_resched). The rationale is
  36. that if the lock owner is running, it is likely to release the lock
  37. soon. The mutex spinners are queued up using MCS lock so that only
  38. one spinner can compete for the mutex.
  39. The MCS lock (proposed by Mellor-Crummey and Scott) is a simple spinlock
  40. with the desirable properties of being fair and with each cpu trying
  41. to acquire the lock spinning on a local variable. It avoids expensive
  42. cacheline bouncing that common test-and-set spinlock implementations
  43. incur. An MCS-like lock is specially tailored for optimistic spinning
  44. for sleeping lock implementation. An important feature of the customized
  45. MCS lock is that it has the extra property that spinners are able to exit
  46. the MCS spinlock queue when they need to reschedule. This further helps
  47. avoid situations where MCS spinners that need to reschedule would continue
  48. waiting to spin on mutex owner, only to go directly to slowpath upon
  49. obtaining the MCS lock.
  50. (iii) slowpath: last resort, if the lock is still unable to be acquired,
  51. the task is added to the wait-queue and sleeps until woken up by the
  52. unlock path. Under normal circumstances it blocks as TASK_UNINTERRUPTIBLE.
  53. While formally kernel mutexes are sleepable locks, it is path (ii) that
  54. makes them more practically a hybrid type. By simply not interrupting a
  55. task and busy-waiting for a few cycles instead of immediately sleeping,
  56. the performance of this lock has been seen to significantly improve a
  57. number of workloads. Note that this technique is also used for rw-semaphores.
  58. Semantics
  59. ---------
  60. The mutex subsystem checks and enforces the following rules:
  61. - Only one task can hold the mutex at a time.
  62. - Only the owner can unlock the mutex.
  63. - Multiple unlocks are not permitted.
  64. - Recursive locking/unlocking is not permitted.
  65. - A mutex must only be initialized via the API (see below).
  66. - A task may not exit with a mutex held.
  67. - Memory areas where held locks reside must not be freed.
  68. - Held mutexes must not be reinitialized.
  69. - Mutexes may not be used in hardware or software interrupt
  70. contexts such as tasklets and timers.
  71. These semantics are fully enforced when CONFIG DEBUG_MUTEXES is enabled.
  72. In addition, the mutex debugging code also implements a number of other
  73. features that make lock debugging easier and faster:
  74. - Uses symbolic names of mutexes, whenever they are printed
  75. in debug output.
  76. - Point-of-acquire tracking, symbolic lookup of function names,
  77. list of all locks held in the system, printout of them.
  78. - Owner tracking.
  79. - Detects self-recursing locks and prints out all relevant info.
  80. - Detects multi-task circular deadlocks and prints out all affected
  81. locks and tasks (and only those tasks).
  82. Interfaces
  83. ----------
  84. Statically define the mutex:
  85. DEFINE_MUTEX(name);
  86. Dynamically initialize the mutex:
  87. mutex_init(mutex);
  88. Acquire the mutex, uninterruptible:
  89. void mutex_lock(struct mutex *lock);
  90. void mutex_lock_nested(struct mutex *lock, unsigned int subclass);
  91. int mutex_trylock(struct mutex *lock);
  92. Acquire the mutex, interruptible:
  93. int mutex_lock_interruptible_nested(struct mutex *lock,
  94. unsigned int subclass);
  95. int mutex_lock_interruptible(struct mutex *lock);
  96. Acquire the mutex, interruptible, if dec to 0:
  97. int atomic_dec_and_mutex_lock(atomic_t *cnt, struct mutex *lock);
  98. Unlock the mutex:
  99. void mutex_unlock(struct mutex *lock);
  100. Test if the mutex is taken:
  101. int mutex_is_locked(struct mutex *lock);
  102. Disadvantages
  103. -------------
  104. Unlike its original design and purpose, 'struct mutex' is among the largest
  105. locks in the kernel. E.g: on x86-64 it is 32 bytes, where 'struct semaphore'
  106. is 24 bytes and rw_semaphore is 40 bytes. Larger structure sizes mean more CPU
  107. cache and memory footprint.
  108. When to use mutexes
  109. -------------------
  110. Unless the strict semantics of mutexes are unsuitable and/or the critical
  111. region prevents the lock from being shared, always prefer them to any other
  112. locking primitive.