From 32da8fe04cf6f131c45a35378458190d6f7d032c Mon Sep 17 00:00:00 2001
From: Thomas Munro <thomas.munro@gmail.com>
Date: Sat, 27 Apr 2024 12:18:15 +1200
Subject: [PATCH v2 10/11] Use streaming I/O in VACUUM via write-behind.

The actual streaming I/O is managed by the BufferAccessStrategy, but to
enable that we have to give it dirty buffers and be careful to force it
to unpin anything we might truncate.
---
 src/backend/access/heap/vacuumlazy.c | 9 ++++++---
 src/backend/commands/vacuum.c        | 5 +++++
 2 files changed, 11 insertions(+), 3 deletions(-)

diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c
index 8e757c313ee..1abf0831206 100644
--- a/src/backend/access/heap/vacuumlazy.c
+++ b/src/backend/access/heap/vacuumlazy.c
@@ -1016,7 +1016,7 @@ lazy_scan_heap(LVRelState *vacrel)
 		{
 			Size		freespace = PageGetHeapFreeSpace(page);
 
-			UnlockReleaseBuffer(buf);
+			StrategyUnlockReleaseBuffer(vacrel->bstrategy, buf);
 			RecordPageWithFreeSpace(vacrel->rel, blkno, freespace);
 
 			/*
@@ -1034,7 +1034,7 @@ lazy_scan_heap(LVRelState *vacrel)
 			}
 		}
 		else
-			UnlockReleaseBuffer(buf);
+			StrategyUnlockReleaseBuffer(vacrel->bstrategy, buf);
 	}
 
 	vacrel->blkno = InvalidBlockNumber;
@@ -2200,7 +2200,7 @@ lazy_vacuum_heap_rel(LVRelState *vacrel)
 		page = BufferGetPage(buf);
 		freespace = PageGetHeapFreeSpace(page);
 
-		UnlockReleaseBuffer(buf);
+		StrategyUnlockReleaseBuffer(vacrel->bstrategy, buf);
 		RecordPageWithFreeSpace(vacrel->rel, blkno, freespace);
 		vacuumed_pages++;
 	}
@@ -2687,6 +2687,9 @@ lazy_truncate_heap(LVRelState *vacrel)
 			return;
 		}
 
+		/* Throw away write-behind work, to get rid of held pins. */
+		StrategyReset(vacrel->bstrategy);
+
 		/*
 		 * Okay to truncate.
 		 */
diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c
index b589279d49f..7a91f6f87e8 100644
--- a/src/backend/commands/vacuum.c
+++ b/src/backend/commands/vacuum.c
@@ -639,8 +639,10 @@ vacuum(List *relations, VacuumParams *params, BufferAccessStrategy bstrategy,
 				analyze_rel(vrel->oid, vrel->relation, params,
 							vrel->va_cols, in_outer_xact, bstrategy);
 
+
 				if (use_own_xacts)
 				{
+					StrategyWaitAll(bstrategy);
 					PopActiveSnapshot();
 					CommitTransactionCommand();
 				}
@@ -2216,6 +2218,9 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams *params,
 	if (rel)
 		relation_close(rel, NoLock);
 
+	/* Make sure the stategy isn't holding any pins. */
+	StrategyWaitAll(bstrategy);
+
 	/*
 	 * Complete the transaction and free all temporary memory used.
 	 */
-- 
2.44.0

