Index | Thread | Search

From:
Laurence Tratt <laurie@tratt.net>
Subject:
Re: ip sysctl atomic
To:
tech@openbsd.org
Date:
Thu, 16 May 2024 11:04:27 +0100

Download raw body.

Thread
On Thu, May 16, 2024 at 12:57:13AM GMT, Alexander Bluhm wrote:

> So what is the intention of the ..._ONCE() macros?

There was a similar discussion (starting at [1]) a couple of years ago.

My worry then remains my worry now: modern versions of C have a largely
well-defined memory model, and a decent API for making use of it, but we
don't seem to be making use of it, which means that we're probably
exposed to various multi-threading problems, particularly on non-x86.

For example, I imagine that `READ_ONCE` is roughly intended to be the
equivalent of modern C's "read with relaxed ordering". However, neither
the name nor the definition that I can see (in atomic.h) make that
clear. Indeed, `READ_ONCE` looks to me like it relies on the `volatile`
keyword, but that's explicitly not enough to guarantee atomicity between
threads [2]:

> Note that volatile variables are not suitable for communication
> between threads; they do not offer atomicity, synchronization, or
> memory ordering. A read from a volatile variable that is modified by
> another thread without synchronization or concurrent modification from
> two unsynchronized threads is undefined behavior due to a data race.

All of this gets even more muddy because atomics have both a run-time
effect on CPUs *and* a compile-time effect (stopping the compiler
reordering some things), and I find that if I'm not careful I think
about one of these and not the other.

A possible suggestions is that `READ_ONCE` should become `READ_RELAXED`
(similarly for `WRITE_ONCE`) and explicitly use modern C's "relaxed"
ordering. We would then be able to defer to C's standard when people
need to work out exactly what these mean.


Laurie

[1] https://marc.info/?l=openbsd-tech&m=164691123319506&w=2
[2] https://en.cppreference.com/w/c/language/volatile