Fix fallback implementation of pg_atomic_write_u32().
authorAndres Freund <andres@anarazel.de>
Fri, 7 Oct 2016 23:55:15 +0000 (16:55 -0700)
committerAndres Freund <andres@anarazel.de>
Fri, 7 Oct 2016 23:55:15 +0000 (16:55 -0700)
commitb0779abb3add11d4dd745779dd81ea8ecdd00a1d
tree135943bfc4c9dcff009b43079b900a4ea0eca68a
parent0aec7f9aec8b828e074b8f2f3cbea2ec3e5c0209
Fix fallback implementation of pg_atomic_write_u32().

I somehow had assumed that in the spinlock (in turn possibly using
semaphores) based fallback atomics implementation 32 bit writes could be
done without a lock. As far as the write goes that's correct, since
postgres supports only platforms with single-copy atomicity for aligned
32bit writes.  But writing without holding the spinlock breaks
read-modify-write operations like pg_atomic_compare_exchange_u32(),
since they'll potentially "miss" a concurrent write, which can't happen
in actual hardware implementations.

In 9.6+ when using the fallback atomics implementation this could lead
to buffer header locks not being properly marked as released, and
potentially some related state corruption.  I don't see a related danger
in 9.5 (earliest release with the API), because pg_atomic_write_u32()
wasn't used in a concurrent manner there.

The state variable of local buffers, before this change, were
manipulated using pg_atomic_write_u32(), to avoid unnecessary
synchronization overhead. As that'd not be the case anymore, introduce
and use pg_atomic_unlocked_write_u32(), which does not correctly
interact with RMW operations.

This bug only caused issues when postgres is compiled on platforms
without atomics support (i.e. no common new platform), or when compiled
with --disable-atomics, which explains why this wasn't noticed in
testing.

Reported-By: Tom Lane
Discussion: <14947.1475690465@sss.pgh.pa.us>
Backpatch: 9.5-, where the atomic operations API was introduced.
src/backend/port/atomics.c
src/backend/storage/buffer/bufmgr.c
src/backend/storage/buffer/localbuf.c
src/include/port/atomics.h
src/include/port/atomics/fallback.h
src/include/port/atomics/generic.h
src/include/storage/buf_internals.h