Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 19f8232

Browse files
committed
Fix ReadRecentBuffer for local buffers.
It incorrectly used GetBufferDescriptor instead of GetLocalBufferDescriptor, causing it to not find the correct buffer in most cases, and performing an out-of-bounds memory read in the corner case that temp_buffers > shared_buffers. It also bumped the usage-count on the buffer, even if it was previously pinned. That won't lead to crashes or incorrect results, but it's different from what the shared-buffer case does, and different from the usual code in LocalBufferAlloc. Fix that too, and make the code ordering match LocalBufferAlloc() more closely, so that it's easier to verify that it's doing the same thing. Currently, ReadRecentBuffer() is only used with non-temp relations, in WAL redo, so the broken code is currently dead code. However, it could be used by extensions. Backpatch-through: 14 Discussion: https://www.postgresql.org/message-id/2d74b46f-27c9-fb31-7f99-327a87184cc0%40iki.fi Reviewed-by: Thomas Munro, Zhang Mingli, Richard Guo
1 parent bd6cfbf commit 19f8232

File tree

1 file changed

+16
-6
lines changed

1 file changed

+16
-6
lines changed

src/backend/storage/buffer/bufmgr.c

+16-6
Original file line numberDiff line numberDiff line change
@@ -636,18 +636,28 @@ ReadRecentBuffer(RelFileNode rnode, ForkNumber forkNum, BlockNumber blockNum,
636636

637637
if (BufferIsLocal(recent_buffer))
638638
{
639-
bufHdr = GetBufferDescriptor(-recent_buffer - 1);
639+
int b = -recent_buffer - 1;
640+
641+
bufHdr = GetLocalBufferDescriptor(b);
640642
buf_state = pg_atomic_read_u32(&bufHdr->state);
641643

642644
/* Is it still valid and holding the right tag? */
643645
if ((buf_state & BM_VALID) && BUFFERTAGS_EQUAL(tag, bufHdr->tag))
644646
{
645-
/* Bump local buffer's ref and usage counts. */
647+
/*
648+
* Bump buffer's ref and usage counts. This is equivalent of
649+
* PinBuffer for a shared buffer.
650+
*/
651+
if (LocalRefCount[b] == 0)
652+
{
653+
if (BUF_STATE_GET_USAGECOUNT(buf_state) < BM_MAX_USAGE_COUNT)
654+
{
655+
buf_state += BUF_USAGECOUNT_ONE;
656+
pg_atomic_unlocked_write_u32(&bufHdr->state, buf_state);
657+
}
658+
}
659+
LocalRefCount[b]++;
646660
ResourceOwnerRememberBuffer(CurrentResourceOwner, recent_buffer);
647-
LocalRefCount[-recent_buffer - 1]++;
648-
if (BUF_STATE_GET_USAGECOUNT(buf_state) < BM_MAX_USAGE_COUNT)
649-
pg_atomic_write_u32(&bufHdr->state,
650-
buf_state + BUF_USAGECOUNT_ONE);
651661

652662
pgBufferUsage.local_blks_hit++;
653663

0 commit comments

Comments
 (0)