|
|
Log in / Subscribe / Register

Beingessner: Rust's Unsafe Pointer Types Need An Overhaul

Beingessner: Rust's Unsafe Pointer Types Need An Overhaul

Posted Mar 22, 2022 4:16 UTC (Tue) by jlombera (guest, #155698)
In reply to: Beingessner: Rust's Unsafe Pointer Types Need An Overhaul by mrugiero
Parent article: Beingessner: Rust's Unsafe Pointer Types Need An Overhaul

> Your C program typically doesn't know about nor can control how cache gets flushed and sync'd.

The processor knows, though. All the compiler needs to do is not to register-optimize and emit memory access instructions instead, the processor takes care of maintaining cache coherence.


to post comments

Beingessner: Rust's Unsafe Pointer Types Need An Overhaul

Posted Mar 22, 2022 4:45 UTC (Tue) by NYKevin (subscriber, #129325) [Link] (16 responses)

To the best of my understanding, this is somewhat true on x86, and not at all true on basically any (modern) architecture other than x86 (e.g. ARM).

Beingessner: Rust's Unsafe Pointer Types Need An Overhaul

Posted Mar 22, 2022 5:02 UTC (Tue) by jlombera (guest, #155698) [Link] (15 responses)

I can assure you "volatile" works as described on at least X64, IA64, SPARC, IBM Z (don't remember the actual name of the arch) using different compilers (GCC, Clang, MSVC, ICC, ACC, Solaris Studio, XLC).

Beingessner: Rust's Unsafe Pointer Types Need An Overhaul

Posted Mar 22, 2022 11:29 UTC (Tue) by tialaramex (subscriber, #21167) [Link] (14 responses)

"Volatile" is a C qualifier but the CPU doesn't run C it runs machine code. And so your volatile storage qualifier is long gone by the time the CPU is running your program.

You can take a look at a toy example with Godbolt, and see for yourself what the compiler actually tells your CPU to do, on x86 (and x86-64) you get Acquire/Release semantics (but not full consistency) "for free" (in fact everybody is paying for these semantics, all the time on this platform so it's only "free" the same way the ice is "free" with a $5 coke in a restaurant) but on other platforms if you don't see the CPU being told to do this work it's not doing the work. Maybe you get away with it, and maybe you don't. You are gambling every time.

Beingessner: Rust's Unsafe Pointer Types Need An Overhaul

Posted Mar 22, 2022 16:14 UTC (Tue) by jlombera (guest, #155698) [Link] (12 responses)

>"Volatile" is a C qualifier but the CPU doesn't run C it runs machine code. And so your volatile storage qualifier is long gone by the time the CPU is running your program.

Again, "volatile" is to ask the *compiler* not to optimize access to memory in the generated binary code.

>You can take a look at a toy example with Godbolt, and see for yourself what the compiler actually tells your CPU to do

Sure, feel free to play with this (very contrived) example in godbolt.org (sorry for the formatting, I couldn't fine a way to make this work as a plain text comment):

```
void f(volatile int *x_p) {
while (!*x_p)
;
}

void g(int *x_p) {
while (!*x_p)
;
}
```

Feel free to play with different compilers, optimization levels, even different archs. You'll see that in every case, in the loop in f() *x_p is read from memory in every iteration, whereas for g(), different kind of optimizations are performed.

Beingessner: Rust's Unsafe Pointer Types Need An Overhaul

Posted Mar 22, 2022 17:13 UTC (Tue) by NYKevin (subscriber, #129325) [Link] (8 responses)

> You'll see that in every case, in the loop in f() *x_p is read from memory in every iteration, whereas for g(), different kind of optimizations are performed.

Nobody is disputing that. We are telling you that the compiler will fail to emit acquire/release memory barrier instructions on non-x86 platforms, and without those, you get no cross-thread guarantees.

Beingessner: Rust's Unsafe Pointer Types Need An Overhaul

Posted Mar 25, 2022 21:33 UTC (Fri) by ncm (guest, #165) [Link] (7 responses)

A quibble here: Apple M1 is said to provide memory/cache semantics compatible with x86, and thus stronger than other-ARM or POWER.

Beingessner: Rust's Unsafe Pointer Types Need An Overhaul

Posted Mar 26, 2022 22:13 UTC (Sat) by foom (subscriber, #14868) [Link] (6 responses)

Apple only enables the x86-like TSO mode in their CPU when running emulated x86 code. It uses the usual ARM memory ordering guarantees otherwise.

Beingessner: Rust's Unsafe Pointer Types Need An Overhaul

Posted Mar 28, 2022 17:13 UTC (Mon) by MrWim (subscriber, #47432) [Link]

I wonder what the performance impact of this being enabled is?

Beingessner: Rust's Unsafe Pointer Types Need An Overhaul

Posted Mar 29, 2022 10:58 UTC (Tue) by nye (guest, #51576) [Link] (4 responses)

I find it fascinating that they've designed their hardware specifically to make it easier to emulate a different architecture. Is this sort of thing done a lot?

Beingessner: Rust's Unsafe Pointer Types Need An Overhaul

Posted Mar 29, 2022 11:46 UTC (Tue) by excors (subscriber, #95769) [Link] (1 responses)

Maybe Nvidia's Denver counts? From early descriptions, it sounds like it was designed with a native ISA that closely matches its microarchitecture (in-order, very superscalar, etc), and it emulates the ARM ISA via both a hardware ARM instruction decoder (low latency but poor utilisation of the unusual microarchitecture) and a firmware-based dynamic ARM-to-native translator (high latency but can heavily optimise hot loops). And it would have also emulated x86 if not for patent licensing issues.

Denver reportedly provides sequential consistency (https://threedots.ovh/blog/2021/02/cpus-with-sequential-c...) so it's even stronger than x86, regardless of what mode it's running in - maybe that made sense when they were originally planning to support x86, because it'd be cheaper than emulating x86 on a weaker model, and simpler than exactly implementing x86's weird TSO model.

On the other hand, that doesn't sound terribly different to all modern CPUs, where the ARM/x86/etc instructions are heavily translated into microarchitecture-specific micro-ops - you could view them all as essentially emulating ARM/x86, and their microarchitectures are designed to do that emulation efficiently. The main difference is just that they're designed for a single ISA (or a related pair like A32 and A64), whereas Denver and Apple M1 were designed for both ARM and x86 (even if Denver only ever shipped as ARM).

Beingessner: Rust's Unsafe Pointer Types Need An Overhaul

Posted Mar 30, 2022 9:53 UTC (Wed) by nye (guest, #51576) [Link]

Quite different but very interesting, especially with the firmware caching translated code in main memory; thanks for the pointer. Apparently they had some former Transmeta employees on the team, which makes sense.

Beingessner: Rust's Unsafe Pointer Types Need An Overhaul

Posted Apr 4, 2022 2:41 UTC (Mon) by ncm (guest, #165) [Link] (1 responses)

It is absolutely the norm, going back to the early 1960s.

The current Intel chips emulate all previous Pentiums, both 64 and 32 bits, which emulated the 486, which emulated the 386, which emulated the 286, which emulated the 8086, which was jimmied to emulate 8080, which emulated 8008. The Z-80 also emulated 8080. IBM z emulates 370, which emulates 360, which could emulate 1401, which I think emulated 701. The DEC Alpha was able to emulate x86 faster than any native x86 of the time could run.

So, emulating is almost the norm. There are said to be businesses running programs from the '60s on machines emulating five levels deep.

But that Apple turns off x86-style bus ordering when not emulating suggests they can run faster without it. It is usually said that Intel avoids a speed penalty for their memory model by throwing way more transistors at the problem than seems reasonable to other makers. So, this looks complicated.

Beingessner: Rust's Unsafe Pointer Types Need An Overhaul

Posted Apr 11, 2022 16:22 UTC (Mon) by flussence (guest, #85566) [Link]

Most of that's right, but it's worth noting new Intel chips are actually starting to pull up the 80xx compatibility ladder behind them. While OSes have long since grown past the need for 40-year-old quirks (and userspace emulation is more than good enough to not care any more), the BIOS was still a major holdout until recently.

Beingessner: Rust's Unsafe Pointer Types Need An Overhaul

Posted Mar 22, 2022 18:27 UTC (Tue) by khim (subscriber, #9252) [Link] (2 responses)

> Again, "volatile" is to ask the *compiler* not to optimize access to memory in the generated binary code.

And that's not enough. Not even on x86. You know that, right?

Intel 8086 included lock prefix from the very beginning! And you can not force compiler to use it with volatile. End of story.

Yes, with C89 you had no choice but to use assembler with some volatile sprinkled here and there. C11 offers atomics which provide much more concise and usable semantic.

Don't use volatile except in kernel, please. It's not needed and harmful.

Beingessner: Rust's Unsafe Pointer Types Need An Overhaul

Posted Mar 22, 2022 20:13 UTC (Tue) by jlombera (guest, #155698) [Link] (1 responses)

Sorry, I think we just keep talking about different things. You keep bringing atomics, reordering and serialization issues to the discussion. I already conceded those might be required in addition (or instead of) to "volatile" depending on what you are trying to achieve (e.g. serialization), but those are not the use case of "volatile".

Beingessner: Rust's Unsafe Pointer Types Need An Overhaul

Posted Mar 23, 2022 0:20 UTC (Wed) by excors (subscriber, #95769) [Link]

Could you give specific examples of use cases with shared memory between threads where volatile is sufficient?

The main thing I can think of is e.g. performance counters, where one thread updates them and another thread periodically reads them, and where you don't care if it reads slightly stale values (but not worse than a few usecs) or reads each counter in an unpredictable order. In that case, you do need something like volatile (to ensure the first thread doesn't hold the counter in a register for many usecs) but you don't need any further synchronisation guarantees. You also need atomic reads/writes, which I don't think volatile guarantees, but in practice it's probably okay if it's an aligned word-sized value.

Probably you could also do a simple form of mailboxes, where the producer thread does "while (m != 0) {}; m = 42;" and the consumer thread does "while (m == 0) {}; do_work(m); m = 0;", where (I think? but not certain) there are hopefully enough implicit dependencies that it will always behave as expected on any CPU. (But that won't work if you want to share more than a single word, because the mailbox message won't be synchronised with any other memory access.)

Those seem very niche cases, though. And you can easily do them with C++/C11 atomics using memory_order_relaxed (which adds no synchronisation barriers but does guarantee atomicity, like a more well-behaved volatile). I'm not aware of any drawbacks of memory_order_relaxed over volatile, and the benefit is it can be combined with acquire/release accesses (to the same variable or to others) for cases where synchronisation is important (which is nearly all cases involving shared memory).

Beingessner: Rust's Unsafe Pointer Types Need An Overhaul

Posted Mar 23, 2022 4:17 UTC (Wed) by marcH (subscriber, #57642) [Link]

> so it's only "free" the same way the ice is "free" with a $5 coke in a restaurant

BTW https://queue.acm.org/detail.cfm?id=3212479

> The cache coherency protocol is one of the hardest parts of a modern CPU to make both fast and correct. Most of the complexity involved comes from supporting a language in which data is expected to be both shared and mutable as a matter of course.

Beingessner: Rust's Unsafe Pointer Types Need An Overhaul

Posted Mar 22, 2022 9:05 UTC (Tue) by tialaramex (subscriber, #21167) [Link] (2 responses)

> the processor takes care of maintaining cache coherence

The CPU doesn't promise sequential consistency, because doing so would make it (much) slower. So now your program doesn't have sequential consistency. This is inherently a very difficult environment in which to write programs at all, but C and C++ don't bother you with that trouble because both languages have the same rule about sequential consistency: If your program doesn't exhibit sequential consistency it instead has Undefined Behaviour and they wash their hands of you entirely.

Again, you can write "volatile" on some more variables and maybe you get lucky and on the CPU you're working with the extra spills cause a cache flush, or forces an extra wait cycle somewhere and it happens to mask the bug. And then maybe somebody buys a CPU with more L1 cache, or a different cache policy and now the mysterious bug is back. You are using the wrong tool for the job.

Beingessner: Rust's Unsafe Pointer Types Need An Overhaul

Posted Mar 22, 2022 15:45 UTC (Tue) by jlombera (guest, #155698) [Link] (1 responses)

Sure, you might need to resort to explicit memory fencing when you want to ensure sequential consistency, but this is not what volatile is about.

Beingessner: Rust's Unsafe Pointer Types Need An Overhaul

Posted Apr 4, 2022 2:54 UTC (Mon) by ncm (guest, #165) [Link]

Being absolutely clear: "volatile" is completely useless for synchronizing between threads. If you have been relying on volatile for synchronization, you are shipping bugs.

Unless you are pinging hardware registers, "volatile" is doing absolutely nothing for you, no matter how it looks to you in Godbolt. To synchronize between threads, you need memory fences, which are expressed as "atomic" types in C and C++. If you are using atomics, there is exactly zero value in adding "volatile". If you are not using atomics and not pinging hardware registers, there is exactly zero value in adding "volatile". "Volatile" appearing in code not part of an OS driver reliably indicates bugs.

Beingessner: Rust's Unsafe Pointer Types Need An Overhaul

Posted Mar 22, 2022 22:38 UTC (Tue) by edeloget (subscriber, #88392) [Link]

> > Your C program typically doesn't know about nor can control how cache gets flushed and sync'd.

> The processor knows, though. All the compiler needs to do is not to register-optimize and emit
> memory access instructions instead, the processor takes care of maintaining cache coherence.

That would not work.

First of all, the obvious: it would fail on the multi-processor (physically separated) case because one thing a processor knows is not always known by the other guy. That would require N-to-N communication between the processors - and it would be a nightmare on systems where you have many nodes (up to 6x64 cores) that can share the same physical memory, such as the Chinese Sunway supercomputer.

And then it would be reeeeeeeeaaaaaaaaaaly slow. The reason why cache works this way is that the processor don't even try to find out if the underlying memory has changed (on a load) or if it should change (on a store). Because it does not check anything, it's fast. If you start to factor in multiple checks then you'll hit a performance wall quite soon.

That's exactly why we do this only when performing an atomic operation: we are willing to pay the performance cost in exchange for the information. This is not something we want to do on every load or store. And that's exactly why processors don't do it unless we explicitely tell them to do it. The application (either the OS or a user space program) knows when it shall make an atomic load or store. The processor cannot know it in advance and unless you make an explicit pledge the compiler cannot know either.

Beingessner: Rust's Unsafe Pointer Types Need An Overhaul

Posted Mar 25, 2022 14:11 UTC (Fri) by darthscsi (guest, #8111) [Link]

> processor takes care of maintaining cache coherence

The problem here is cache coherence is a broad term and what different architectures do is vastly different. Multithreaded or multiprocess code expose the cache coherence semantics of the architecture to the programmer. This is not true for single threaded coded. Programmers, especially x86 programmers, try to extrapolate what cache coherence does from single threaded execution, which is not a correct thing to do. Volatile effective forces the compiler to make loads and stores (but doesn't order volatile and non-volatile accesses, which is why old code had the iconic empty asm block marked as writing all memory), but it does nothing to protect you from the architecture's memory model. x86 has a strong memory model, which has fewer classes of behavior which don't match single threaded code, if you constrain the compiler, but that doesn't mean they don't exist, the ISA has locked prefixes for a number of instructions for a reason.


Copyright © 2026, Eklektix, Inc.
Comments and public postings are copyrighted by their creators.
Linux is a registered trademark of Linus Torvalds