Skip to content

Commit 2a275e6

Browse files
committed
Fix pg_buffercache to release buffer partition locks in reverse order,
and add a note about why. This is not tremendously important right now, probably, but it will get more urgent if NUM_BUFFER_PARTITIONS is increased as much as proposed.
1 parent 82b3684 commit 2a275e6

File tree

1 file changed

+11
-4
lines changed

1 file changed

+11
-4
lines changed

contrib/pg_buffercache/pg_buffercache_pages.c

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
* pg_buffercache_pages.c
44
* display some contents of the buffer cache
55
*
6-
* $PostgreSQL: pgsql/contrib/pg_buffercache/pg_buffercache_pages.c,v 1.12 2007/04/07 16:09:14 momjian Exp $
6+
* $PostgreSQL: pgsql/contrib/pg_buffercache/pg_buffercache_pages.c,v 1.13 2007/07/16 21:20:36 tgl Exp $
77
*-------------------------------------------------------------------------
88
*/
99
#include "postgres.h"
@@ -110,7 +110,8 @@ pg_buffercache_pages(PG_FUNCTION_ARGS)
110110
/*
111111
* To get a consistent picture of the buffer state, we must lock all
112112
* partitions of the buffer map. Needless to say, this is horrible
113-
* for concurrency...
113+
* for concurrency. Must grab locks in increasing order to avoid
114+
* possible deadlocks.
114115
*/
115116
for (i = 0; i < NUM_BUFFER_PARTITIONS; i++)
116117
LWLockAcquire(FirstBufMappingLock + i, LW_SHARED);
@@ -145,8 +146,14 @@ pg_buffercache_pages(PG_FUNCTION_ARGS)
145146
UnlockBufHdr(bufHdr);
146147
}
147148

148-
/* Release Buffer map. */
149-
for (i = 0; i < NUM_BUFFER_PARTITIONS; i++)
149+
/*
150+
* And release locks. We do this in reverse order for two reasons:
151+
* (1) Anyone else who needs more than one of the locks will be trying
152+
* to lock them in increasing order; we don't want to release the other
153+
* process until it can get all the locks it needs.
154+
* (2) This avoids O(N^2) behavior inside LWLockRelease.
155+
*/
156+
for (i = NUM_BUFFER_PARTITIONS; --i >= 0;)
150157
LWLockRelease(FirstBufMappingLock + i);
151158
}
152159

0 commit comments

Comments
 (0)