Re: MemoryFence()

Ni, Ray

I just read the link you provided. It recommends to use mutex semaphore spin lock over volatile.
But the funny thing here is we are talking about how to implement the mutex semaphore spin lock in edk2

Maybe we need to rely on built in atomic functions but not sure these are gcc only?

发件人: Andrew Fish <afish@...>
发送时间: Saturday, February 6, 2021 1:48:50 AM
收件人: Ni, Ray <>
抄送: Laszlo Ersek <lersek@...>; edk2 RFC list <>; Kinney, Michael D <michael.d.kinney@...>; Leif Lindholm (Nuvia address) <leif@...>; Ard Biesheuvel ( address) <ardb@...>; Dong, Eric <eric.dong@...>; Liming Gao (Byosoft address) <gaoliming@...>; Ankur Arora <ankur.a.arora@...>; Paolo Bonzini <pbonzini@...>
主题: Re: MemoryFence()

On Feb 5, 2021, at 12:25 AM, Ni, Ray <<>> wrote:

So if I understand correctly
1) volatile basically tells C to always read the memory. So it impacts the C memory model.
2) CompilerFence() tells the C serialize and complete everything before the barrier, and read memory again the 1st time after the barrier.
3) MemoryFence() is really dealing with speculative fetches and maybe coherency. Basically the CPU reordering things.
I agree with this summary.
Volatile using in MpInitLib or PiSmmCpu driver cannot be emitted because different CPU threads change the same memory content to synchronize with each other.
I don’t quite understand if removing “volatile” what mechanism can be used to force the compiler generating code that always reads from memory?


I agree the C definition of volatile is not thread safe.

I was doing some research on volatile and I realize the Linux kernel guides recommend against using volatile [1]. I think it has to do with people confusing volatile for being thread safe. So my guess is it is more of a coding standard to encourage people to use synchronization primitives. The primitives imply compiler fences which indirectly enforces the same behavior as volatile.



Andrew Fish


Join to automatically receive all group messages.