Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is linux' "mutex lock" implemented using "memory barrier"?

I was reading this where Robert Love mentioned that mutex is implemented using memory barrier but I am not able to see the memory barrier instructions being used in Linux implementation of mutex lock.

I was wondering if he was referring to mutex lock implementation in posix library which does use memory barrier instruction so that it doesn't get reordered with respect to the critical resource. Am I right?

like image 285
noman pouigt Avatar asked Dec 19 '22 22:12

noman pouigt


1 Answers

That Robert Love's answer is applicable to mutexes in any area.

Implementation in the linux kernel you refers uses __mutex_fastpath_lock, which do most the work and usually implementing using assembler code. E.g., on x86_64 its implementation could be:

 20 static inline void __mutex_fastpath_lock(atomic_t *v,
 21                                          void (*fail_fn)(atomic_t *))
 22 {
 23         asm_volatile_goto(LOCK_PREFIX "   decl %0\n"
 24                           "   jns %l[exit]\n"
 25                           : : "m" (v->counter)
 26                           : "memory", "cc"
 27                           : exit);
 28         fail_fn(v);
 29 exit:
 30         return;
 31 }

The key here is LOCK prefix (LOCK_PREFIX) before dec (decl) operation. On x86 LOCK prefix means atomicity and always implies full memory barrier.

like image 122
Tsyvarev Avatar answered Jan 09 '23 11:01

Tsyvarev