fill_seq_fork_with_data() initializes buffer without lock

Andres Freund <andres@anarazel.de>

From: Andres Freund <andres@anarazel.de>
To: pgsql-hackers@postgresql.org
Date: 2023-04-04T18:55:01Z
Lists: pgsql-hackers
Hi,

Look at:

static void
fill_seq_fork_with_data(Relation rel, HeapTuple tuple, ForkNumber forkNum)
{
	Buffer		buf;
	Page		page;
	sequence_magic *sm;
	OffsetNumber offnum;

	/* Initialize first page of relation with special magic number */

	buf = ReadBufferExtended(rel, forkNum, P_NEW, RBM_NORMAL, NULL);
	Assert(BufferGetBlockNumber(buf) == 0);

	page = BufferGetPage(buf);

	PageInit(page, BufferGetPageSize(buf), sizeof(sequence_magic));
	sm = (sequence_magic *) PageGetSpecialPointer(page);
	sm->magic = SEQ_MAGIC;

	/* Now insert sequence tuple */

	LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);


Clearly we are modifying the page (via PageInit()), without holding a buffer
lock, which is only acquired subsequently.

It's clearly unlikely to cause bad consequences - the sequence doesn't yet
really exist, and we haven't seen any reports of a problem - but it doesn't
seem quite impossible that it would cause problems.

As far as I can tell, this goes back to the initial addition of the sequence
code, in e8647c45d66a - I'm too lazy to figure out whether it possibly wasn't
a problem in 1997 for some reason.

Greetings,

Andres Freund



Commits

  1. sequences: Lock buffer before initializing page