From 99214b61387847a2fd8bfcb2cb2b1b902d642a53 Mon Sep 17 00:00:00 2001
From: Tomas Vondra <tomas@vondra.me>
Date: Sat, 21 Nov 2026 17:08:54 +0100
Subject: [PATCH v6 2/2] Allow using spread checkpoints when enabling/disabling
 checksums

While enabling data checksums, the process has to rewrite all data
pages, and then perform checkpoints at certain points. The writes due to
updating data checksums on pages may be throttled (by using the
cost_delay/cost_limit parameters), but the checkpoints were always
requested as CHECKPOINT_FAST. That can be very disruptive.

This applies even to disabling data checksums. In this case no pages
need to be rewritten to update the data checksums, but the checkpoints
are still needed and may trigger a lot of I/O. So a seemingly cheap
operation (disabling checksums) may get rather disruptive.

This commit allows requesting spread (throttled) checkpoints while
enabling or disabling data checksums in a running cluster, to limit the
impact on the rest of the system. It introduces a new "fast" parameter
for functions initiating the data checksum state change. The default
"fast=true" means the requested checkpoints are still "fast."

Original patch by Daniel Gustafsson, part of the f19c0eccae96 work, but
removed to reduce scope of the initial commit. Revived by me, with some
minor cleanups and improvements.

Author: Tomas Vondra <tomas@vondra.me>
Author: Daniel Gustafsson <daniel@yesql.se>
Reviewed-by: Daniel Gustafsson <daniel@yesql.se>
Reviewed-by: Ewan Young <kdbase.hack@gmail.com>
Reviewed-by: Fujii Masao <masao.fujii@gmail.com>
Reviewed-by: Rui Zhao <zhaorui126@gmail.com>
Discussion: https://postgr.es/m/37745926-4213-49a3-b628-4136e9e49f9b@vondra.me
---
 doc/src/sgml/func/func-admin.sgml             | 22 ++++++-
 doc/src/sgml/wal.sgml                         |  5 +-
 src/backend/access/transam/xlog.c             | 31 +++++++--
 src/backend/postmaster/datachecksum_state.c   | 64 ++++++++++++++++---
 src/include/access/xlog.h                     |  4 +-
 src/include/catalog/pg_proc.dat               | 12 ++--
 .../test_checksums/t/DataChecksums/Utils.pm   | 24 ++++++-
 7 files changed, 134 insertions(+), 28 deletions(-)

diff --git a/doc/src/sgml/func/func-admin.sgml b/doc/src/sgml/func/func-admin.sgml
index ed872264f02..a7c4aae27a3 100644
--- a/doc/src/sgml/func/func-admin.sgml
+++ b/doc/src/sgml/func/func-admin.sgml
@@ -3163,7 +3163,7 @@ SELECT convert_from(pg_read_binary_file('file_in_utf8.txt'), 'UTF8');
         <indexterm>
          <primary>pg_enable_data_checksums</primary>
         </indexterm>
-        <function>pg_enable_data_checksums</function> ( <optional><parameter>cost_delay</parameter> <type>int</type> <optional>, <parameter>cost_limit</parameter> <type>int</type></optional></optional> )
+        <function>pg_enable_data_checksums</function> ( <optional><parameter>cost_delay</parameter> <type>int</type> <optional>, <parameter>cost_limit</parameter> <type>int</type> <optional>, <parameter>fast</parameter> <type>boolean</type></optional></optional></optional> )
         <returnvalue>void</returnvalue>
        </para>
        <para>
@@ -3185,6 +3185,15 @@ SELECT convert_from(pg_read_binary_file('file_in_utf8.txt'), 'UTF8');
        <para>
         This function is restricted to superusers.
        </para>
+       <para>
+        The <parameter>fast</parameter> parameter specifies whether the checkpoints
+        performed are fast or spread.
+        When set to <literal>true</literal> the checkpoints are fast, which may cause
+        a spike in I/O. When set to <literal>false</literal>, the checkpoints are
+        spread (throttled), which may increase the time needed to enable data checksums,
+        but it limits the impact on the system.
+        The default value is <literal>true</literal>.
+       </para>
        </entry>
       </row>
 
@@ -3193,7 +3202,7 @@ SELECT convert_from(pg_read_binary_file('file_in_utf8.txt'), 'UTF8');
         <indexterm>
          <primary>pg_disable_data_checksums</primary>
         </indexterm>
-        <function>pg_disable_data_checksums</function> ()
+        <function>pg_disable_data_checksums</function> ( <optional><parameter>fast</parameter> <type>boolean</type> <literal>DEFAULT</literal> <literal>true</literal></optional> )
         <returnvalue>void</returnvalue>
        </para>
        <para>
@@ -3206,6 +3215,15 @@ SELECT convert_from(pg_read_binary_file('file_in_utf8.txt'), 'UTF8');
        <para>
         This function is restricted to superusers.
        </para>
+       <para>
+        The <parameter>fast</parameter> parameter specifies whether the checkpoints
+        performed are fast or spread.
+        When set to <literal>true</literal> the checkpoints are fast, which may cause
+        a spike in I/O. When set to <literal>false</literal>, the checkpoints are
+        spread (throttled), which may increase the time needed to disable data checksums,
+        but it limits the impact on the system.
+        The default value is <literal>true</literal>.
+       </para>
        </entry>
       </row>
      </tbody>
diff --git a/doc/src/sgml/wal.sgml b/doc/src/sgml/wal.sgml
index 9af09d06a86..19c729703bb 100644
--- a/doc/src/sgml/wal.sgml
+++ b/doc/src/sgml/wal.sgml
@@ -402,7 +402,10 @@
     <para>
       Checkpoints have to be performed at certain points - both when enabling
       and disabling data checksums, which may generate of lot of writes due to
-      flushing dirty pages.
+      flushing dirty pages. The impact may be reduced by requresting spread
+      checkpoints using the <parameter>fast</parameter> parameter of the
+      <function>pg_enable_data_checksums()</function> and
+      <function>pg_disable_data_checksums()</function> functions.
     </para>
 
     <para>
diff --git a/src/backend/access/transam/xlog.c b/src/backend/access/transam/xlog.c
index fd37ea4f607..b5c01efa29a 100644
--- a/src/backend/access/transam/xlog.c
+++ b/src/backend/access/transam/xlog.c
@@ -4881,15 +4881,24 @@ SetDataChecksumsOnInProgress(void)
  * state can be changed to "on". Once the state is "on" checksums will be both
  * written and verified.
  *
+ * 'fast' determines whether the checkpoints requested before progressing to
+ * the next phase are fast (CHECKPOINT_FAST) or spread.
+ *
  * This function blocks until all backends in the cluster have acknowledged the
  * state transition.
  */
 void
-SetDataChecksumsOn(void)
+SetDataChecksumsOn(bool fast)
 {
 	uint64		barrier;
 	bool		persist;
 	XLogRecPtr	recptr;
+	int			flags;
+
+	/* determine flags for the checkpoint(s) */
+	flags = CHECKPOINT_FORCE | CHECKPOINT_WAIT;
+	if (fast)
+		flags |= CHECKPOINT_FAST;
 
 	SpinLockAcquire(&XLogCtl->info_lck);
 
@@ -4903,7 +4912,7 @@ SetDataChecksumsOn(void)
 		SpinLockRelease(&XLogCtl->info_lck);
 		elog(WARNING,
 			 "cannot set data checksums to \"on\", current state is not \"inprogress-on\", disabling");
-		SetDataChecksumsOff();
+		SetDataChecksumsOff(fast);
 		return;
 	}
 
@@ -4923,7 +4932,7 @@ SetDataChecksumsOn(void)
 
 	INJECTION_POINT("datachecksums-on-before-checkpoint", NULL);
 
-	RequestCheckpoint(CHECKPOINT_FORCE | CHECKPOINT_WAIT | CHECKPOINT_FAST);
+	RequestCheckpoint(flags);
 
 	INJECTION_POINT("datachecksums-on-after-checkpoint", NULL);
 
@@ -4961,14 +4970,24 @@ SetDataChecksumsOn(void)
  * backends which have yet to observe the state change from "on" won't get
  * validation errors on concurrently modified pages. Once all backends have
  * changed to "inprogress-off", the barrier for moving to "off" can be emitted.
+ *
+ * 'fast' determines whether the checkpoints requested before progressing to
+ * the next phase are fast (CHECKPOINT_FAST) or spread.
+ *
  * This function blocks until all backends in the cluster have acknowledged the
  * state transition.
  */
 void
-SetDataChecksumsOff(void)
+SetDataChecksumsOff(bool fast)
 {
 	uint64		barrier;
 	XLogRecPtr	recptr;
+	int			flags;
+
+	/* determine flags for the checkpoint */
+	flags = CHECKPOINT_FORCE | CHECKPOINT_WAIT;
+	if (fast)
+		flags |= CHECKPOINT_FAST;
 
 	SpinLockAcquire(&XLogCtl->info_lck);
 
@@ -5008,7 +5027,7 @@ SetDataChecksumsOff(void)
 		MyProc->delayChkptFlags &= ~DELAY_CHKPT_START;
 		END_CRIT_SECTION();
 
-		RequestCheckpoint(CHECKPOINT_FORCE | CHECKPOINT_WAIT | CHECKPOINT_FAST);
+		RequestCheckpoint(flags);
 		WaitForProcSignalBarrier(barrier);
 
 		/*
@@ -5044,7 +5063,7 @@ SetDataChecksumsOff(void)
 	MyProc->delayChkptFlags &= ~DELAY_CHKPT_START;
 	END_CRIT_SECTION();
 
-	RequestCheckpoint(CHECKPOINT_FORCE | CHECKPOINT_WAIT | CHECKPOINT_FAST);
+	RequestCheckpoint(flags);
 	WaitForProcSignalBarrier(barrier);
 }
 
diff --git a/src/backend/postmaster/datachecksum_state.c b/src/backend/postmaster/datachecksum_state.c
index e2b673a96b5..2a9f02e66b9 100644
--- a/src/backend/postmaster/datachecksum_state.c
+++ b/src/backend/postmaster/datachecksum_state.c
@@ -325,6 +325,7 @@ typedef struct DataChecksumsStateStruct
 	DataChecksumsWorkerOperation launch_operation;
 	int			launch_cost_delay;
 	int			launch_cost_limit;
+	bool		launch_fast_checkpoint;
 
 	/*
 	 * Is a launcher process currently running?  This is set by the main
@@ -358,6 +359,7 @@ typedef struct DataChecksumsStateStruct
 	DataChecksumsWorkerOperation operation;
 	int			cost_delay;
 	int			cost_limit;
+	bool		fast_checkpoint;
 
 	/*
 	 * Signaling between the launcher and the worker process. Protected by
@@ -400,7 +402,8 @@ static DataChecksumsWorkerOperation operation;
 /* Prototypes */
 static void StartDataChecksumsWorkerLauncher(DataChecksumsWorkerOperation op,
 											 int cost_delay,
-											 int cost_limit);
+											 int cost_limit,
+											 bool fast);
 static void ErrorOnInvalidDatabases(void);
 static bool ProcessSingleRelationFork(Relation reln, ForkNumber forkNum, BufferAccessStrategy strategy);
 static void ResetDataChecksumsProgressCounters(void);
@@ -569,6 +572,8 @@ AbsorbDataChecksumsBarrier(ProcSignalBarrierType barrier)
 Datum
 disable_data_checksums(PG_FUNCTION_ARGS)
 {
+	bool		fast = PG_GETARG_BOOL(0);
+
 	PreventCommandDuringRecovery("pg_disable_data_checksums()");
 
 	if (!superuser())
@@ -576,7 +581,7 @@ disable_data_checksums(PG_FUNCTION_ARGS)
 				errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
 				errmsg("must be superuser to change data checksum state"));
 
-	StartDataChecksumsWorkerLauncher(DISABLE_DATACHECKSUMS, 0, 0);
+	StartDataChecksumsWorkerLauncher(DISABLE_DATACHECKSUMS, 0, 0, fast);
 	PG_RETURN_VOID();
 }
 
@@ -590,6 +595,7 @@ enable_data_checksums(PG_FUNCTION_ARGS)
 {
 	int			cost_delay = PG_GETARG_INT32(0);
 	int			cost_limit = PG_GETARG_INT32(1);
+	bool		fast = PG_GETARG_BOOL(2);
 
 	PreventCommandDuringRecovery("pg_enable_data_checksums()");
 
@@ -619,7 +625,7 @@ enable_data_checksums(PG_FUNCTION_ARGS)
 	 */
 	ErrorOnInvalidDatabases();
 
-	StartDataChecksumsWorkerLauncher(ENABLE_DATACHECKSUMS, cost_delay, cost_limit);
+	StartDataChecksumsWorkerLauncher(ENABLE_DATACHECKSUMS, cost_delay, cost_limit, fast);
 
 	PG_RETURN_VOID();
 }
@@ -639,7 +645,8 @@ enable_data_checksums(PG_FUNCTION_ARGS)
 static void
 StartDataChecksumsWorkerLauncher(DataChecksumsWorkerOperation op,
 								 int cost_delay,
-								 int cost_limit)
+								 int cost_limit,
+								 bool fast)
 {
 	BackgroundWorker bgw;
 	BackgroundWorkerHandle *bgw_handle;
@@ -659,6 +666,7 @@ StartDataChecksumsWorkerLauncher(DataChecksumsWorkerOperation op,
 	DataChecksumState->launch_operation = op;
 	DataChecksumState->launch_cost_delay = cost_delay;
 	DataChecksumState->launch_cost_limit = cost_limit;
+	DataChecksumState->launch_fast_checkpoint = fast;
 
 	/* Is the launcher already running? If so, what is it doing? */
 	running = DataChecksumState->launcher_running;
@@ -1153,7 +1161,20 @@ launcher_exit(int code, Datum arg)
 	 * the state to off since processing cannot be resumed.
 	 */
 	if (DataChecksumsInProgressOn())
-		SetDataChecksumsOff();
+	{
+		bool		fast_checkpoint;
+
+		/*
+		 * Get the current value of the launch_fast_checkpoint flag. It might
+		 * have been updated while the launcher was already running, so make
+		 * sure to follow the locking protocol.
+		 */
+		LWLockAcquire(DataChecksumsWorkerLock, LW_EXCLUSIVE);
+		fast_checkpoint = DataChecksumState->launch_fast_checkpoint;
+		LWLockRelease(DataChecksumsWorkerLock);
+
+		SetDataChecksumsOff(fast_checkpoint);
+	}
 
 	LWLockAcquire(DataChecksumsWorkerLock, LW_EXCLUSIVE);
 	if (launcher_running)
@@ -1293,6 +1314,7 @@ DataChecksumsWorkerLauncherMain(Datum arg)
 	DataChecksumState->operation = operation;
 	DataChecksumState->cost_delay = DataChecksumState->launch_cost_delay;
 	DataChecksumState->cost_limit = DataChecksumState->launch_cost_limit;
+	DataChecksumState->fast_checkpoint = DataChecksumState->launch_fast_checkpoint;
 	LWLockRelease(DataChecksumsWorkerLock);
 
 	/*
@@ -1309,6 +1331,8 @@ again:
 
 	if (operation == ENABLE_DATACHECKSUMS)
 	{
+		bool		fast_checkpoint;
+
 		/*
 		 * If we are asked to enable checksums in a cluster which already has
 		 * checksums enabled, exit immediately as there is nothing more to do.
@@ -1345,23 +1369,42 @@ again:
 					errmsg("unable to enable data checksums in cluster"));
 		}
 
+		/*
+		 * Get the current value of the fast_checkpoint flag, in case it was
+		 * updated while the worker was running.
+		 */
+		LWLockAcquire(DataChecksumsWorkerLock, LW_EXCLUSIVE);
+		fast_checkpoint = DataChecksumState->fast_checkpoint;
+		LWLockRelease(DataChecksumsWorkerLock);
+
 		/*
 		 * Data checksums have been set on all pages, set the state to on in
 		 * order to instruct backends to validate checksums on reading.
 		 */
-		SetDataChecksumsOn();
+		SetDataChecksumsOn(fast_checkpoint);
 
 		ereport(LOG,
 				errmsg("data checksums are now enabled"));
 	}
 	else if (operation == DISABLE_DATACHECKSUMS)
 	{
+		bool		fast_checkpoint;
+
 		ereport(LOG,
 				errmsg("disabling data checksums requested"));
 
 		pgstat_progress_update_param(PROGRESS_DATACHECKSUMS_PHASE,
 									 PROGRESS_DATACHECKSUMS_PHASE_DISABLING);
-		SetDataChecksumsOff();
+
+		/*
+		 * Get the current value of the fast_checkpoint flag, in case it was
+		 * updated while the worker was running.
+		 */
+		LWLockAcquire(DataChecksumsWorkerLock, LW_EXCLUSIVE);
+		fast_checkpoint = DataChecksumState->fast_checkpoint;
+		LWLockRelease(DataChecksumsWorkerLock);
+
+		SetDataChecksumsOff(fast_checkpoint);
 		ereport(LOG,
 				errmsg("data checksums are now disabled"));
 	}
@@ -1389,6 +1432,7 @@ done:
 		operation = DataChecksumState->launch_operation;
 		DataChecksumState->cost_delay = DataChecksumState->launch_cost_delay;
 		DataChecksumState->cost_limit = DataChecksumState->launch_cost_limit;
+		DataChecksumState->fast_checkpoint = DataChecksumState->launch_fast_checkpoint;
 
 		/*
 		 * If the user started, but aborted processing, and then changed their
@@ -1478,7 +1522,7 @@ ProcessAllDatabases(void)
 			 * Disable checksums on cluster, because we failed one of the
 			 * databases and this is an all or nothing process.
 			 */
-			SetDataChecksumsOff();
+			SetDataChecksumsOff(DataChecksumState->fast_checkpoint);
 			ereport(ERROR,
 					errcode(ERRCODE_INSUFFICIENT_RESOURCES),
 					errmsg("data checksums failed to get enabled in all databases, aborting"),
@@ -1883,7 +1927,8 @@ DataChecksumsWorkerMain(Datum arg)
 			break;
 		}
 		if ((DataChecksumState->launch_cost_delay != DataChecksumState->cost_delay)
-			|| (DataChecksumState->launch_cost_limit != DataChecksumState->cost_limit))
+			|| (DataChecksumState->launch_cost_limit != DataChecksumState->cost_limit)
+			|| (DataChecksumState->launch_fast_checkpoint != DataChecksumState->fast_checkpoint))
 		{
 			costs_updated = true;
 			VacuumCostDelay = DataChecksumState->launch_cost_delay;
@@ -1892,6 +1937,7 @@ DataChecksumsWorkerMain(Datum arg)
 
 			DataChecksumState->cost_delay = DataChecksumState->launch_cost_delay;
 			DataChecksumState->cost_limit = DataChecksumState->launch_cost_limit;
+			DataChecksumState->fast_checkpoint = DataChecksumState->launch_fast_checkpoint;
 		}
 		else
 			costs_updated = false;
diff --git a/src/include/access/xlog.h b/src/include/access/xlog.h
index 2bf5714b51e..c21d4942c06 100644
--- a/src/include/access/xlog.h
+++ b/src/include/access/xlog.h
@@ -270,8 +270,8 @@ extern bool DataChecksumsOn(void);
 extern bool DataChecksumsOff(void);
 extern bool DataChecksumsInProgressOn(void);
 extern void SetDataChecksumsOnInProgress(void);
-extern void SetDataChecksumsOn(void);
-extern void SetDataChecksumsOff(void);
+extern void SetDataChecksumsOn(bool fast);
+extern void SetDataChecksumsOff(bool fast);
 extern const char *show_data_checksums(void);
 extern const char *get_checksum_state_string(uint32 state);
 extern void InitLocalDataChecksumState(void);
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 50fb182cb79..9084eb8561d 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -12485,13 +12485,15 @@
 # data checksum management functions
 { oid => '6507', descr => 'disable data checksums',
   proname => 'pg_disable_data_checksums', provolatile => 'v',
-  proparallel => 'r', prorettype => 'void', proargtypes => '',
-  prosrc => 'disable_data_checksums', proacl => '{POSTGRES=X}' },
+  proparallel => 'r', prorettype => 'void', proargtypes => 'bool',
+  proallargtypes => '{bool}', proargmodes => '{i}', proargnames => '{fast}',
+  proargdefaults => '{true}', prosrc => 'disable_data_checksums',
+  proacl => '{POSTGRES=X}' },
 { oid => '6506', descr => 'enable data checksums',
   proname => 'pg_enable_data_checksums', provolatile => 'v', proparallel => 'r',
-  prorettype => 'void', proargtypes => 'int4 int4',
-  proallargtypes => '{int4,int4}', proargmodes => '{i,i}',
-  proargnames => '{cost_delay,cost_limit}', proargdefaults => '{0,100}',
+  prorettype => 'void', proargtypes => 'int4 int4 bool',
+  proallargtypes => '{int4,int4,bool}', proargmodes => '{i,i,i}',
+  proargnames => '{cost_delay,cost_limit,fast}', proargdefaults => '{0,100,true}',
   prosrc => 'enable_data_checksums', proacl => '{POSTGRES=X}' },
 
 # collation management functions
diff --git a/src/test/modules/test_checksums/t/DataChecksums/Utils.pm b/src/test/modules/test_checksums/t/DataChecksums/Utils.pm
index 3aa533d777f..77c208dd5fd 100644
--- a/src/test/modules/test_checksums/t/DataChecksums/Utils.pm
+++ b/src/test/modules/test_checksums/t/DataChecksums/Utils.pm
@@ -118,6 +118,11 @@ If defined, the function will wait for the state defined in this parameter,
 waiting timing out, before returning.  The function will wait for
 $PostgreSQL::Test::Utils::timeout_default seconds before timing out.
 
+=item fast
+
+The B<fast> determines if checkpoints will be fast or spread, default is
+'true' (which means fast checkpoints).
+
 =back
 
 =cut
@@ -130,13 +135,14 @@ sub enable_data_checksums
 	# Set sane defaults for the parameters
 	$params{cost_delay} = 0 unless (defined($params{cost_delay}));
 	$params{cost_limit} = 100 unless (defined($params{cost_limit}));
+	$params{fast} = 'true' unless (defined($params{fast}));
 
 	my $query = <<'EOQ';
-SELECT pg_enable_data_checksums(%s, %s);
+SELECT pg_enable_data_checksums(%s, %s, %s);
 EOQ
 
 	$postgresnode->safe_psql('postgres',
-		sprintf($query, $params{cost_delay}, $params{cost_limit}));
+		sprintf($query, $params{cost_delay}, $params{cost_limit}, $params{fast}));
 
 	if (defined($params{wait}))
 	{
@@ -166,6 +172,11 @@ waiting timing out, before returning.  The function will wait for
 $PostgreSQL::Test::Utils::timeout_default seconds before timing out.
 Unlike in C<enable_data_checksums> the value of the parameter is discarded.
 
+=item fast
+
+The B<fast> determines if checkpoints will be fast or spread, default is
+'true' (which means fast checkpoints).
+
 =back
 
 =cut
@@ -175,8 +186,15 @@ sub disable_data_checksums
 	my $postgresnode = shift;
 	my %params = @_;
 
+	# Set sane defaults for the parameters
+	$params{fast} = 'true' unless (defined($params{fast}));
+
+	my $query = <<'EOQ';
+SELECT pg_disable_data_checksums(%s);
+EOQ
+
 	$postgresnode->safe_psql('postgres',
-		'SELECT pg_disable_data_checksums();');
+		sprintf($query, $params{fast}));
 
 	if (defined($params{wait}))
 	{
-- 
2.56.1

