553 points · by GordonS · 8y ago · 144 comments
The root of the problem is that .NET implemented a rather baroque spin loop with several assumptions about the CPU and OS architecture. Unlike any other spin loop I have seen or written, they execute multiple pause instructions per loop. Arguably this was a poor choice.
It would be interesting to see the history of this design. It was probably done years ago when .NET was closed source.
At the risk of repeating the content of the blog post ... The issue was reported in August, 2017 and fixed later in the same month. The fix shipped in a .NET Core patch update in September. We attempted to get the fix into .NET Framework 4.7.2 but missed that scheduling. We're now looking at making the fix in a .NET Framework patch release.
Would be interested to know why you think the code was always broken. Perhaps Intel define a preferred algorithm they failed to implement?
New architecture makes new choices and, according to the redlined doc, they expect 1-2% performance improvements on threaded apps, which is a measurable improvement. They also explicitly call for possible degradation cases so folks who care can adjust.
.NET apparently hits such a degradation case, but parent says this is due to .NET implementing spin loops in a way (almost) no one else does. If so, in this particular case Intel is doing the greatest good for the greatest number, which is reasonable. My 2c.
Examples: All the Concurrency primitives like Task<T> are thread-safe by default, and that has some associated cost. Other runtimes like javascript or other singlethreaded event loops don't have to pay for that cost, and might still be able to scale horizontally. Also the IO subsystem on .NET requires a lot of synchronization: Most IO callbacks (e.g. for sockets) will be made from an arbitrary Threadpool thread, which requires synchronization or marshaling to get back to another context. Again that will be cheaper on a runtime where the whole event sources and consumers are using the same thread.
I certainly can't quantify it in numbers, but I guess .NET has some of the highest requirements regarding synchronization performance. At least the standard libs, there are obviously some efforts underway to improve that situation.
You aren't going to get a good spin lock without making some assumptions about the hardware and OS. Get new hardware, gotta add a new case.
I also have to quibble with this conclusion:
This is not a .NET issue. It affects all Spinlock implementations
which use the pause instruction.
The instruction isn't the issue, the exponential backoff that .NET includes is. At the extreme (last iteration, on a 64-core CPU) it will spin for 1.2 million pause instructions...Is it though?
The "pause" instruction gives all resources to the hyperthread sibling. So under high-utilization (ie: your core has a hyperthread-sibling ready and willing), a "pause" instruction is basically a super-low latency task-switch.
I wouldn't be surprised that a "spinlock with pause" would be better, even in 5ms to 10ms chunks of time (Windows has 15ms quantas, and may task switch as late as 30ms to 75ms depending on the situation).
Because its better to do the hardware-assisted "pause" task switch rather than actually cause the OS-scheduler to get involved. In fact, that's what Microsoft AND Intel have concluded!! To get better real-world metrics, both Microsoft AND Intel felt like the "pause" instruction should wait longer! Skylake-X increases the latency, while .NET created this exponential-backoff.
I bet it was good in isolation, but when combined, the overall effect was too much pausing.
Yes, definitely, beyond any doubt.
The .NET approach only makes sense if you have exactly the same number of active threads as CPU "cores" and if your CPU always supports hyperthreading. If either of those is not true then what .NET is doing is a severe CPU bottleneck when the lock is actually contended.
And it is incredibly unlikely that that exact situation happens in the wild. You almost always have more than <cpu core count> threads/processes active in heavy multithreading workloads, and you definitely can't assume everyone has hyperthreading as that's a feature commonly cut from mid & low range CPUs.
For context here a thread context switch via something like futex is in the sub-10us range. So a 5ms spinlock robs you of ~4.9ms of usable CPU throughput that a different thread/process could have been doing instead. The timeout levels here are just shy of an eternity. 5ms is a really, really long amount of time.
By way of comparison pthread_mutex_lock in glibc will do one pause per attempt for at most 100 attempts. So under skylake it has a max pause duration of around 3-5us, depending on clock speed, which is pretty reasonable. It roughly aligns with the cost of a context switch, so once it starts spinning for longer than a context switch it switches to a context switch instead.
Pausing for as much as 10ms could be better under some circumstances, but that would seem to me to be heavier than a context-switch. Whether the system actually achieves better throughput or not in that case would be workload dependent. Worst case the hyperthread is also running the spin lock loop and no useful work at all is accomplished on the core.
"The issue has been fixed with .NET Core 2.1 and .NET Framework 4.8 Preview contains also the fixes for it."
And by the end of the article I was thinking their code might just run faster as a single thread on a ~4GHz processor.
Another thought was why do they have so much resource contention in the first place? That seems fishy.
Another thought: Perhaps they should write it in Rust with all of its "fearless concurrency" claims. While I'm skeptical of those claims, The exercise would probably highlight some of the real issues.
Any way I look at it, I keep thinking it's a software design problem.
Rust doesn't solve deadlocks or race conditions. Rust only makes it hard to accidentally share a memory location, but that's only a very small part of the problem, race conditions being a fundamental part of computer science, being baked into any language that supports expressing and joining asynchronous processes.
I would be generous in agreeing with a statement about Rust making it a little more difficult to end up with a deadlock or unwanted race condition, except that's not true when compared with many other high level languages.
Also nothing is impossible until you prove it via formal methods (e.g. TLA+).
Speculation on my part. I'm not actually advocating Rust but I am thinking about a project to give it a try.
The problem was GC initiated i.e. the entry into GC caused the deadlock to start with which the process never recovered from as it was spinlocking all threads and no resources were available to complete GC.
The object code in question uses an instruction that's basically a microarchitecture-specific hack. IMO the real issue here is that the object code is optimized for an earlier microarchitecture and needs an update.
Disclaimer: I work for Intel, but not on their CPUs and I'm not a fanbois.
On the other hand, I think the hack is not in using the pause instruction itself, but that crazy backoff algo. For example Linux uses pause too (via rep; nop) in lots of places. But not in a exponential loop (that I'm aware of).
I would expect any spinning lock to spin at most some slight fraction of the scheduling granularity, but almost always far less than the context switch time except maybe in some specific case of latency sensitive code.
Maybe thr long spin tine is for some reason trying to account for the very long scheduling quantas of windows server?
Superficially it seems misdirected in anything but real-time code since most schedulers would allow the thread to keep its quanta until the next scheduling if the thread wait time was low. The only case I can see this as not being the case is in a system that is overloaded and all CPU's have multiple threads that are all starved.
So its not like resources are lost (at least, under high CPU utilization). But still, you're right in that a 29ms spin-lock sounds outrageous to me. That's definitely long.
The textbook example of a spinlock is maybe a synchronized counter (iterations++), or maybe a producer/consumer queue.
- invokes the accept() function of the socket family: https://github.com/torvalds/linux/blob/be779f03d563981c65cc7...
- which invokes the accept() function of the protocol: https://github.com/torvalds/linux/blob/be779f03d563981c65cc7...
- which invokes lock_sock_nested(), which spins https://github.com/torvalds/linux/blob/be779f03d563981c65cc7...
Genuine questions, because I really don't know.
https://www.youtube.com/watch?v=9hJkWwHDDxs
So actually, you're about right. Its "wrong" to spinlock above 40 cores. But at 40-cores or less, you probably should prefer spinlocks over atomics or other primitives on the x86 platform.
As for what? Well, you need a synchronization primitive for a producer-consumer queue. A spinlock would be a good choice for that, even on 40+ core machines (since most of those cores wouldn't be spinning at the same time, even if they're all locking the same lock).
Remember, x86 primitive for synchronization is the "LOCK" prefix. When an x86 core "LOCK"s an instruction, no other core is allowed to touch the data its touching. (In MESI protocol: the cache line goes into the "exclusive" state). As such, spinlocks match the fundamental nature of the x86 instruction set very very well.
Can anybody actually explain this result? The spinlock needs at least one atomic operation and a write (for lock + unlock) and one non-atomic read-modify-write per iteration while the atomic increment needs only a single atomic operation per iteration and no other memory access. How on Earth can the latter variant be slower?
The only thing I can think of right now is that due to some micro-architectural idiosyncracies, the relevant cache lines end up migrating between cores more often in the atomic increment case, while in the spinlock case, the same core ends up winning the lock back-to-back more often (and so cachelines migrate less frequently which reduces the overall running time).
That seems like it would most likely only ever be relevant to this kind of extremely micro benchmark, but I'd be interested to hear if there are other explanations (I haven't watched the whole talk, but at least the slides don't seem to make an attempt to explain this).
Furthermore, ALL loads / stores are almost strictly ordered on x86.
http://www.cs.cmu.edu/~410-f10/doc/Intel_Reordering_318147.p...
> Intel 64 memory ordering obeys the following principles:
> 1. Loads are not reordered with other loads.
> 2. Stores are not reordered with other stores.
> 3. Stores are not reordered with older loads.
> 4. Loads may be reordered with older stores to different locations but not with older stores to the same location.
> 5. In a multiprocessor system, memory ordering obeys causality (memory ordering respects transitive visibility).
> 6. In a multiprocessor system, stores to the same location have a total order.
> 7. In a multiprocessor system, locked instructions have a total order.
> 8. Loads and stores are not reordered with locked instructions.
As such, "relaxed atomics" DO NOT EXIST on x86. Almost everything on x86 is innately an acquire / release semantics (even non-locked stuff).
------------
As such, the optimal spinlock-unlock implementation on x86 doesn't use the LOCK prefix at all! You rely upon the memory-ordering consistently guaranteed by the x86 processor, and let the cache-coherence mechanism handle everything for you.
You'll still need the "lock" to obtain the lock (writing 1 into the memory location AND reading the old value). But unlocking the lock (writing 0 into the memory location) can be done x86-LOCK-prefix free.
In contrast, a CAS-atomic on x86 needs to "LOCK" the memory bus, which under x86 is specified as:
> Causes the processor’s LOCK# signal to be asserted during execution of the accompanying instruction (turns the instruction into an atomic instruction). In a multiprocessor environment, the LOCK# signal ensures that the processor has exclusive use of any shared memory while the signal is asserted.
So when you do a CAS-atomic on x86, in REALITY, the LOCK-prefix will be asserted, locking out all other cores from interacting with your cache line.
------------
So the cache-coherence mechanism on x86 seems sufficiently robust and well optimized by Intel / AMD, at least with our current 28-core Xeons and 32-core EPYCS. Future scaling may be an issue for Intel/AMD, and ARM / Power9 (which have true relaxed memory) may scale better eventually.
https://www.youtube.com/watch?v=9hJkWwHDDxs
Atomics-based lock-free data-structures scale beyond 40+ core counts. But note that x86's "lock" instruction is fundamental to the system. x86 doesn't have relaxed atomics or barriers under most circumstances. As such, the spinlock best represents what the x86 instruction set offers.
More info on the purpose of the pause instruction: https://stackoverflow.com/questions/4725676/how-does-x86-pau...
Info on what's a "spinlock" (I thought it was another word for busy wait, but there's a subtle difference): https://stackoverflow.com/questions/38124337/spinlock-vs-bus...
The increased latency ... has a small positive performance impact of 1-2% on highly threaded applications.
Making an instruction more than 10x slower overall, for a 1-2% gain (who wants to bet it's some "industry standard" benchmark...?) in a very specific situation sounds like a textbook example of premature microoptimisation. Of course they don't want to give the impression that they severely slowed things down, but the wording of the last sentence is quite amusing: "some performance loss"? More like "a lot". It reminds me of what they said about the Spectre/Meltdown workarounds.
No, this is textbook optimization
Benchmarks showed a positive gain -> that's a real optimization, not premature at all.
Premature optimization is when you guess than a change will make things better without measuring. As soon as you measure it becomes real optimization work, not premature at all. As in, this is how you're supposed to make things better.
Feel free to debate the merits of their benchmarkmark, but this is a textbook example of Doing Performance Correctly otherwise.
But this gain of 1-2% is balanced with author's 50% performance loss. I guess it means that the benchmark results here depend on choice of tested applications. If they had used more multithread .NET applications, the tests could show a performance degradation as well.
If you are spending even a tiny fraction of 1% of your time spinning, your app has terrible performance bugs already.
This article is just bad analysis.
Not necessarily. Very latency-sensitive applications may pin a thread to a CPU core and mark the core as reserved so the kernel doesn't schedule any other task or interrupt on it. Busy-waiting is used instead of yielding to the scheduler, that way context switches can be avoided almost entirely.
The bottom line is that this is an architecture optimized for compute throughput, and they figured out that if they spent a few cycles on spin exit they could more than make it back via more effective hyperthread dispatch. And for everyone but .NET, that seems to be the case.
I thought the VM class of languages were generally inappropriate for real-time work. Heck, even in C, you need to do specific work on the memory allocator to make real-time viable.
It’s not “premature optimization” to gain 1-2% for likely trillions of application executions.
Maybe??
Tbh I think this is more of a sign that Intel's architecture, the Core i generation of CPUs, has been optimized as much as you reasonably can and Intel is squeezing out a few more cpu cycles here and there.
Someone else can pipe in, but the impression I got from friends in that industry was that Intel had a fairly advanced org set up to evaluate that.
Or to look at it another way, they didn't want to make an $x billion bet without due diligence.
https://msdn.microsoft.com/en-us/library/windows/desktop/ms6...
If the SwitchToThread call returns False, then the code reverts to a Sleep(0) call instead.
Credit to StackOverflow and Joe Duffy's excellent article on this:
https://stackoverflow.com/questions/1383943/switchtothread-v...
http://joeduffyblog.com/2006/08/22/priorityinduced-starvatio...
However, as mentioned in one of the SO replies, you still need to make sure that you don't use locks that use loops on calls like this when those locks will have to wait on anything long-running - you're just going to burn CPU/battery needlessly. So, only use such locks when you know that the protected code doesn't involve any long wait states, or modify the code to back out even further into a proper kernel wait after looping X times. Personally, I agree with second SO answer and don't like such constructs, and would personally say just go with a straight-up kernel wait if there's any question about whether such conditions could exist now or in the future.
"Pause" is a hint to the CPU that the current thread is spinning in a spinlock. You've ALREADY have tested the lock, but it was being held by some other processor. So why do you care about latency? In fact, you probably want to free up more processor resources as much as possible.
Indeed, there's not actually any resources wasted when you do a "pause" instruction. In a highly-threaded environment, the hyperthread-brother of the thread picks up the slack (you give all your resources to that thread, so it executes quicker).
10-cycles is probably a poor choice for modern processors. 10-cycles is 3.3 nanoseconds, which is way faster than even the L3 cache. So by the time a single pause instruction is done on older architectures, the L3 cache hasn't updated yet and everything is still locked!!
140-cycles is a bit on the long side, but we're also looking at a server-chip which might be dual socket. So if the processor is waiting for main-memory to update, then 140-cycles is reasonable (but really, it should be ~40 cycles so that it can coordinate over L3 cache if possible).
So I can see why Intel would increase the pause time above 10-cycles. But I'm unsure why Intel increased the timing beyond that. I'm guessing it has something to do with pipelining?
I have no idea what "disrupting Intel's model" would actually mean. But I would be fine if Intel is just outcompeted at their own game, and this already seems to be happening.
You can get a 8 year year old octocore that still destroys anything Intel has put out recently.
Intel relies on inertia. Amd consistently beats them on actual performance at a lower price. I remember my 386 dx 2 had better performance than an Intel 486. And let's not forget the p4 issues with their garbage ram. Plus they backdoor their chips with stupid insecure crap
It's only with Ryzen that AMD reached performance parity with Intel once again.
[1] https://www.tomshardware.com/reviews/amd-phenom-ii-x6-1090t-...
I absolutely don't believe an 8 year old AMD octacore will "destroy" anything intel has. Sure I imagine a single highly specific and biased test could give AMD the advantage in that one instance, but overall performance AMD has been behind since the pentium M/core2 with only a few products that initially compete or win, only to fall behind again.
We may be remembering a different history, but Intel has had single threaded performance locked up for awhile.
AMD prices aggressively and glues more cores together, but hyperbole isn't doing your point any favors.
Bad compared to whom?
Intel's 32 bit offering at the time wasn't any good either; the pentium had such a deep pipeline (and not so smart prefetch/speculative) that the chips ran at a high frequency, ate a lot of power, but pipeline stages were idling or working on useless stuff a large amount of the time.
Luckily for the world, AMD managed to produce that alternative, the AMD64 architecture, which kicked intel's ass so hard that eventually they had to adopt it.
If it weren't for AMD's AMD64, and their cross-licensing deal with Intel (that allowed them to make an x86 compatible chip without specifically asking for Intel's permission), we'd be in an Itanium dominated world right now (or .. ARM would have stepped up, it's hard to predict an alternate reality) but surely with less efficient and less effective processors.
History does not repeat, but it rhymes. Intel has no Itanic this time, but it did become numb enough to let AMD outmaneuver them again.
It's not that Intel is doing a bad job, as much as they have too little incentive to do a good job.
This is far from certain: Itanium shipped years later and much, much below the advertised performance thresholds. In the meantime even Intel’s own x86 had closed the raw performance gap and since IA-64 was such a huge bet on brilliant compilers that the early benchmarks for most business code favored the P-III even before you factored in cost. Similarly, the original claim that it’d offer competitive x86 performance turned out to be half a decade behind years behind when it shipped so it wasn’t even remotely competitive for legacy code and businesses back then had even more weight of code which was difficult to recompile.
It’s equally plausible to me that Intel would have continued to see strong x86 sales and weak demand for Itanium and ended up shipping their own 64-bit extension a few years later with less pressure from AMD simply because businesses weren’t keen on the “recompile everything, make a bunch of expensive optimizations, and it might be faster than the system it’s replacing”