Re: [PATCH] hwmon: (max16065) Use READ/WRITE_ONCE to avoid compiler optimization induced race

From: Gui-Dong Han

Date: Sat Feb 07 2026 - 06:51:18 EST


On Sat, Feb 7, 2026 at 6:43 PM David Laight
<david.laight.linux@xxxxxxxxx> wrote:
>
> On Tue, 3 Feb 2026 20:14:43 +0800
> Gui-Dong Han <hanguidong02@xxxxxxxxx> wrote:
>
> > Simply copying shared data to a local variable cannot prevent data
> > races. The compiler is allowed to optimize away the local copy and
> > re-read the shared memory, causing a Time-of-Check Time-of-Use (TOCTOU)
> > issue if the data changes between the check and the usage.
>
> While the compiler is allowed to do this, is there any indication
> that either gcc or clang have ever done it?
> ISTR someone saying that they never did - although I thought that
> was the original justification for adding ACCESS_ONCE().

This patch addresses an issue originally reported by Ben Hutchings
during his review of the 5.10 stable queue. Ben explicitly pointed out
the potential race and suggested using READ/WRITE_ONCE to enforce
local variable usage [1]. Many of his recent suggestions on stable
patches have been adopted by maintainers like Greg KH.

>
> READ_ONCE() also includes barriers to guarantee ordering between cpu.
> These are empty on x86 but add code to architectures where the cpu
> can (IIRC) re-order writes.
> This is worst on alpha but affects arm and probably ppc.
>
> For these cases is it enough to add the compile-time barrier() after
> reading the variable to a local.
> That will also generate better code on x86.
>
> The WRITE_ONCE() aren't needed at all, the compilers definitely
> guarantee to do a single memory access for aligned accesses that are
> less than the size of a word.

Following his report, I consulted the LKMM documentation. The access
pattern here fits the definition of a data race, and the documentation
recommends annotating these accesses to eliminate the data race [2].

>
> This all stinks of being an AI generated patch.

I assure you this patch was not generated by AI. It was created based
on feedback from an experienced developer and kernel documentation.

Thanks.

[1] https://lore.kernel.org/all/6fe17868327207e8b850cf9f88b7dc58b2021f73.camel@xxxxxxxxxxxxxxx/
[2] https://elixir.bootlin.com/linux/v6.19-rc5/source/tools/memory-model/Documentation/explanation.txt#L2231