From b8917f6b5f159ecc6c73957c7806a14f256b1608 Mon Sep 17 00:00:00 2001
From: Kuntal Ghosh <kuntal.ghosh@enterprisedb.com>
Date: Mon, 10 Apr 2017 15:43:17 +0530
Subject: [PATCH 2/2] Add GUC for max_parallel_workers upper limit

---
 src/backend/postmaster/bgworker.c | 10 ++++++++++
 src/backend/utils/misc/guc.c      |  4 ++--
 src/include/postmaster/bgworker.h |  7 +++++++
 3 files changed, 19 insertions(+), 2 deletions(-)

diff --git a/src/backend/postmaster/bgworker.c b/src/backend/postmaster/bgworker.c
index 59b13fc..d386a3a 100644
--- a/src/backend/postmaster/bgworker.c
+++ b/src/backend/postmaster/bgworker.c
@@ -941,6 +941,16 @@ RegisterDynamicBackgroundWorker(BackgroundWorker *worker,
 	 * postmaster must not take locks; a memory barrier wouldn't guarantee
 	 * anything useful.
 	 */
+
+	/*
+	 * For a parallel worker, the absolute difference between parallal worker
+	 * register count and terminate count must be less than maximum parallel
+	 * worker count limit.
+	 */
+	Assert(!parallel || abs((int)(BackgroundWorkerData->parallel_register_count -
+											 BackgroundWorkerData->parallel_terminate_count)) <=
+				MAX_PARALLEL_WORKER_LIMIT);
+
 	if (parallel && (BackgroundWorkerData->parallel_register_count -
 					 BackgroundWorkerData->parallel_terminate_count) >=
 		max_parallel_workers)
diff --git a/src/backend/utils/misc/guc.c b/src/backend/utils/misc/guc.c
index a57b175..3081cfb 100644
--- a/src/backend/utils/misc/guc.c
+++ b/src/backend/utils/misc/guc.c
@@ -2689,7 +2689,7 @@ static struct config_int ConfigureNamesInt[] =
 			NULL
 		},
 		&max_parallel_workers_per_gather,
-		2, 0, 1024,
+		2, 0, MAX_PARALLEL_WORKER_LIMIT,
 		NULL, NULL, NULL
 	},
 
@@ -2699,7 +2699,7 @@ static struct config_int ConfigureNamesInt[] =
 			NULL
 		},
 		&max_parallel_workers,
-		8, 0, 1024,
+		8, 0, MAX_PARALLEL_WORKER_LIMIT,
 		NULL, NULL, NULL
 	},
 
diff --git a/src/include/postmaster/bgworker.h b/src/include/postmaster/bgworker.h
index 51a5978..7f55f4b 100644
--- a/src/include/postmaster/bgworker.h
+++ b/src/include/postmaster/bgworker.h
@@ -41,6 +41,13 @@
 #ifndef BGWORKER_H
 #define BGWORKER_H
 
+/* GUC options */
+
+/*
+ * Maximum possible value of parallel workers.
+ */
+#define MAX_PARALLEL_WORKER_LIMIT 1024
+
 /*---------------------------------------------------------------------
  * External module API.
  *---------------------------------------------------------------------
-- 
1.8.3.1

