Skip to content

Commit 0e68570

Browse files
committed
Prevent potentially hazardous compiler/cpu reordering during lwlock release.
In LWLockRelease() (and in 9.4+ LWLockUpdateVar()) we release enqueued waiters using PGSemaphoreUnlock(). As there are other sources of such unlocks backends only wake up if MyProc->lwWaiting is set to false; which is only done in the aforementioned functions. Before this commit there were dangers because the store to lwWaitLink could become visible before the store to lwWaitLink. This could both happen due to compiler reordering (on most compilers) and on some platforms due to the CPU reordering stores. The possible consequence of this is that a backend stops waiting before lwWaitLink is set to NULL. If that backend then tries to acquire another lock and has to wait there the list could become corrupted once the lwWaitLink store is finally performed. Add a write memory barrier to prevent that issue. Unfortunately the barrier support has been only added in 9.2. Given that the issue has not knowingly been observed in praxis it seems sufficient to prohibit compiler reordering using volatile for 9.0 and 9.1. Actual problems due to compiler reordering are more likely anyway. Discussion: 20140210134625.GA15246@awork2.anarazel.de
1 parent ef8472b commit 0e68570

File tree

1 file changed

+12
-0
lines changed

1 file changed

+12
-0
lines changed

src/backend/storage/lmgr/lwlock.c

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727
#include "commands/async.h"
2828
#include "miscadmin.h"
2929
#include "pg_trace.h"
30+
#include "storage/barrier.h"
3031
#include "storage/ipc.h"
3132
#include "storage/predicate.h"
3233
#include "storage/proc.h"
@@ -835,6 +836,17 @@ LWLockRelease(LWLockId lockid)
835836
proc = head;
836837
head = proc->lwWaitLink;
837838
proc->lwWaitLink = NULL;
839+
/*
840+
* Guarantee that lwWaiting being unset only becomes visible once the
841+
* unlink from the link has completed. Otherwise the target backend
842+
* could be woken up for other reason and enqueue for a new lock - if
843+
* that happens before the list unlink happens, the list would end up
844+
* being corrupted.
845+
*
846+
* The barrier pairs with the SpinLockAcquire() when enqueing for
847+
* another lock.
848+
*/
849+
pg_write_barrier();
838850
proc->lwWaiting = false;
839851
PGSemaphoreUnlock(&proc->sem);
840852
}

0 commit comments

Comments
 (0)