Fix memory leak and inefficiency in CREATE DATABASE ... STRATEGY WAL_LOG
authorAndres Freund <[email protected]>
Tue, 21 Mar 2023 04:57:40 +0000 (21:57 -0700)
committerAndres Freund <[email protected]>
Wed, 22 Mar 2023 16:20:34 +0000 (09:20 -0700)
RelationCopyStorageUsingBuffer() did not free the strategies used to access
the source / target relation. They memory was released at the end of the
transaction, but when using a template database with a lot of relations, the
temporary leak can become big prohibitively big.

RelationCopyStorageUsingBuffer() acquired the buffer for the target relation
with RBM_NORMAL, therefore requiring a read of a block guaranteed to be
zero. Use RBM_ZERO_AND_LOCK instead.

Reviewed-by: Robert Haas <[email protected]>
Discussion: https://postgr.es/m/20230321070113[email protected]
Backpatch: 15-, where STRATEGY WAL_LOG was introduced

src/backend/storage/buffer/bufmgr.c

index 0a05577b68df21349fe1dc2a1018b2985e66dbb8..95212a39416eece3a448f12cb8f82dc53a9f78e7 100644 (file)
@@ -3833,11 +3833,9 @@ RelationCopyStorageUsingBuffer(RelFileLocator srclocator,
                LockBuffer(srcBuf, BUFFER_LOCK_SHARE);
                srcPage = BufferGetPage(srcBuf);
 
-               /* Use P_NEW to extend the destination relation. */
                dstBuf = ReadBufferWithoutRelcache(dstlocator, forkNum, blkno,
-                                                                                  RBM_NORMAL, bstrategy_dst,
+                                                                                  RBM_ZERO_AND_LOCK, bstrategy_dst,
                                                                                   permanent);
-               LockBuffer(dstBuf, BUFFER_LOCK_EXCLUSIVE);
                dstPage = BufferGetPage(dstBuf);
 
                START_CRIT_SECTION();
@@ -3855,6 +3853,9 @@ RelationCopyStorageUsingBuffer(RelFileLocator srclocator,
                UnlockReleaseBuffer(dstBuf);
                UnlockReleaseBuffer(srcBuf);
        }
+
+       FreeAccessStrategy(bstrategy_src);
+       FreeAccessStrategy(bstrategy_dst);
 }
 
 /* ---------------------------------------------------------------------