Skip to content

Commit d9c85aa

Browse files
committed
Add memory barriers to ensure write/read order of TLI and LSN
1 parent 208f9ad commit d9c85aa

File tree

2 files changed

+15
-1
lines changed

2 files changed

+15
-1
lines changed

contrib/pg_tde/src/access/pg_tde_xlog_smgr.c

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,14 @@ TDEXLogGetEncKeyLsn()
8888
static void
8989
TDEXLogSetEncKeyLocation(WALLocation loc)
9090
{
91+
/*
92+
* Write TLI first and then LSN. The barrier ensures writes won't be
93+
* reordered. When reading, the opposite must be done (with a matching
94+
* barrier in between), so we always see a valid TLI after observing a
95+
* valid LSN.
96+
*/
9197
pg_atomic_write_u32(&EncryptionState->enc_key_tli, loc.tli);
98+
pg_write_barrier();
9299
pg_atomic_write_u64(&EncryptionState->enc_key_lsn, loc.lsn);
93100
}
94101

@@ -304,7 +311,7 @@ tdeheap_xlog_seg_write(int fd, const void *buf, size_t count, off_t offset,
304311
*
305312
* This func called with WALWriteLock held, so no need in any extra sync.
306313
*/
307-
if (EncryptionKey.type !=MAP_ENTRY_EMPTY && TDEXLogGetEncKeyLsn() == 0)
314+
if (EncryptionKey.type != MAP_ENTRY_EMPTY && TDEXLogGetEncKeyLsn() == 0)
308315
{
309316
XLogRecPtr lsn;
310317

@@ -353,7 +360,12 @@ tdeheap_xlog_seg_read(int fd, void *buf, size_t count, off_t offset,
353360
keys = pg_tde_fetch_wal_keys(start);
354361
}
355362

363+
/*
364+
* The barrier ensures that we always read a vaild TLI after the valid
365+
* LSN. See the comment in TDEXLogSetEncKeyLocation()
366+
*/
356367
write_key_lsn = TDEXLogGetEncKeyLsn();
368+
pg_read_barrier();
357369

358370
if (!XLogRecPtrIsInvalid(write_key_lsn))
359371
{

contrib/pg_tde/src/include/pg_tde_fe.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,8 @@ static int tde_fe_error_level = 0;
8888
#define FreeFile(file) fclose(file)
8989

9090
#define pg_fsync(fd) fsync(fd)
91+
92+
#define pg_read_barrier() NULL
9193
#endif /* FRONTEND */
9294

9395
#endif /* PG_TDE_EREPORT_H */

0 commit comments

Comments
 (0)