runtime icon indicating copy to clipboard operation
runtime copied to clipboard

Changing process affinity from 1 to N cores causes memory corruption and deadlocks

Open GPSnoopy opened this issue 7 years ago • 13 comments

To reproduce the problem

  • Launch a process with its initial thread affinity pinned to 1 core.
  • Process unpins itself from 1 core to multiple cores.
  • Process runs several asynchronous Tasks.
  • Process will randomly experience memory corruption (including deadlocks and spurious exceptions).

We suspect the problem has been introduced in .NET 4.8 as well as .NET Core 2.1 (or earlier).

Notes

  • Confirmed to happen on Windows 7, Windows 10.
  • Confirmed to happen on .NET Framework 4.8, .NET Core 2.1, .NET Core 3.0.
  • Confirmed not to happen on .NET Framework 4.7 (as long as .NET Framework 4.8 has not been installed on the machine).
  • The more tasks are started, the more likely it will go wrong.
  • Setting initial affinity to 0x0001 (rather than 0x0002) fails to reproduce the problem.
  • Subsequent affinity needs to be any number of cores other than 1 (0x0FFF being used here as the test machine had 12 cores, you will need to switch to a smaller mask if your machine has less cores).

How come we are doing this When submitting a job to our internal compute farm, its process gets assigned to the specific CPU cores allocated for the job to run on. Most jobs only request one CPU core, therefore their affinity mask gets set to one core.

In the case of our GPU compute farm, the CPUs are not the limiting resource. Instead we want to pin the process to the CPU cores closest to the GPU we've been assigned to. Because our farm scheduler does not seem to be able to understand the complexity of GPU and NUMA node topologies., we apply the logic above once the job has started from within the job process itself.

GPSnoopy avatar Oct 02 '19 14:10 GPSnoopy

Adding reproducible example targetting net48, netcoreapp2.1 and netcoreapp3.0: Net48Tester_20191002.zip

Typically the sub-process will hang after a few runs (takes a few seconds per try):

Framework: Location: C:\Windows\Microsoft.NET\Framework64\v4.0.30319\mscorlib.dll
Framework: ImageRuntimeVersion: v4.0.30319
Framework: full version: 4.0.0.0
Framework: ProductVersion: 4.8.4010.0
JIT Compiler: 'clrjit.dll' 4.8.4010.0 built by: NET48REL1LAST_B
Environment.ProcessorCount: 16
CPU affinity: 000000000000FFFF
New affinity: 0000000000000002

Launching subprocess...
CPU affinity: 0000000000000002
New affinity: 0000000000000FFF
<hangs here forever>

Or you get lucky and can witness various form of memory corruption:

Launching subprocess...
CPU affinity: 0000000000000002
New affinity: 0000000000000FFF
ERROR: System.AggregateException: One or more errors occurred. (Start may not be called on a task that was already started.)
 ---> System.InvalidOperationException: Start may not be called on a task that was already started.
   at System.Threading.Tasks.Task.Start(TaskScheduler scheduler)
   at System.Threading.Tasks.TaskReplicator.Replica.Execute()
   --- End of inner exception stack trace ---
   at System.Threading.Tasks.TaskReplicator.Run[TState](ReplicatableUserAction`1 action, ParallelOptions options, Boolean stopOnFirstFailure)
   at System.Threading.Tasks.Parallel.ForWorker[TLocal](Int32 fromInclusive, Int32 toExclusive, ParallelOptions parallelOptions, Action`1 body, Action`2 bodyWithState, Func`4 bodyWithLocal, Func`1 localInit, Action`1 localFinally)
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw(Exception source)
   at System.Threading.Tasks.Parallel.ThrowSingleCancellationExceptionOrOtherException(ICollection exceptions, CancellationToken cancelToken, Exception otherException)
   at System.Threading.Tasks.Parallel.ForWorker[TLocal](Int32 fromInclusive, Int32 toExclusive, ParallelOptions parallelOptions, Action`1 body, Action`2 bodyWithState, Func`4 bodyWithLocal, Func`1 localInit, Action`1 localFinally)
   at System.Threading.Tasks.Parallel.For(Int32 fromInclusive, Int32 toExclusive, Action`1 body)
   at Net48Tester.Program.Child(Process current) in D:\Temporary\Net48Tester\Net48Tester\Tester\Program.cs:line 127
   at Net48Tester.Program.Main(String[] args) in D:\Temporary\Net48Tester\Net48Tester\Tester\Program.cs:line 20
Launching subprocess...
CPU affinity: 0000000000000002
New affinity: 0000000000000FFF
Unhandled exception. System.EntryPointNotFoundException: Entry point was not found.
   at System.Threading.ThreadPoolWorkQueue.Dispatch()
   at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()

In production, I've even seen the log file itself being corrupted.

GPSnoopy avatar Oct 02 '19 14:10 GPSnoopy

cc: @Maoni0

janvorli avatar Oct 02 '19 15:10 janvorli

I'm unfamiliar with these exceptions - how could you tell these are due to memory corruption? @stephentoub do these seem like exceptions caused by memory corruption to you?

are you using Server GC at all? if you are using the default which is Workstation GC it doesn't care about the affinity of the process.

Maoni0 avatar Oct 02 '19 19:10 Maoni0

@Maoni0 While trying to reproduce these errors, I've seen hundreds of different errors and exceptions. I believe they are just symptoms of general undefined behaviour rather than pointing to the real culprit. I've seen many AccessViolationException instances as well as clear evidence of corrupted memory locations. The root cause could be a race condition or a dangling pointer.

The GC type does not seem impact the reproducibility of this issue. I've seen it on my Windows 10 desktop with the code above as well as on Windows Server 2016 using production code. Turning concurrent GC on and off had no impact either.

For the laugh, here are a couple more (using .NET 4.8), including a clear memory access violation:

Launching subprocess...
CPU affinity: 0000000000000002
New affinity: 0000000000000FFF
ERROR: System.AggregateException: One or more errors occurred. ---> System.IndexOutOfRangeException: Index was outside the bounds of the array.
   at System.Threading.Tasks.RangeWorker.FindNewWork(Int64& nFromInclusiveLocal, Int64& nToExclusiveLocal)
   at System.Threading.Tasks.RangeWorker.FindNewWork32(Int32& nFromInclusiveLocal32, Int32& nToExclusiveLocal32)
   at System.Threading.Tasks.Parallel.<>c__DisplayClass17_0`1.<ForWorker>b__1()
   at System.Threading.Tasks.Task.InnerInvokeWithArg(Task childTask)
   at System.Threading.Tasks.Task.<>c__DisplayClass176_0.<ExecuteSelfReplicating>b__0(Object <p0>)
   --- End of inner exception stack trace ---
   at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
   at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken)
   at System.Threading.Tasks.Parallel.ForWorker[TLocal](Int32 fromInclusive, Int32 toExclusive, ParallelOptions parallelOptions, Action`1 body, Action`2 bodyWithState, Func`4 bodyWithLocal, Func`1 localInit, Action`1 localFinally)
   at System.Threading.Tasks.Parallel.For(Int32 fromInclusive, Int32 toExclusive, Action`1 body)
   at Net48Tester.Program.Child(Process current) in D:\Temporary\Net48Tester\Net48Tester\Tester\Program.cs:line 127
   at Net48Tester.Program.Main(String[] args) in D:\Temporary\Net48Tester\Net48Tester\Tester\Program.cs:line 20
---> (Inner Exception #0) System.IndexOutOfRangeException: Index was outside the bounds of the array.
   at System.Threading.Tasks.RangeWorker.FindNewWork(Int64& nFromInclusiveLocal, Int64& nToExclusiveLocal)
   at System.Threading.Tasks.RangeWorker.FindNewWork32(Int32& nFromInclusiveLocal32, Int32& nToExclusiveLocal32)
   at System.Threading.Tasks.Parallel.<>c__DisplayClass17_0`1.<ForWorker>b__1()
   at System.Threading.Tasks.Task.InnerInvokeWithArg(Task childTask)
   at System.Threading.Tasks.Task.<>c__DisplayClass176_0.<ExecuteSelfReplicating>b__0(Object <p0>)<---
Launching subprocess...
CPU affinity: 0000000000000002
New affinity: 0000000000000FFF

Unhandled Exception: System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
   at System.String.Concat(String str0, String str1, String str2)
   at System.Exception.ToString(Boolean needFileLineInfo, Boolean needMessage)
   at System.Exception.ToString(Boolean needFileLineInfo, Boolean needMessage)
   at System.Exception.ToString(Boolean needFileLineInfo, Boolean needMessage)
   at System.AggregateException.ToString()
   at Net48Tester.Program.Main(String[] args) in D:\Temporary\Net48Tester\Net48Tester\Tester\Program.cs:line 35

Do note that so far I've not been able to reproduce the problem on Linux (Ubuntu 18.04 with .NET Core 3.0). I suspect part of the answer might be in the C++ internals of the CLR.

GPSnoopy avatar Oct 02 '19 21:10 GPSnoopy

I've just realized it could also be related to the thread pool. @kouvel does it seem possible to you?

janvorli avatar Oct 02 '19 21:10 janvorli

@janvorli My hunch so far is either the thread pool implementation, or something related like the work queues. These are also the parts that appear the most often in the stack traces.

I've cloned the coreclr repo and inspected it, but it's a big haystack.

GPSnoopy avatar Oct 02 '19 22:10 GPSnoopy

This is a problem with the UP allocation helpers. We use GetCurrentProcessCpuCount to decide whether it is ok to use them here: https://github.com/dotnet/coreclr/blob/master/src/vm/gcheaputilities.h#L130 but the implementation of the UP allocation helpers does not use interlocked operations, e.g. here: https://github.com/dotnet/coreclr/blob/master/src/vm/amd64/JitHelpers_Slow.asm#L174

We either need to use total CPU count to decide whether it is ok to use them; or make them multi-processor safe by using interlocked operations.

jkotas avatar Oct 03 '19 07:10 jkotas

The GC type does not seem impact the reproducibility of this issue.

This repros with workstation GC only, but you do not see it because of we ignore the request to use server GC if the process is affinitized to a single processor during startup: https://github.com/dotnet/coreclr/blob/master/src/vm/ceemain.cpp#L456

jkotas avatar Oct 03 '19 07:10 jkotas

We suspect the problem has been introduced in .NET 4.8 as well as .NET Core 2.1

You are right. This problem was introduced by https://github.com/dotnet/coreclr/pull/10065/

jkotas avatar Oct 08 '19 02:10 jkotas

Reopening for 3.1 port

jkotas avatar Oct 08 '19 02:10 jkotas

For .NET Framework, we are currently planning to fix this for January 2020 update.

jkotas avatar Oct 10 '19 21:10 jkotas

I just wanted to add that I ran across this issue as well and noticed that if I ran on a virtual machine with ONE vCPU and .net 4.7.2 that the issue still arose for me but if I ran on a virtual machine with TWO or more vCPU and .net 4.7.2 it was not reproducible. The inverse was true for .net 4.8 where a virtual machine with ONE vCPU and .net 4.8 could not reproduce but with a virtual machine with TWO or more vCPU and .net 4.8 I could reproduce.

JohnFredMeyer avatar Jan 06 '20 15:01 JohnFredMeyer

Does the fix also come for Windows 7 Enterprise with ESU or without ESU?

anorisoft avatar Feb 22 '20 17:02 anorisoft