>From ed21c52a5c3ed5837fda5a16871be7505e6bb02d Mon Sep 17 00:00:00 2001
From: Andres Freund <andres@anarazel.de>
Date: Sun, 7 Jul 2013 18:39:43 +0200
Subject: [PATCH] Add syscache for filenode to oid mapping

This cache is problematic because formallyindexes used by syscaches needs to be
unique, this one is not. This is "just" because of 0/InvalidOid are stored in
pg_class.relfilenode for nailed/shared catalog relations. Even if we should
never query those values we need to make sure nothing bad can happen in that
case. So add a 'filter' to the syscache infrastructure that allows to specify a
function which prevents tuples from ending up in a catcache.
---
 src/backend/utils/cache/catcache.c | 25 ++++++++++++++++-----
 src/backend/utils/cache/relcache.c | 45 +++++++++++++++++++++++++++++++++++++
 src/backend/utils/cache/syscache.c | 46 +++++++++++++++++++++++++++++++++++++-
 src/include/utils/catcache.h       | 21 ++++++++++-------
 src/include/utils/relcache.h       |  6 +++++
 src/include/utils/syscache.h       |  1 +
 6 files changed, 129 insertions(+), 15 deletions(-)

diff --git a/src/backend/utils/cache/catcache.c b/src/backend/utils/cache/catcache.c
index d12da76..536de2d 100644
--- a/src/backend/utils/cache/catcache.c
+++ b/src/backend/utils/cache/catcache.c
@@ -726,7 +726,8 @@ InitCatCache(int id,
 			 Oid indexoid,
 			 int nkeys,
 			 const int *key,
-			 int nbuckets)
+			 int nbuckets,
+			 PGFunction filter)
 {
 	CatCache   *cp;
 	MemoryContext oldcxt;
@@ -787,6 +788,7 @@ InitCatCache(int id,
 	cp->cc_indexoid = indexoid;
 	cp->cc_relisshared = false; /* temporary */
 	cp->cc_tupdesc = (TupleDesc) NULL;
+	cp->cc_filter = filter;
 	cp->cc_ntup = 0;
 	cp->cc_nbuckets = nbuckets;
 	cp->cc_nkeys = nkeys;
@@ -1162,6 +1164,18 @@ SearchCatCache(CatCache *cache,
 		}
 	}
 
+	ct = NULL;
+
+	if (cache->cc_filter != NULL &&
+		DatumGetBool(DirectFunctionCall2(cache->cc_filter,
+										 PointerGetDatum(cache),
+										 PointerGetDatum(&cur_skey))))
+	{
+		CACHE2_elog(DEBUG2, "SearchCatCache(%s): filtering lookup",
+					cache->cc_relname);
+		goto create_negative;
+	}
+
 	/*
 	 * Tuple was not found in cache, so we have to try to retrieve it directly
 	 * from the relation.  If found, we will add it to the cache; if not
@@ -1186,8 +1200,6 @@ SearchCatCache(CatCache *cache,
 								  cache->cc_nkeys,
 								  cur_skey);
 
-	ct = NULL;
-
 	while (HeapTupleIsValid(ntp = systable_getnext(scandesc)))
 	{
 		ct = CatalogCacheCreateEntry(cache, ntp,
@@ -1204,10 +1216,11 @@ SearchCatCache(CatCache *cache,
 
 	heap_close(relation, AccessShareLock);
 
+create_negative:
 	/*
-	 * If tuple was not found, we need to build a negative cache entry
-	 * containing a fake tuple.  The fake tuple has the correct key columns,
-	 * but nulls everywhere else.
+	 * If tuple was not found or filtered, we need to build a negative cache
+	 * entry containing a fake tuple.  The fake tuple has the correct key
+	 * columns, but nulls everywhere else.
 	 *
 	 * In bootstrap mode, we don't build negative entries, because the cache
 	 * invalidation mechanism isn't alive and can't clear them if the tuple
diff --git a/src/backend/utils/cache/relcache.c b/src/backend/utils/cache/relcache.c
index 66fb63b..c1eb3c4 100644
--- a/src/backend/utils/cache/relcache.c
+++ b/src/backend/utils/cache/relcache.c
@@ -4859,3 +4859,48 @@ unlink_initfile(const char *initfilename)
 			elog(LOG, "could not remove cache file \"%s\": %m", initfilename);
 	}
 }
+
+Oid
+RelidByRelfilenode(Oid reltablespace, Oid relfilenode)
+{
+	Oid			lookup_tablespace;
+	Oid			heaprel;
+	HeapTuple	tuple;
+
+	if (reltablespace == 0)
+		reltablespace = DEFAULTTABLESPACE_OID;
+
+	/* in global tablespace, has to be a shared table */
+	if (reltablespace == GLOBALTABLESPACE_OID)
+	{
+		heaprel = RelationMapFilenodeToOid(relfilenode, true);
+	}
+	else
+	{
+		/*
+		 * relations in the default tablespace are stored with InvalidOid as
+		 * pg_class."reltablespace".
+		 */
+		if (reltablespace == DEFAULTTABLESPACE_OID)
+			lookup_tablespace = InvalidOid;
+		else
+			lookup_tablespace = reltablespace;
+
+
+		tuple = SearchSysCache2(RELFILENODE,
+								lookup_tablespace,
+								relfilenode);
+		/* ok, found it */
+		if (HeapTupleIsValid(tuple))
+		{
+			heaprel = HeapTupleHeaderGetOid(tuple->t_data);
+			ReleaseSysCache(tuple);
+		}
+		/* has to be nonexistant or a nailed table, but not shared */
+		else
+		{
+			heaprel = RelationMapFilenodeToOid(relfilenode, false);
+		}
+	}
+	return heaprel;
+}
diff --git a/src/backend/utils/cache/syscache.c b/src/backend/utils/cache/syscache.c
index 1ff2f2b..0b3e901 100644
--- a/src/backend/utils/cache/syscache.c
+++ b/src/backend/utils/cache/syscache.c
@@ -110,8 +110,11 @@ struct cachedesc
 	int			nkeys;			/* # of keys needed for cache lookup */
 	int			key[4];			/* attribute numbers of key attrs */
 	int			nbuckets;		/* number of hash buckets for this cache */
+	PGFunction	filter;			/* optional filter to guarantee uniqueness */
 };
 
+static Datum filter_filenode_syscache(PG_FUNCTION_ARGS);
+
 static const struct cachedesc cacheinfo[] = {
 	{AggregateRelationId,		/* AGGFNOID */
 		AggregateFnoidIndexId,
@@ -598,6 +601,18 @@ static const struct cachedesc cacheinfo[] = {
 		},
 		64
 	},
+	{RelationRelationId,		/* RELFILENODE */
+		ClassTblspcRelfilenodeIndexId,
+		2,
+		{
+			Anum_pg_class_reltablespace,
+			Anum_pg_class_relfilenode,
+			0,
+			0
+		},
+		1024,
+		filter_filenode_syscache
+	},
 	{RelationRelationId,		/* RELNAMENSP */
 		ClassNameNspIndexId,
 		2,
@@ -834,7 +849,8 @@ InitCatalogCache(void)
 										 cacheinfo[cacheId].indoid,
 										 cacheinfo[cacheId].nkeys,
 										 cacheinfo[cacheId].key,
-										 cacheinfo[cacheId].nbuckets);
+										 cacheinfo[cacheId].nbuckets,
+										 cacheinfo[cacheId].filter);
 		if (!PointerIsValid(SysCache[cacheId]))
 			elog(ERROR, "could not initialize cache %u (%d)",
 				 cacheinfo[cacheId].reloid, cacheId);
@@ -1208,3 +1224,31 @@ oid_compare(const void *a, const void *b)
 		return 0;
 	return (oa > ob) ? 1 : -1;
 }
+
+/*
+ * Filter away lookups with a InvalidOid relfilenode - those are nailed &
+ * shared relations and are managed via relmapper not via pg_class. Because of
+ * that InvalidOid is stored in pg_class.relfilenode for those making the index
+ * not unique. Make it unique by filtering away those rows.
+ *
+ * Arguments passed:
+ *  0: catcache
+ *  1: *ScanKey[4] identifying the to-be-filtered key
+ *
+ * Return true if the argument should be considered *nonexistant*.
+ */
+static Datum
+filter_filenode_syscache(PG_FUNCTION_ARGS)
+{
+	CatCache   *cache = (CatCache *) PG_GETARG_POINTER(0);
+	ScanKeyData	*skeys  = (ScanKeyData *) PG_GETARG_POINTER(1);
+
+	if (cache->cc_nkeys != 2)
+		elog(ERROR, "invalid parameter");
+
+	/* filter away if relfilenode == 0 */
+	if (DatumGetObjectId(skeys[1].sk_argument) == InvalidOid)
+		PG_RETURN_BOOL(true);
+
+	PG_RETURN_BOOL(false);
+}
diff --git a/src/include/utils/catcache.h b/src/include/utils/catcache.h
index b6e1c97..a671d31 100644
--- a/src/include/utils/catcache.h
+++ b/src/include/utils/catcache.h
@@ -37,21 +37,22 @@
 typedef struct catcache
 {
 	int			id;				/* cache identifier --- see syscache.h */
+	int			cc_ntup;		/* # of tuples currently in this cache */
+	int			cc_nbuckets;	/* # of hash buckets in this cache */
+	int			cc_nkeys;		/* # of keys (1..CATCACHE_MAXKEYS) */
 	slist_node	cc_next;		/* list link */
 	const char *cc_relname;		/* name of relation the tuples come from */
 	Oid			cc_reloid;		/* OID of relation the tuples come from */
 	Oid			cc_indexoid;	/* OID of index matching cache keys */
 	bool		cc_relisshared; /* is relation shared across databases? */
-	TupleDesc	cc_tupdesc;		/* tuple descriptor (copied from reldesc) */
-	int			cc_ntup;		/* # of tuples currently in this cache */
-	int			cc_nbuckets;	/* # of hash buckets in this cache */
-	int			cc_nkeys;		/* # of keys (1..CATCACHE_MAXKEYS) */
+	bool		cc_isname[CATCACHE_MAXKEYS];	/* flag "name" key columns */
 	int			cc_key[CATCACHE_MAXKEYS];		/* AttrNumber of each key */
 	PGFunction	cc_hashfunc[CATCACHE_MAXKEYS];	/* hash function for each key */
 	ScanKeyData cc_skey[CATCACHE_MAXKEYS];		/* precomputed key info for
 												 * heap scans */
-	bool		cc_isname[CATCACHE_MAXKEYS];	/* flag "name" key columns */
+	TupleDesc	cc_tupdesc;		/* tuple descriptor (copied from reldesc) */
 	dlist_head	cc_lists;		/* list of CatCList structs */
+	PGFunction	cc_filter;		/* optional filter to achieve uniqueness */
 #ifdef CATCACHE_STATS
 	long		cc_searches;	/* total # searches against this cache */
 	long		cc_hits;		/* # of matches against existing entry */
@@ -74,6 +75,9 @@ typedef struct catctup
 {
 	int			ct_magic;		/* for identifying CatCTup entries */
 #define CT_MAGIC   0x57261502
+
+	uint32		hash_value;		/* hash value for this tuple's keys */
+
 	CatCache   *my_cache;		/* link to owning catcache */
 
 	/*
@@ -107,7 +111,6 @@ typedef struct catctup
 	int			refcount;		/* number of active references */
 	bool		dead;			/* dead but not yet removed? */
 	bool		negative;		/* negative cache entry? */
-	uint32		hash_value;		/* hash value for this tuple's keys */
 	HeapTupleData tuple;		/* tuple management header */
 } CatCTup;
 
@@ -116,6 +119,9 @@ typedef struct catclist
 {
 	int			cl_magic;		/* for identifying CatCList entries */
 #define CL_MAGIC   0x52765103
+
+	uint32		hash_value;		/* hash value for lookup keys */
+
 	CatCache   *my_cache;		/* link to owning catcache */
 
 	/*
@@ -144,7 +150,6 @@ typedef struct catclist
 	bool		dead;			/* dead but not yet removed? */
 	bool		ordered;		/* members listed in index order? */
 	short		nkeys;			/* number of lookup keys specified */
-	uint32		hash_value;		/* hash value for lookup keys */
 	HeapTupleData tuple;		/* header for tuple holding keys */
 	int			n_members;		/* number of member tuples */
 	CatCTup    *members[1];		/* members --- VARIABLE LENGTH ARRAY */
@@ -166,7 +171,7 @@ extern void AtEOXact_CatCache(bool isCommit);
 
 extern CatCache *InitCatCache(int id, Oid reloid, Oid indexoid,
 			 int nkeys, const int *key,
-			 int nbuckets);
+			 int nbuckets, PGFunction filter);
 extern void InitCatCachePhase2(CatCache *cache, bool touch_index);
 
 extern HeapTuple SearchCatCache(CatCache *cache,
diff --git a/src/include/utils/relcache.h b/src/include/utils/relcache.h
index 8ac2549..46172f3 100644
--- a/src/include/utils/relcache.h
+++ b/src/include/utils/relcache.h
@@ -110,6 +110,12 @@ extern void RelationCacheInitFilePreInvalidate(void);
 extern void RelationCacheInitFilePostInvalidate(void);
 extern void RelationCacheInitFileRemove(void);
 
+/*
+ * Mapping from relfilenode to oid
+ */
+extern  Oid RelidByRelfilenode(Oid reltablespace, Oid relfilenode);
+
+
 /* should be used only by relcache.c and catcache.c */
 extern bool criticalRelcachesBuilt;
 
diff --git a/src/include/utils/syscache.h b/src/include/utils/syscache.h
index e41b3d2..66d5684 100644
--- a/src/include/utils/syscache.h
+++ b/src/include/utils/syscache.h
@@ -75,6 +75,7 @@ enum SysCacheIdentifier
 	PROCNAMEARGSNSP,
 	PROCOID,
 	RANGETYPE,
+	RELFILENODE,
 	RELNAMENSP,
 	RELOID,
 	RULERELNAME,
-- 
1.8.3.251.g1462b67

