From 29d7e8c46fddf2c95b6dc0ff702912be5516e881 Mon Sep 17 00:00:00 2001
From: Antonin Houska <ah@cybertec.at>
Date: Mon, 23 Sep 2019 07:40:49 +0200
Subject: [PATCH 4/6] Introduce InvalidTimeLineID.

This is useful to tell the WALSegmentOpen() callback that it should determine
TLI itself. We can't pass NULL pointer because the function should return the
TLI via the argument in such a case.
---
 src/backend/access/transam/timeline.c | 10 ++++++++--
 src/backend/access/transam/xlog.c     |  1 +
 src/include/access/xlogdefs.h         |  4 ++++
 3 files changed, 13 insertions(+), 2 deletions(-)

diff --git a/src/backend/access/transam/timeline.c b/src/backend/access/transam/timeline.c
index c2ba480c70..7cb6046835 100644
--- a/src/backend/access/transam/timeline.c
+++ b/src/backend/access/transam/timeline.c
@@ -254,6 +254,8 @@ findNewestTimeLine(TimeLineID startTLI)
 	/*
 	 * The algorithm is just to probe for the existence of timeline history
 	 * files.  XXX is it useful to allow gaps in the sequence?
+	 *
+	 * XXX Should we check whether all possible timelines are in use?
 	 */
 	newestTLI = startTLI;
 
@@ -263,9 +265,13 @@ findNewestTimeLine(TimeLineID startTLI)
 		{
 			newestTLI = probeTLI;	/* probeTLI exists */
 		}
-		else
+		else if (probeTLI != MaxTimeLineID)
 		{
-			/* doesn't exist, assume we're done */
+			/*
+			 * Doesn't exist, assume we're done, but do not return
+			 * MaxTimeLineID - if caller incremented that, it'd become
+			 * InvalidTimeLineID.
+			 */
 			break;
 		}
 	}
diff --git a/src/backend/access/transam/xlog.c b/src/backend/access/transam/xlog.c
index 031733aba8..c9e01fe82d 100644
--- a/src/backend/access/transam/xlog.c
+++ b/src/backend/access/transam/xlog.c
@@ -7421,6 +7421,7 @@ StartupXLOG(void)
 		Assert(InArchiveRecovery);
 
 		ThisTimeLineID = findNewestTimeLine(recoveryTargetTLI) + 1;
+		Assert(ThisTimeLineID != InvalidTimeLineID);
 		ereport(LOG,
 				(errmsg("selected new timeline ID: %u", ThisTimeLineID)));
 
diff --git a/src/include/access/xlogdefs.h b/src/include/access/xlogdefs.h
index daded3dca0..459dc99d3e 100644
--- a/src/include/access/xlogdefs.h
+++ b/src/include/access/xlogdefs.h
@@ -51,6 +51,10 @@ typedef uint64 XLogSegNo;
  */
 typedef uint32 TimeLineID;
 
+#define InvalidTimeLineID		((TimeLineID) 0xFFFFFFFF)
+
+#define MaxTimeLineID			((TimeLineID) 0xFFFFFFFE)
+
 /*
  * Replication origin id - this is located in this file to avoid having to
  * include origin.h in a bunch of xlog related places.
-- 
2.20.1

