Dare I ... another volatile discussion ?
Mike via Digitalmars-d
digitalmars-d at puremagic.com
Fri May 8 01:39:35 PDT 2015
On Thursday, 7 May 2015 at 16:04:56 UTC, Jens Bauer wrote:
> So back to what originally triggered this post; this is what
> the question is actually about:
> If writing a driver for <platform X>, how is reading/writing
> hardware registers usually done in D ?
Here's my pre 2.067 code for `volatile` semantics
@inline T volatileLoad(T)(T* a)
{
asm { "" ::: "memory"; };
return *cast(shared T*)a;
}
@inline void volatileStore(T)(T* a, in T v)
{
asm { "" ::: "memory"; };
*cast(shared T*)a = v;
}
As Iain showed, shared does not provide any order guarantees, so
that's why I added the asm { "" ::: "memory"; }; memory barrier.
This code, however, is still incorrect because it uses a bug in
GDC as a feature. Iain explained that bug here:
https://youtu.be/o5m0m_ZG9e8?t=3141
There's also a post here that shows a volatileLoad/Store
implementation using memory barriers without shared
(http://forum.dlang.org/post/501A6E01.7010809@gmail.com), but
when I tried it with my cross-compiler, I got an ICE.
Furthermore, I don't even understand it. I don't understand
exactly what the +g and +m constraints do, and I hate using code
I don't understand.
Once 2.067 is properly merged and implemented, none of this will
be necessary anyway as volatileLoad/Store intrinsics were
introduced. That being said, you will still have to add some
boilerplate around volatileLoad/Store to make the syntax
tolerable. Johannes has a nice implementation of Volatile!T for
that purpose here (http://dpaste.dzfl.pl/dd7fa4c3d42b). I have
my own CTFE Template implementation here
(https://github.com/JinShil/stm32f42_discovery_demo/blob/master/source/stm32f42/mmio.d).
In terms of shared, I think the following thread is quite
telling:
http://forum.dlang.org/post/lruc3n$at1$1@digitalmars.com. Based
on that, I wouldn't trust shared for anything, and I think it
should just be ignored altogether. See also
http://p0nce.github.io/d-idioms/#The-truth-about-shared
I'm not sure what to do yet for synchronized/atomic access. If I
had to do in now, I'd probably just stick with C-like techniques.
Mike
More information about the Digitalmars-d
mailing list