Skip to content

[Question] Implementation of Thread.VolatileRead #40444

Closed

Description

@8ggmaker

Sorry that I don't know whether it is the proper place to ask this:
I know that now Thread.VolatileRead is wrapper of Volatile.Read, it is different from .NETFramework, does Thread.VolatileRead (.NETFramework) load variables from memory instead of registers by using [MethodImpl(MethodImplOptions.NoInlining)]:

[MethodImplAttribute(MethodImplOptions.NoInlining)] // disable optimizations
public static int VolatileRead(ref int address)
{
    int ret = address;
    MemoryBarrier(); // Call MemoryBarrier to ensure the proper semantic in a portable way.
    return ret;
}

I think memory barrier here is for preventing reordering, and the read of the latest value is guaranteed by 'NoInling' ?
I have tested with code below:

    class Program
   {

      public static int result;
      public static int finished;

      static void Thread2()
      {
         result = 143;
         finished = 1;
      }

      static void Main()
      {
         finished = 0;

         // Run Thread2() in a new thread
         new Thread(new ThreadStart(Thread2)).Start();

         // Wait for Thread2 to signal that it has a result by setting
         // finished to 1.
         for (; ; )
         {
            if (TestVolatileRead(ref finished)==1)
            {
               Console.WriteLine("result = {0}", result);
               break;
            }
         }
      }

      [MethodImpl(MethodImplOptions.NoInlining)]
      static int TestVolatileRead(ref int address)
      {
         int ret = address;
         Thread.MemoryBarrier(); // Call MemoryBarrier to ensure the proper semantic in a portable way.
         return ret;
      }
   }

And if I remove 'NoInlining' and run in Release mode, the program sometimes will be endless because of read finished from register is always 0.

Could anyone help me figure it out, Thanks.

Activity

  1. added
    untriaged
    on Aug 6, 2020
  2. Dotnet-GitSync-Bot commented on Aug 6, 2020

    @Dotnet-GitSync-Bot
    Collaborator

    I couldn't figure out the best area label to add to this issue. If you have write-permissions please help me learn by adding exactly one area label.

  3. changed the title [-][Questions] Implementation of Thread.VolatileRead[/-] [+][Question] Implementation of Thread.VolatileRead[/+] on Aug 6, 2020
  4. added
    question
    on Aug 6, 2020
  5. danmoseley commented on Aug 6, 2020

    @danmoseley
    Contributor
  6. 8ggmaker commented on Aug 6, 2020

    @8ggmaker
    MemberAuthor

    If we don't set NoInlining to TestVolatieMethod, we need to change the implementation to:

      static int TestVolatileRead(ref int address)
          {
             Thread.MemoryBarrier(); 
             int ret = address;
             Thread.MemoryBarrier(); // Call MemoryBarrier to ensure the proper semantic in a portable way.
             return ret;
          }

    the first memory barrier is to get the latest value, and the second for preventing reodering, is it right?

  7. added this to the Future milestone on Aug 6, 2020
  8. removed
    untriaged
    on Aug 6, 2020
  9. john-h-k commented on Aug 7, 2020

    @john-h-k
    Contributor

    Yeah so this is the old .NET Framework impl, and it is kinda... horrible. In .NET Core, the VolatileRead methods simply forward forwards to Volatile, which are intrinsics that use the volatile. prefix in IL, which causes the runtime to do everything correctly (insert barriers where necessary on ARM/MIPS, and prevent caching optimisations).

    It appears they don't do this in framework, presumably because they didn't do IL rewriting like .NET Core does for Volatile, Unsafe, Interlocked, etc. Though this is complete guess work because the runtime isn't open source for framework.

    So instead they just insert a full memory barrier, which does achieve volatile semantics (acquire and release semantics for reads and writes to be specific, iirc from ECMA), but is complete overkill, and not great for perf. On x86/64, acquire/release semantics are implicit, and so the barrier is, I believe, entirely unnecessary and just a waste of 100 cycles. The NoInlining is to prevent the JIT doing constant folding or reading from locals - it doesn't necessarily have to be a register, but the idea is if it was inlined the JIT could cache it in some form, and preventing inlining stops that. (putting a volatile. prefix on the read prevents the JIT using a cached version and is why the .NET Core impl doesn't need NoInlining)

    If we don't set NoInlining to TestVolatieMethod, we need to change the implementation to:

    I don't think this will actually fix it. Without the volatile prefix, you need to prevent inlining or the JIT could local cache it, even with a memory barrier, I think

  10. 8ggmaker commented on Aug 7, 2020

    @8ggmaker
    MemberAuthor

    @john-h-k Thanks for your explanation.
    And I have used SharpLab to see the JIT ASM of this code, the core part is the if statement check of

    if (TestVolatileRead(ref finished))
    1. Platform: .NET Framework (X86), Without NoInling:
        L004c: mov eax, [0x2f4b3070]
        L0052: lock or dword [esp], 0x0
        L0057: cmp eax, 0x1
        L005a: jnz L004c
    

    seem it is safe because it does not cache the value, and load each time (L004c).
    2. Platform: .NET Framework (X64), Without NoInling:

        L006f: mov ecx, [rip+0xd1cfb]
        L0075: mov eax, ecx
        L0077: lock or dword [rsp], 0x0
        L007c: cmp eax, 0x1
        L007f: jnz L0075
    

    It caches the value in ecx and cmp the same value, it is not safe.
    And if we add another memory barrier before the assignment statement:

      static int TestVolatileRead(ref int address)
      {
         Thread.MemoryBarrier(); 
         int ret = address;
         Thread.MemoryBarrier(); // Call MemoryBarrier to ensure the proper semantic in a portable way.
         return ret;
      }
    1. Platform: .NET Framework (X64), More memory barrier, Without NoInlining:
        L006f: lock or dword [rsp], 0x0
        L0074: mov ecx, [rip+0xd1cf6]
        L007a: lock or dword [rsp], 0x0
        L007f: cmp ecx, 0x1
        L0082: jnz L006f
    

    It is safe, because it load value each time (L0074).

    If we change finished to volatile, and just use finished==1 to do check:
    4. Platform: .NET Framework, Volatile field, no memory barrier:

        L006f: cmp dword [rip+0xd1cfa], 0x1
        L0076: jnz L006f
    

    It is safe by loading value each time. But I have a question about instruction reordering:

     static void Thread2()
     {
        result = 143;
        finished = 1;
     }

    this method is converted to:

        L0000: mov dword [0x2f38306c], 0x8f
        L000a: mov byte [0x2f383070], 0x1
        L0011: ret
    

    and whether finished is volatile or not, the instructions are same, how it prevents reordering to avoid finished variable be assigned before result.

  11. kouvel commented on Aug 11, 2020

    @kouvel
    Contributor

    Looks like this repros in .NET Core too. Regarding:

        L006f: mov ecx, [rip+0xd1cfb]
        L0075: mov eax, ecx
        L0077: lock or dword [rsp], 0x0
        L007c: cmp eax, 0x1
        L007f: jnz L0075
    

    The memory load appears to have been hoisted outside the loop, shouldn't the memory barrier have prevented that? Moving to CodeGen area for now.

    whether finished is volatile or not, the instructions are same, how it prevents reordering to avoid finished variable be assigned before result.

    Typically stores are not reordered, but to be perfectly correct finished = 1 probably should be a volatile write instead. Otherwise it is theoretically possible that finished == 1 would be seen and result == 0.

  12. added
    area-CodeGen-coreclr
    and removed on Aug 11, 2020
  13. removed this from the Future milestone on Aug 11, 2020
  14. 1 remaining item

  15. kouvel commented on Aug 12, 2020

    @kouvel
    Contributor

    I think memory barrier before the assignment can prevent this, but the implementation of .NET Framework is after assignment (I think this is for preventing reorder).

    Because it's a loop there is a memory barrier before the load too (on subsequent iterations of the loop). So while the memory load for the first loop iteration could be hoisted out of the loop, subsequent iterations should be loading from memory I think.

  16. kouvel commented on Aug 12, 2020

    @kouvel
    Contributor

    but the implementation of .NET Framework is after assignment (I think this is for preventing reorder)

    For a volatile load the memory barrier is after the load to ensure that any subsequent loads are at least as recent as the volatile load.

  17. 8ggmaker commented on Aug 12, 2020

    @8ggmaker
    MemberAuthor

    I think memory barrier before the assignment can prevent this, but the implementation of .NET Framework is after assignment (I think this is for preventing reorder).

    Because it's a loop there is a memory barrier before the load too (on subsequent iterations of the loop). So while the memory load for the first loop iteration could be hoisted out of the loop, subsequent iterations should be loading from memory I think.

    I got you point, because there is a loop, so the next time it should load from memory, but the instructions generated load the value to register out of the loop, and each time it loads from ecx register, it is still the cached value

    L006f: mov ecx, [rip+0xd1cfb]
    L0075: mov eax, ecx
    L0077: lock or dword [rsp], 0x0
    L007c: cmp eax, 0x1
    L007f: jnz L0075
    

    If the last line is jnz L006f, I think it should be right

  18. added and removed
    question
    on Aug 12, 2020
  19. AndyAyersMS commented on Aug 13, 2020

    @AndyAyersMS
    Member

    cc @dotnet/jit-contrib

    Looking at what the jit does. Here's the Loop body

    ------------ BB02 [01C..029) -> BB02 (cond), preds={BB01,BB02} succs={BB03,BB02}
    
    ***** BB02
    STMT00016 (IL 0x01C...  ???)
    N004 (  4, 12) [000058] -A--G---R---              *  ASG       int    <l:$101, c:$340>
    N003 (  1,  1) [000057] D------N----              +--*  LCL_VAR   int    V05 tmp5         d:1 <l:$101, c:$340>
    N002 (  4, 12) [000055] *---G-------              \--*  IND       int    <l:$101, c:$340>
    N001 (  2, 10) [000054] ------------                 \--*  CNS_INT(h) byref  0x7ffa3802c388 static Fseq[finished] $c8
    
    ***** BB02
    STMT00017 (IL 0x01C...  ???)
    N001 (  1,  1) [000061] -A--G-------              *  MEMORYBARRIER void  
    
    ***** BB02
    STMT00007 (IL   ???...  ???)
    N004 (  5,  5) [000026] ------------              *  JTRUE     void  
    N003 (  3,  3) [000025] N------N-U--              \--*  NE        int    <l:$3c1, c:$3c0>
    N001 (  1,  1) [000059] ------------                 +--*  LCL_VAR   int    V05 tmp5         u:1 (last use) <l:$101, c:$340>
    N002 (  1,  1) [000024] ------------                 \--*  CNS_INT   int    1 $43
    

    The jit's will hoist the load out of the loop:

    optHoistLoopCode for loop L00 <BB02..BB02>:
      Loop body does not contain a call
    
      USEDEF  (1)={V05}
      INOUT   (0)={}
      LOOPVARS(0)={}
        optHoistLoopBlocks BB02 (weight=  8   ) of loop L00 <BB02..BB02>, firstBlock is true
    
    Hoisting a copy of [000055] into PreHeader for loop L00 <BB02..BB02>:
    N002 (  4, 12) [000055] *---G-------              *  IND       int    <l:$101, c:$340>
    N001 (  2, 10) [000054] ------------              \--*  CNS_INT(h) byref  0x7ffa3802c388 static Fseq[finished] $c8
    
    New Basic Block BB04 [0006] created.
    
    Created PreHeader (BB04) for loop L00 (BB02 - BB02), with weight = 1   
    This hoisted copy placed in PreHeader (BB04):
                   [000083] ----G-------              *  COMMA     void  
         (  4, 12) [000080] *---G--H----              +--*  IND       int    <l:$101, c:$340>
         (  2, 10) [000081] -------H----              |  \--*  CNS_INT(h) byref  0x7ffa3802c388 static Fseq[finished] $c8
                   [000082] ------------              \--*  NOP       void  
    

    Surprised we'd hoist like this with (or without) the memory barrier. I thought we treated statics as implicitly volatile.

    Resulting loop may not terminate

    G_M27646_IG03:
           8BC1                 mov      eax, ecx
           F0                   lock
           830C2400             or       dword ptr [rsp], 0
           83F801               cmp      eax, 1
           75F4                 jne      SHORT G_M27646_IG03
    

    Note using the actual Thread.VolatileRead works as expected; codegen for the loop is

    G_M27646_IG03:
           833DD2331E0001       cmp      dword ptr [(reloc)], 1
           75F7                 jne      SHORT G_M27646_IG03
    
  20. briansull commented on Aug 13, 2020

    @briansull
    Contributor

    A memory barrier should block any expression from being hoisted before it.

    I will take a look.

  21. self-assigned this
    on Aug 13, 2020
  22. briansull commented on Aug 14, 2020

    @briansull
    Contributor

    This issue is now fixed with #40821
    And I added a test case derived from the test here

  23. kouvel commented on Aug 14, 2020

    @kouvel
    Contributor

    Thanks! Would the fix be ported to .NET Framework too?

  24. briansull commented on Aug 14, 2020

    @briansull
    Contributor

    I would say that this is unlikely to meet the bar to be ported to the desktop .NET Framework.

  25. kouvel commented on Aug 14, 2020

    @kouvel
    Contributor

    Oh ok. Using Thread.VolatileRead or Volatile.Read is working as expected in .NET Framework 4.8 (the former has the NoInlining attribute).

  26. briansull commented on Aug 14, 2020

    @briansull
    Contributor

    The fix address a missing check for a Thread.MemoryBarrier()
    All of the other memory ordering checking instructions were already covered by the current code.

  27. ghost locked as resolved and limited conversation to collaborators on Dec 7, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

area-CodeGen-coreclrbug

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions