PostgreSQL Source Code  git master
inval.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * inval.c
4  * POSTGRES cache invalidation dispatcher code.
5  *
6  * This is subtle stuff, so pay attention:
7  *
8  * When a tuple is updated or deleted, our standard visibility rules
9  * consider that it is *still valid* so long as we are in the same command,
10  * ie, until the next CommandCounterIncrement() or transaction commit.
11  * (See access/heap/heapam_visibility.c, and note that system catalogs are
12  * generally scanned under the most current snapshot available, rather than
13  * the transaction snapshot.) At the command boundary, the old tuple stops
14  * being valid and the new version, if any, becomes valid. Therefore,
15  * we cannot simply flush a tuple from the system caches during heap_update()
16  * or heap_delete(). The tuple is still good at that point; what's more,
17  * even if we did flush it, it might be reloaded into the caches by a later
18  * request in the same command. So the correct behavior is to keep a list
19  * of outdated (updated/deleted) tuples and then do the required cache
20  * flushes at the next command boundary. We must also keep track of
21  * inserted tuples so that we can flush "negative" cache entries that match
22  * the new tuples; again, that mustn't happen until end of command.
23  *
24  * Once we have finished the command, we still need to remember inserted
25  * tuples (including new versions of updated tuples), so that we can flush
26  * them from the caches if we abort the transaction. Similarly, we'd better
27  * be able to flush "negative" cache entries that may have been loaded in
28  * place of deleted tuples, so we still need the deleted ones too.
29  *
30  * If we successfully complete the transaction, we have to broadcast all
31  * these invalidation events to other backends (via the SI message queue)
32  * so that they can flush obsolete entries from their caches. Note we have
33  * to record the transaction commit before sending SI messages, otherwise
34  * the other backends won't see our updated tuples as good.
35  *
36  * When a subtransaction aborts, we can process and discard any events
37  * it has queued. When a subtransaction commits, we just add its events
38  * to the pending lists of the parent transaction.
39  *
40  * In short, we need to remember until xact end every insert or delete
41  * of a tuple that might be in the system caches. Updates are treated as
42  * two events, delete + insert, for simplicity. (If the update doesn't
43  * change the tuple hash value, catcache.c optimizes this into one event.)
44  *
45  * We do not need to register EVERY tuple operation in this way, just those
46  * on tuples in relations that have associated catcaches. We do, however,
47  * have to register every operation on every tuple that *could* be in a
48  * catcache, whether or not it currently is in our cache. Also, if the
49  * tuple is in a relation that has multiple catcaches, we need to register
50  * an invalidation message for each such catcache. catcache.c's
51  * PrepareToInvalidateCacheTuple() routine provides the knowledge of which
52  * catcaches may need invalidation for a given tuple.
53  *
54  * Also, whenever we see an operation on a pg_class, pg_attribute, or
55  * pg_index tuple, we register a relcache flush operation for the relation
56  * described by that tuple (as specified in CacheInvalidateHeapTuple()).
57  * Likewise for pg_constraint tuples for foreign keys on relations.
58  *
59  * We keep the relcache flush requests in lists separate from the catcache
60  * tuple flush requests. This allows us to issue all the pending catcache
61  * flushes before we issue relcache flushes, which saves us from loading
62  * a catcache tuple during relcache load only to flush it again right away.
63  * Also, we avoid queuing multiple relcache flush requests for the same
64  * relation, since a relcache flush is relatively expensive to do.
65  * (XXX is it worth testing likewise for duplicate catcache flush entries?
66  * Probably not.)
67  *
68  * Many subsystems own higher-level caches that depend on relcache and/or
69  * catcache, and they register callbacks here to invalidate their caches.
70  * While building a higher-level cache entry, a backend may receive a
71  * callback for the being-built entry or one of its dependencies. This
72  * implies the new higher-level entry would be born stale, and it might
73  * remain stale for the life of the backend. Many caches do not prevent
74  * that. They rely on DDL for can't-miss catalog changes taking
75  * AccessExclusiveLock on suitable objects. (For a change made with less
76  * locking, backends might never read the change.) The relation cache,
77  * however, needs to reflect changes from CREATE INDEX CONCURRENTLY no later
78  * than the beginning of the next transaction. Hence, when a relevant
79  * invalidation callback arrives during a build, relcache.c reattempts that
80  * build. Caches with similar needs could do likewise.
81  *
82  * If a relcache flush is issued for a system relation that we preload
83  * from the relcache init file, we must also delete the init file so that
84  * it will be rebuilt during the next backend restart. The actual work of
85  * manipulating the init file is in relcache.c, but we keep track of the
86  * need for it here.
87  *
88  * Currently, inval messages are sent without regard for the possibility
89  * that the object described by the catalog tuple might be a session-local
90  * object such as a temporary table. This is because (1) this code has
91  * no practical way to tell the difference, and (2) it is not certain that
92  * other backends don't have catalog cache or even relcache entries for
93  * such tables, anyway; there is nothing that prevents that. It might be
94  * worth trying to avoid sending such inval traffic in the future, if those
95  * problems can be overcome cheaply.
96  *
97  * When wal_level=logical, write invalidations into WAL at each command end to
98  * support the decoding of the in-progress transactions. See
99  * CommandEndInvalidationMessages.
100  *
101  * Portions Copyright (c) 1996-2021, PostgreSQL Global Development Group
102  * Portions Copyright (c) 1994, Regents of the University of California
103  *
104  * IDENTIFICATION
105  * src/backend/utils/cache/inval.c
106  *
107  *-------------------------------------------------------------------------
108  */
109 #include "postgres.h"
110 
111 #include <limits.h>
112 
113 #include "access/htup_details.h"
114 #include "access/xact.h"
115 #include "catalog/catalog.h"
116 #include "catalog/pg_constraint.h"
117 #include "miscadmin.h"
118 #include "storage/sinval.h"
119 #include "storage/smgr.h"
120 #include "utils/catcache.h"
121 #include "utils/guc.h"
122 #include "utils/inval.h"
123 #include "utils/memdebug.h"
124 #include "utils/memutils.h"
125 #include "utils/rel.h"
126 #include "utils/relmapper.h"
127 #include "utils/snapmgr.h"
128 #include "utils/syscache.h"
129 
130 
131 /*
132  * Pending requests are stored as ready-to-send SharedInvalidationMessages.
133  * We keep the messages themselves in arrays in TopTransactionContext
134  * (there are separate arrays for catcache and relcache messages). Control
135  * information is kept in a chain of TransInvalidationInfo structs, also
136  * allocated in TopTransactionContext. (We could keep a subtransaction's
137  * TransInvalidationInfo in its CurTransactionContext; but that's more
138  * wasteful not less so, since in very many scenarios it'd be the only
139  * allocation in the subtransaction's CurTransactionContext.)
140  *
141  * We can store the message arrays densely, and yet avoid moving data around
142  * within an array, because within any one subtransaction we need only
143  * distinguish between messages emitted by prior commands and those emitted
144  * by the current command. Once a command completes and we've done local
145  * processing on its messages, we can fold those into the prior-commands
146  * messages just by changing array indexes in the TransInvalidationInfo
147  * struct. Similarly, we need distinguish messages of prior subtransactions
148  * from those of the current subtransaction only until the subtransaction
149  * completes, after which we adjust the array indexes in the parent's
150  * TransInvalidationInfo to include the subtransaction's messages.
151  *
152  * The ordering of the individual messages within a command's or
153  * subtransaction's output is not considered significant, although this
154  * implementation happens to preserve the order in which they were queued.
155  * (Previous versions of this code did not preserve it.)
156  *
157  * For notational convenience, control information is kept in two-element
158  * arrays, the first for catcache messages and the second for relcache
159  * messages.
160  */
161 #define CatCacheMsgs 0
162 #define RelCacheMsgs 1
163 
164 /* Pointers to main arrays in TopTransactionContext */
165 typedef struct InvalMessageArray
166 {
167  SharedInvalidationMessage *msgs; /* palloc'd array (can be expanded) */
168  int maxmsgs; /* current allocated size of array */
170 
172 
173 /* Control information for one logical group of messages */
174 typedef struct InvalidationMsgsGroup
175 {
176  int firstmsg[2]; /* first index in relevant array */
177  int nextmsg[2]; /* last+1 index */
179 
180 /* Macros to help preserve InvalidationMsgsGroup abstraction */
181 #define SetSubGroupToFollow(targetgroup, priorgroup, subgroup) \
182  do { \
183  (targetgroup)->firstmsg[subgroup] = \
184  (targetgroup)->nextmsg[subgroup] = \
185  (priorgroup)->nextmsg[subgroup]; \
186  } while (0)
187 
188 #define SetGroupToFollow(targetgroup, priorgroup) \
189  do { \
190  SetSubGroupToFollow(targetgroup, priorgroup, CatCacheMsgs); \
191  SetSubGroupToFollow(targetgroup, priorgroup, RelCacheMsgs); \
192  } while (0)
193 
194 #define NumMessagesInSubGroup(group, subgroup) \
195  ((group)->nextmsg[subgroup] - (group)->firstmsg[subgroup])
196 
197 #define NumMessagesInGroup(group) \
198  (NumMessagesInSubGroup(group, CatCacheMsgs) + \
199  NumMessagesInSubGroup(group, RelCacheMsgs))
200 
201 
202 /*----------------
203  * Invalidation messages are divided into two groups:
204  * 1) events so far in current command, not yet reflected to caches.
205  * 2) events in previous commands of current transaction; these have
206  * been reflected to local caches, and must be either broadcast to
207  * other backends or rolled back from local cache when we commit
208  * or abort the transaction.
209  * Actually, we need such groups for each level of nested transaction,
210  * so that we can discard events from an aborted subtransaction. When
211  * a subtransaction commits, we append its events to the parent's groups.
212  *
213  * The relcache-file-invalidated flag can just be a simple boolean,
214  * since we only act on it at transaction commit; we don't care which
215  * command of the transaction set it.
216  *----------------
217  */
218 
219 typedef struct TransInvalidationInfo
220 {
221  /* Back link to parent transaction's info */
223 
224  /* Subtransaction nesting depth */
225  int my_level;
226 
227  /* Events emitted by current command */
229 
230  /* Events emitted by previous commands of this (sub)transaction */
232 
233  /* init file must be invalidated? */
236 
238 
239 /* GUC storage */
241 
242 /*
243  * Dynamically-registered callback functions. Current implementation
244  * assumes there won't be enough of these to justify a dynamically resizable
245  * array; it'd be easy to improve that if needed.
246  *
247  * To avoid searching in CallSyscacheCallbacks, all callbacks for a given
248  * syscache are linked into a list pointed to by syscache_callback_links[id].
249  * The link values are syscache_callback_list[] index plus 1, or 0 for none.
250  */
251 
252 #define MAX_SYSCACHE_CALLBACKS 64
253 #define MAX_RELCACHE_CALLBACKS 10
254 
255 static struct SYSCACHECALLBACK
256 {
257  int16 id; /* cache number */
258  int16 link; /* next callback index+1 for same cache */
262 
264 
265 static int syscache_callback_count = 0;
266 
267 static struct RELCACHECALLBACK
268 {
272 
273 static int relcache_callback_count = 0;
274 
275 /* ----------------------------------------------------------------
276  * Invalidation subgroup support functions
277  * ----------------------------------------------------------------
278  */
279 
280 /*
281  * AddInvalidationMessage
282  * Add an invalidation message to a (sub)group.
283  *
284  * The group must be the last active one, since we assume we can add to the
285  * end of the relevant InvalMessageArray.
286  *
287  * subgroup must be CatCacheMsgs or RelCacheMsgs.
288  */
289 static void
291  const SharedInvalidationMessage *msg)
292 {
293  InvalMessageArray *ima = &InvalMessageArrays[subgroup];
294  int nextindex = group->nextmsg[subgroup];
295 
296  if (nextindex >= ima->maxmsgs)
297  {
298  if (ima->msgs == NULL)
299  {
300  /* Create new storage array in TopTransactionContext */
301  int reqsize = 32; /* arbitrary */
302 
305  reqsize * sizeof(SharedInvalidationMessage));
306  ima->maxmsgs = reqsize;
307  Assert(nextindex == 0);
308  }
309  else
310  {
311  /* Enlarge storage array */
312  int reqsize = 2 * ima->maxmsgs;
313 
315  repalloc(ima->msgs,
316  reqsize * sizeof(SharedInvalidationMessage));
317  ima->maxmsgs = reqsize;
318  }
319  }
320  /* Okay, add message to current group */
321  ima->msgs[nextindex] = *msg;
322  group->nextmsg[subgroup]++;
323 }
324 
325 /*
326  * Append one subgroup of invalidation messages to another, resetting
327  * the source subgroup to empty.
328  */
329 static void
332  int subgroup)
333 {
334  /* Messages must be adjacent in main array */
335  Assert(dest->nextmsg[subgroup] == src->firstmsg[subgroup]);
336 
337  /* ... which makes this easy: */
338  dest->nextmsg[subgroup] = src->nextmsg[subgroup];
339 
340  /*
341  * This is handy for some callers and irrelevant for others. But we do it
342  * always, reasoning that it's bad to leave different groups pointing at
343  * the same fragment of the message array.
344  */
345  SetSubGroupToFollow(src, dest, subgroup);
346 }
347 
348 /*
349  * Process a subgroup of invalidation messages.
350  *
351  * This is a macro that executes the given code fragment for each message in
352  * a message subgroup. The fragment should refer to the message as *msg.
353  */
354 #define ProcessMessageSubGroup(group, subgroup, codeFragment) \
355  do { \
356  int _msgindex = (group)->firstmsg[subgroup]; \
357  int _endmsg = (group)->nextmsg[subgroup]; \
358  for (; _msgindex < _endmsg; _msgindex++) \
359  { \
360  SharedInvalidationMessage *msg = \
361  &InvalMessageArrays[subgroup].msgs[_msgindex]; \
362  codeFragment; \
363  } \
364  } while (0)
365 
366 /*
367  * Process a subgroup of invalidation messages as an array.
368  *
369  * As above, but the code fragment can handle an array of messages.
370  * The fragment should refer to the messages as msgs[], with n entries.
371  */
372 #define ProcessMessageSubGroupMulti(group, subgroup, codeFragment) \
373  do { \
374  int n = NumMessagesInSubGroup(group, subgroup); \
375  if (n > 0) { \
376  SharedInvalidationMessage *msgs = \
377  &InvalMessageArrays[subgroup].msgs[(group)->firstmsg[subgroup]]; \
378  codeFragment; \
379  } \
380  } while (0)
381 
382 
383 /* ----------------------------------------------------------------
384  * Invalidation group support functions
385  *
386  * These routines understand about the division of a logical invalidation
387  * group into separate physical arrays for catcache and relcache entries.
388  * ----------------------------------------------------------------
389  */
390 
391 /*
392  * Add a catcache inval entry
393  */
394 static void
396  int id, uint32 hashValue, Oid dbId)
397 {
399 
400  Assert(id < CHAR_MAX);
401  msg.cc.id = (int8) id;
402  msg.cc.dbId = dbId;
403  msg.cc.hashValue = hashValue;
404 
405  /*
406  * Define padding bytes in SharedInvalidationMessage structs to be
407  * defined. Otherwise the sinvaladt.c ringbuffer, which is accessed by
408  * multiple processes, will cause spurious valgrind warnings about
409  * undefined memory being used. That's because valgrind remembers the
410  * undefined bytes from the last local process's store, not realizing that
411  * another process has written since, filling the previously uninitialized
412  * bytes
413  */
414  VALGRIND_MAKE_MEM_DEFINED(&msg, sizeof(msg));
415 
416  AddInvalidationMessage(group, CatCacheMsgs, &msg);
417 }
418 
419 /*
420  * Add a whole-catalog inval entry
421  */
422 static void
424  Oid dbId, Oid catId)
425 {
427 
429  msg.cat.dbId = dbId;
430  msg.cat.catId = catId;
431  /* check AddCatcacheInvalidationMessage() for an explanation */
432  VALGRIND_MAKE_MEM_DEFINED(&msg, sizeof(msg));
433 
434  AddInvalidationMessage(group, CatCacheMsgs, &msg);
435 }
436 
437 /*
438  * Add a relcache inval entry
439  */
440 static void
442  Oid dbId, Oid relId)
443 {
445 
446  /*
447  * Don't add a duplicate item. We assume dbId need not be checked because
448  * it will never change. InvalidOid for relId means all relations so we
449  * don't need to add individual ones when it is present.
450  */
452  if (msg->rc.id == SHAREDINVALRELCACHE_ID &&
453  (msg->rc.relId == relId ||
454  msg->rc.relId == InvalidOid))
455  return);
456 
457  /* OK, add the item */
459  msg.rc.dbId = dbId;
460  msg.rc.relId = relId;
461  /* check AddCatcacheInvalidationMessage() for an explanation */
462  VALGRIND_MAKE_MEM_DEFINED(&msg, sizeof(msg));
463 
464  AddInvalidationMessage(group, RelCacheMsgs, &msg);
465 }
466 
467 /*
468  * Add a snapshot inval entry
469  *
470  * We put these into the relcache subgroup for simplicity.
471  */
472 static void
474  Oid dbId, Oid relId)
475 {
477 
478  /* Don't add a duplicate item */
479  /* We assume dbId need not be checked because it will never change */
481  if (msg->sn.id == SHAREDINVALSNAPSHOT_ID &&
482  msg->sn.relId == relId)
483  return);
484 
485  /* OK, add the item */
487  msg.sn.dbId = dbId;
488  msg.sn.relId = relId;
489  /* check AddCatcacheInvalidationMessage() for an explanation */
490  VALGRIND_MAKE_MEM_DEFINED(&msg, sizeof(msg));
491 
492  AddInvalidationMessage(group, RelCacheMsgs, &msg);
493 }
494 
495 /*
496  * Append one group of invalidation messages to another, resetting
497  * the source group to empty.
498  */
499 static void
502 {
505 }
506 
507 /*
508  * Execute the given function for all the messages in an invalidation group.
509  * The group is not altered.
510  *
511  * catcache entries are processed first, for reasons mentioned above.
512  */
513 static void
515  void (*func) (SharedInvalidationMessage *msg))
516 {
517  ProcessMessageSubGroup(group, CatCacheMsgs, func(msg));
518  ProcessMessageSubGroup(group, RelCacheMsgs, func(msg));
519 }
520 
521 /*
522  * As above, but the function is able to process an array of messages
523  * rather than just one at a time.
524  */
525 static void
527  void (*func) (const SharedInvalidationMessage *msgs, int n))
528 {
529  ProcessMessageSubGroupMulti(group, CatCacheMsgs, func(msgs, n));
530  ProcessMessageSubGroupMulti(group, RelCacheMsgs, func(msgs, n));
531 }
532 
533 /* ----------------------------------------------------------------
534  * private support functions
535  * ----------------------------------------------------------------
536  */
537 
538 /*
539  * RegisterCatcacheInvalidation
540  *
541  * Register an invalidation event for a catcache tuple entry.
542  */
543 static void
545  uint32 hashValue,
546  Oid dbId)
547 {
549  cacheId, hashValue, dbId);
550 }
551 
552 /*
553  * RegisterCatalogInvalidation
554  *
555  * Register an invalidation event for all catcache entries from a catalog.
556  */
557 static void
559 {
561  dbId, catId);
562 }
563 
564 /*
565  * RegisterRelcacheInvalidation
566  *
567  * As above, but register a relcache invalidation event.
568  */
569 static void
571 {
573  dbId, relId);
574 
575  /*
576  * Most of the time, relcache invalidation is associated with system
577  * catalog updates, but there are a few cases where it isn't. Quick hack
578  * to ensure that the next CommandCounterIncrement() will think that we
579  * need to do CommandEndInvalidationMessages().
580  */
581  (void) GetCurrentCommandId(true);
582 
583  /*
584  * If the relation being invalidated is one of those cached in a relcache
585  * init file, mark that we need to zap that file at commit. For simplicity
586  * invalidations for a specific database always invalidate the shared file
587  * as well. Also zap when we are invalidating whole relcache.
588  */
589  if (relId == InvalidOid || RelationIdIsInInitFile(relId))
590  transInvalInfo->RelcacheInitFileInval = true;
591 }
592 
593 /*
594  * RegisterSnapshotInvalidation
595  *
596  * Register an invalidation event for MVCC scans against a given catalog.
597  * Only needed for catalogs that don't have catcaches.
598  */
599 static void
601 {
603  dbId, relId);
604 }
605 
606 /*
607  * LocalExecuteInvalidationMessage
608  *
609  * Process a single invalidation message (which could be of any type).
610  * Only the local caches are flushed; this does not transmit the message
611  * to other backends.
612  */
613 void
615 {
616  if (msg->id >= 0)
617  {
618  if (msg->cc.dbId == MyDatabaseId || msg->cc.dbId == InvalidOid)
619  {
621 
622  SysCacheInvalidate(msg->cc.id, msg->cc.hashValue);
623 
624  CallSyscacheCallbacks(msg->cc.id, msg->cc.hashValue);
625  }
626  }
627  else if (msg->id == SHAREDINVALCATALOG_ID)
628  {
629  if (msg->cat.dbId == MyDatabaseId || msg->cat.dbId == InvalidOid)
630  {
632 
634 
635  /* CatalogCacheFlushCatalog calls CallSyscacheCallbacks as needed */
636  }
637  }
638  else if (msg->id == SHAREDINVALRELCACHE_ID)
639  {
640  if (msg->rc.dbId == MyDatabaseId || msg->rc.dbId == InvalidOid)
641  {
642  int i;
643 
644  if (msg->rc.relId == InvalidOid)
646  else
648 
649  for (i = 0; i < relcache_callback_count; i++)
650  {
651  struct RELCACHECALLBACK *ccitem = relcache_callback_list + i;
652 
653  ccitem->function(ccitem->arg, msg->rc.relId);
654  }
655  }
656  }
657  else if (msg->id == SHAREDINVALSMGR_ID)
658  {
659  /*
660  * We could have smgr entries for relations of other databases, so no
661  * short-circuit test is possible here.
662  */
663  RelFileNodeBackend rnode;
664 
665  rnode.node = msg->sm.rnode;
666  rnode.backend = (msg->sm.backend_hi << 16) | (int) msg->sm.backend_lo;
667  smgrclosenode(rnode);
668  }
669  else if (msg->id == SHAREDINVALRELMAP_ID)
670  {
671  /* We only care about our own database and shared catalogs */
672  if (msg->rm.dbId == InvalidOid)
673  RelationMapInvalidate(true);
674  else if (msg->rm.dbId == MyDatabaseId)
675  RelationMapInvalidate(false);
676  }
677  else if (msg->id == SHAREDINVALSNAPSHOT_ID)
678  {
679  /* We only care about our own database and shared catalogs */
680  if (msg->sn.dbId == InvalidOid)
682  else if (msg->sn.dbId == MyDatabaseId)
684  }
685  else
686  elog(FATAL, "unrecognized SI message ID: %d", msg->id);
687 }
688 
689 /*
690  * InvalidateSystemCaches
691  *
692  * This blows away all tuples in the system catalog caches and
693  * all the cached relation descriptors and smgr cache entries.
694  * Relation descriptors that have positive refcounts are then rebuilt.
695  *
696  * We call this when we see a shared-inval-queue overflow signal,
697  * since that tells us we've lost some shared-inval messages and hence
698  * don't know what needs to be invalidated.
699  */
700 void
702 {
704 }
705 
706 void
708 {
709  int i;
710 
713  RelationCacheInvalidate(debug_discard); /* gets smgr and relmap too */
714 
715  for (i = 0; i < syscache_callback_count; i++)
716  {
717  struct SYSCACHECALLBACK *ccitem = syscache_callback_list + i;
718 
719  ccitem->function(ccitem->arg, ccitem->id, 0);
720  }
721 
722  for (i = 0; i < relcache_callback_count; i++)
723  {
724  struct RELCACHECALLBACK *ccitem = relcache_callback_list + i;
725 
726  ccitem->function(ccitem->arg, InvalidOid);
727  }
728 }
729 
730 
731 /* ----------------------------------------------------------------
732  * public functions
733  * ----------------------------------------------------------------
734  */
735 
736 /*
737  * AcceptInvalidationMessages
738  * Read and process invalidation messages from the shared invalidation
739  * message queue.
740  *
741  * Note:
742  * This should be called as the first step in processing a transaction.
743  */
744 void
746 {
749 
750  /*----------
751  * Test code to force cache flushes anytime a flush could happen.
752  *
753  * This helps detect intermittent faults caused by code that reads a cache
754  * entry and then performs an action that could invalidate the entry, but
755  * rarely actually does so. This can spot issues that would otherwise
756  * only arise with badly timed concurrent DDL, for example.
757  *
758  * The default debug_discard_caches = 0 does no forced cache flushes.
759  *
760  * If used with CLOBBER_FREED_MEMORY,
761  * debug_discard_caches = 1 (formerly known as CLOBBER_CACHE_ALWAYS)
762  * provides a fairly thorough test that the system contains no cache-flush
763  * hazards. However, it also makes the system unbelievably slow --- the
764  * regression tests take about 100 times longer than normal.
765  *
766  * If you're a glutton for punishment, try
767  * debug_discard_caches = 3 (formerly known as CLOBBER_CACHE_RECURSIVELY).
768  * This slows things by at least a factor of 10000, so I wouldn't suggest
769  * trying to run the entire regression tests that way. It's useful to try
770  * a few simple tests, to make sure that cache reload isn't subject to
771  * internal cache-flush hazards, but after you've done a few thousand
772  * recursive reloads it's unlikely you'll learn more.
773  *----------
774  */
775 #ifdef DISCARD_CACHES_ENABLED
776  {
777  static int recursion_depth = 0;
778 
779  if (recursion_depth < debug_discard_caches)
780  {
781  recursion_depth++;
783  recursion_depth--;
784  }
785  }
786 #endif
787 }
788 
789 /*
790  * PrepareInvalidationState
791  * Initialize inval data for the current (sub)transaction.
792  */
793 static void
795 {
796  TransInvalidationInfo *myInfo;
797 
798  if (transInvalInfo != NULL &&
799  transInvalInfo->my_level == GetCurrentTransactionNestLevel())
800  return;
801 
802  myInfo = (TransInvalidationInfo *)
804  sizeof(TransInvalidationInfo));
805  myInfo->parent = transInvalInfo;
807 
808  /* Now, do we have a previous stack entry? */
809  if (transInvalInfo != NULL)
810  {
811  /* Yes; this one should be for a deeper nesting level. */
812  Assert(myInfo->my_level > transInvalInfo->my_level);
813 
814  /*
815  * The parent (sub)transaction must not have any current (i.e.,
816  * not-yet-locally-processed) messages. If it did, we'd have a
817  * semantic problem: the new subtransaction presumably ought not be
818  * able to see those events yet, but since the CommandCounter is
819  * linear, that can't work once the subtransaction advances the
820  * counter. This is a convenient place to check for that, as well as
821  * being important to keep management of the message arrays simple.
822  */
823  if (NumMessagesInGroup(&transInvalInfo->CurrentCmdInvalidMsgs) != 0)
824  elog(ERROR, "cannot start a subtransaction when there are unprocessed inval messages");
825 
826  /*
827  * MemoryContextAllocZero set firstmsg = nextmsg = 0 in each group,
828  * which is fine for the first (sub)transaction, but otherwise we need
829  * to update them to follow whatever is already in the arrays.
830  */
832  &transInvalInfo->CurrentCmdInvalidMsgs);
834  &myInfo->PriorCmdInvalidMsgs);
835  }
836  else
837  {
838  /*
839  * Here, we need only clear any array pointers left over from a prior
840  * transaction.
841  */
842  InvalMessageArrays[CatCacheMsgs].msgs = NULL;
843  InvalMessageArrays[CatCacheMsgs].maxmsgs = 0;
844  InvalMessageArrays[RelCacheMsgs].msgs = NULL;
845  InvalMessageArrays[RelCacheMsgs].maxmsgs = 0;
846  }
847 
848  transInvalInfo = myInfo;
849 }
850 
851 /*
852  * PostPrepare_Inval
853  * Clean up after successful PREPARE.
854  *
855  * Here, we want to act as though the transaction aborted, so that we will
856  * undo any syscache changes it made, thereby bringing us into sync with the
857  * outside world, which doesn't believe the transaction committed yet.
858  *
859  * If the prepared transaction is later aborted, there is nothing more to
860  * do; if it commits, we will receive the consequent inval messages just
861  * like everyone else.
862  */
863 void
865 {
866  AtEOXact_Inval(false);
867 }
868 
869 /*
870  * xactGetCommittedInvalidationMessages() is called by
871  * RecordTransactionCommit() to collect invalidation messages to add to the
872  * commit record. This applies only to commit message types, never to
873  * abort records. Must always run before AtEOXact_Inval(), since that
874  * removes the data we need to see.
875  *
876  * Remember that this runs before we have officially committed, so we
877  * must not do anything here to change what might occur *if* we should
878  * fail between here and the actual commit.
879  *
880  * see also xact_redo_commit() and xact_desc_commit()
881  */
882 int
884  bool *RelcacheInitFileInval)
885 {
886  SharedInvalidationMessage *msgarray;
887  int nummsgs;
888  int nmsgs;
889 
890  /* Quick exit if we haven't done anything with invalidation messages. */
891  if (transInvalInfo == NULL)
892  {
893  *RelcacheInitFileInval = false;
894  *msgs = NULL;
895  return 0;
896  }
897 
898  /* Must be at top of stack */
899  Assert(transInvalInfo->my_level == 1 && transInvalInfo->parent == NULL);
900 
901  /*
902  * Relcache init file invalidation requires processing both before and
903  * after we send the SI messages. However, we need not do anything unless
904  * we committed.
905  */
906  *RelcacheInitFileInval = transInvalInfo->RelcacheInitFileInval;
907 
908  /*
909  * Collect all the pending messages into a single contiguous array of
910  * invalidation messages, to simplify what needs to happen while building
911  * the commit WAL message. Maintain the order that they would be
912  * processed in by AtEOXact_Inval(), to ensure emulated behaviour in redo
913  * is as similar as possible to original. We want the same bugs, if any,
914  * not new ones.
915  */
916  nummsgs = NumMessagesInGroup(&transInvalInfo->PriorCmdInvalidMsgs) +
917  NumMessagesInGroup(&transInvalInfo->CurrentCmdInvalidMsgs);
918 
919  *msgs = msgarray = (SharedInvalidationMessage *)
921  nummsgs * sizeof(SharedInvalidationMessage));
922 
923  nmsgs = 0;
925  CatCacheMsgs,
926  (memcpy(msgarray + nmsgs,
927  msgs,
928  n * sizeof(SharedInvalidationMessage)),
929  nmsgs += n));
931  CatCacheMsgs,
932  (memcpy(msgarray + nmsgs,
933  msgs,
934  n * sizeof(SharedInvalidationMessage)),
935  nmsgs += n));
937  RelCacheMsgs,
938  (memcpy(msgarray + nmsgs,
939  msgs,
940  n * sizeof(SharedInvalidationMessage)),
941  nmsgs += n));
943  RelCacheMsgs,
944  (memcpy(msgarray + nmsgs,
945  msgs,
946  n * sizeof(SharedInvalidationMessage)),
947  nmsgs += n));
948  Assert(nmsgs == nummsgs);
949 
950  return nmsgs;
951 }
952 
953 /*
954  * ProcessCommittedInvalidationMessages is executed by xact_redo_commit() or
955  * standby_redo() to process invalidation messages. Currently that happens
956  * only at end-of-xact.
957  *
958  * Relcache init file invalidation requires processing both
959  * before and after we send the SI messages. See AtEOXact_Inval()
960  */
961 void
963  int nmsgs, bool RelcacheInitFileInval,
964  Oid dbid, Oid tsid)
965 {
966  if (nmsgs <= 0)
967  return;
968 
969  elog(trace_recovery(DEBUG4), "replaying commit with %d messages%s", nmsgs,
970  (RelcacheInitFileInval ? " and relcache file invalidation" : ""));
971 
972  if (RelcacheInitFileInval)
973  {
974  elog(trace_recovery(DEBUG4), "removing relcache init files for database %u",
975  dbid);
976 
977  /*
978  * RelationCacheInitFilePreInvalidate, when the invalidation message
979  * is for a specific database, requires DatabasePath to be set, but we
980  * should not use SetDatabasePath during recovery, since it is
981  * intended to be used only once by normal backends. Hence, a quick
982  * hack: set DatabasePath directly then unset after use.
983  */
984  if (OidIsValid(dbid))
985  DatabasePath = GetDatabasePath(dbid, tsid);
986 
988 
989  if (OidIsValid(dbid))
990  {
992  DatabasePath = NULL;
993  }
994  }
995 
996  SendSharedInvalidMessages(msgs, nmsgs);
997 
998  if (RelcacheInitFileInval)
1000 }
1001 
1002 /*
1003  * AtEOXact_Inval
1004  * Process queued-up invalidation messages at end of main transaction.
1005  *
1006  * If isCommit, we must send out the messages in our PriorCmdInvalidMsgs list
1007  * to the shared invalidation message queue. Note that these will be read
1008  * not only by other backends, but also by our own backend at the next
1009  * transaction start (via AcceptInvalidationMessages). This means that
1010  * we can skip immediate local processing of anything that's still in
1011  * CurrentCmdInvalidMsgs, and just send that list out too.
1012  *
1013  * If not isCommit, we are aborting, and must locally process the messages
1014  * in PriorCmdInvalidMsgs. No messages need be sent to other backends,
1015  * since they'll not have seen our changed tuples anyway. We can forget
1016  * about CurrentCmdInvalidMsgs too, since those changes haven't touched
1017  * the caches yet.
1018  *
1019  * In any case, reset our state to empty. We need not physically
1020  * free memory here, since TopTransactionContext is about to be emptied
1021  * anyway.
1022  *
1023  * Note:
1024  * This should be called as the last step in processing a transaction.
1025  */
1026 void
1027 AtEOXact_Inval(bool isCommit)
1028 {
1029  /* Quick exit if no messages */
1030  if (transInvalInfo == NULL)
1031  return;
1032 
1033  /* Must be at top of stack */
1034  Assert(transInvalInfo->my_level == 1 && transInvalInfo->parent == NULL);
1035 
1036  if (isCommit)
1037  {
1038  /*
1039  * Relcache init file invalidation requires processing both before and
1040  * after we send the SI messages. However, we need not do anything
1041  * unless we committed.
1042  */
1043  if (transInvalInfo->RelcacheInitFileInval)
1045 
1047  &transInvalInfo->CurrentCmdInvalidMsgs);
1048 
1051 
1052  if (transInvalInfo->RelcacheInitFileInval)
1054  }
1055  else
1056  {
1059  }
1060 
1061  /* Need not free anything explicitly */
1062  transInvalInfo = NULL;
1063 }
1064 
1065 /*
1066  * AtEOSubXact_Inval
1067  * Process queued-up invalidation messages at end of subtransaction.
1068  *
1069  * If isCommit, process CurrentCmdInvalidMsgs if any (there probably aren't),
1070  * and then attach both CurrentCmdInvalidMsgs and PriorCmdInvalidMsgs to the
1071  * parent's PriorCmdInvalidMsgs list.
1072  *
1073  * If not isCommit, we are aborting, and must locally process the messages
1074  * in PriorCmdInvalidMsgs. No messages need be sent to other backends.
1075  * We can forget about CurrentCmdInvalidMsgs too, since those changes haven't
1076  * touched the caches yet.
1077  *
1078  * In any case, pop the transaction stack. We need not physically free memory
1079  * here, since CurTransactionContext is about to be emptied anyway
1080  * (if aborting). Beware of the possibility of aborting the same nesting
1081  * level twice, though.
1082  */
1083 void
1084 AtEOSubXact_Inval(bool isCommit)
1085 {
1086  int my_level;
1088 
1089  /* Quick exit if no messages. */
1090  if (myInfo == NULL)
1091  return;
1092 
1093  /* Also bail out quickly if messages are not for this level. */
1094  my_level = GetCurrentTransactionNestLevel();
1095  if (myInfo->my_level != my_level)
1096  {
1097  Assert(myInfo->my_level < my_level);
1098  return;
1099  }
1100 
1101  if (isCommit)
1102  {
1103  /* If CurrentCmdInvalidMsgs still has anything, fix it */
1105 
1106  /*
1107  * We create invalidation stack entries lazily, so the parent might
1108  * not have one. Instead of creating one, moving all the data over,
1109  * and then freeing our own, we can just adjust the level of our own
1110  * entry.
1111  */
1112  if (myInfo->parent == NULL || myInfo->parent->my_level < my_level - 1)
1113  {
1114  myInfo->my_level--;
1115  return;
1116  }
1117 
1118  /*
1119  * Pass up my inval messages to parent. Notice that we stick them in
1120  * PriorCmdInvalidMsgs, not CurrentCmdInvalidMsgs, since they've
1121  * already been locally processed. (This would trigger the Assert in
1122  * AppendInvalidationMessageSubGroup if the parent's
1123  * CurrentCmdInvalidMsgs isn't empty; but we already checked that in
1124  * PrepareInvalidationState.)
1125  */
1127  &myInfo->PriorCmdInvalidMsgs);
1128 
1129  /* Must readjust parent's CurrentCmdInvalidMsgs indexes now */
1131  &myInfo->parent->PriorCmdInvalidMsgs);
1132 
1133  /* Pending relcache inval becomes parent's problem too */
1134  if (myInfo->RelcacheInitFileInval)
1135  myInfo->parent->RelcacheInitFileInval = true;
1136 
1137  /* Pop the transaction state stack */
1138  transInvalInfo = myInfo->parent;
1139 
1140  /* Need not free anything else explicitly */
1141  pfree(myInfo);
1142  }
1143  else
1144  {
1147 
1148  /* Pop the transaction state stack */
1149  transInvalInfo = myInfo->parent;
1150 
1151  /* Need not free anything else explicitly */
1152  pfree(myInfo);
1153  }
1154 }
1155 
1156 /*
1157  * CommandEndInvalidationMessages
1158  * Process queued-up invalidation messages at end of one command
1159  * in a transaction.
1160  *
1161  * Here, we send no messages to the shared queue, since we don't know yet if
1162  * we will commit. We do need to locally process the CurrentCmdInvalidMsgs
1163  * list, so as to flush our caches of any entries we have outdated in the
1164  * current command. We then move the current-cmd list over to become part
1165  * of the prior-cmds list.
1166  *
1167  * Note:
1168  * This should be called during CommandCounterIncrement(),
1169  * after we have advanced the command ID.
1170  */
1171 void
1173 {
1174  /*
1175  * You might think this shouldn't be called outside any transaction, but
1176  * bootstrap does it, and also ABORT issued when not in a transaction. So
1177  * just quietly return if no state to work on.
1178  */
1179  if (transInvalInfo == NULL)
1180  return;
1181 
1184 
1185  /* WAL Log per-command invalidation messages for wal_level=logical */
1186  if (XLogLogicalInfoActive())
1188 
1190  &transInvalInfo->CurrentCmdInvalidMsgs);
1191 }
1192 
1193 
1194 /*
1195  * CacheInvalidateHeapTuple
1196  * Register the given tuple for invalidation at end of command
1197  * (ie, current command is creating or outdating this tuple).
1198  * Also, detect whether a relcache invalidation is implied.
1199  *
1200  * For an insert or delete, tuple is the target tuple and newtuple is NULL.
1201  * For an update, we are called just once, with tuple being the old tuple
1202  * version and newtuple the new version. This allows avoidance of duplicate
1203  * effort during an update.
1204  */
1205 void
1207  HeapTuple tuple,
1208  HeapTuple newtuple)
1209 {
1210  Oid tupleRelId;
1211  Oid databaseId;
1212  Oid relationId;
1213 
1214  /* Do nothing during bootstrap */
1216  return;
1217 
1218  /*
1219  * We only need to worry about invalidation for tuples that are in system
1220  * catalogs; user-relation tuples are never in catcaches and can't affect
1221  * the relcache either.
1222  */
1223  if (!IsCatalogRelation(relation))
1224  return;
1225 
1226  /*
1227  * IsCatalogRelation() will return true for TOAST tables of system
1228  * catalogs, but we don't care about those, either.
1229  */
1230  if (IsToastRelation(relation))
1231  return;
1232 
1233  /*
1234  * If we're not prepared to queue invalidation messages for this
1235  * subtransaction level, get ready now.
1236  */
1238 
1239  /*
1240  * First let the catcache do its thing
1241  */
1242  tupleRelId = RelationGetRelid(relation);
1243  if (RelationInvalidatesSnapshotsOnly(tupleRelId))
1244  {
1245  databaseId = IsSharedRelation(tupleRelId) ? InvalidOid : MyDatabaseId;
1246  RegisterSnapshotInvalidation(databaseId, tupleRelId);
1247  }
1248  else
1249  PrepareToInvalidateCacheTuple(relation, tuple, newtuple,
1251 
1252  /*
1253  * Now, is this tuple one of the primary definers of a relcache entry? See
1254  * comments in file header for deeper explanation.
1255  *
1256  * Note we ignore newtuple here; we assume an update cannot move a tuple
1257  * from being part of one relcache entry to being part of another.
1258  */
1259  if (tupleRelId == RelationRelationId)
1260  {
1261  Form_pg_class classtup = (Form_pg_class) GETSTRUCT(tuple);
1262 
1263  relationId = classtup->oid;
1264  if (classtup->relisshared)
1265  databaseId = InvalidOid;
1266  else
1267  databaseId = MyDatabaseId;
1268  }
1269  else if (tupleRelId == AttributeRelationId)
1270  {
1271  Form_pg_attribute atttup = (Form_pg_attribute) GETSTRUCT(tuple);
1272 
1273  relationId = atttup->attrelid;
1274 
1275  /*
1276  * KLUGE ALERT: we always send the relcache event with MyDatabaseId,
1277  * even if the rel in question is shared (which we can't easily tell).
1278  * This essentially means that only backends in this same database
1279  * will react to the relcache flush request. This is in fact
1280  * appropriate, since only those backends could see our pg_attribute
1281  * change anyway. It looks a bit ugly though. (In practice, shared
1282  * relations can't have schema changes after bootstrap, so we should
1283  * never come here for a shared rel anyway.)
1284  */
1285  databaseId = MyDatabaseId;
1286  }
1287  else if (tupleRelId == IndexRelationId)
1288  {
1289  Form_pg_index indextup = (Form_pg_index) GETSTRUCT(tuple);
1290 
1291  /*
1292  * When a pg_index row is updated, we should send out a relcache inval
1293  * for the index relation. As above, we don't know the shared status
1294  * of the index, but in practice it doesn't matter since indexes of
1295  * shared catalogs can't have such updates.
1296  */
1297  relationId = indextup->indexrelid;
1298  databaseId = MyDatabaseId;
1299  }
1300  else if (tupleRelId == ConstraintRelationId)
1301  {
1302  Form_pg_constraint constrtup = (Form_pg_constraint) GETSTRUCT(tuple);
1303 
1304  /*
1305  * Foreign keys are part of relcache entries, too, so send out an
1306  * inval for the table that the FK applies to.
1307  */
1308  if (constrtup->contype == CONSTRAINT_FOREIGN &&
1309  OidIsValid(constrtup->conrelid))
1310  {
1311  relationId = constrtup->conrelid;
1312  databaseId = MyDatabaseId;
1313  }
1314  else
1315  return;
1316  }
1317  else
1318  return;
1319 
1320  /*
1321  * Yes. We need to register a relcache invalidation event.
1322  */
1323  RegisterRelcacheInvalidation(databaseId, relationId);
1324 }
1325 
1326 /*
1327  * CacheInvalidateCatalog
1328  * Register invalidation of the whole content of a system catalog.
1329  *
1330  * This is normally used in VACUUM FULL/CLUSTER, where we haven't so much
1331  * changed any tuples as moved them around. Some uses of catcache entries
1332  * expect their TIDs to be correct, so we have to blow away the entries.
1333  *
1334  * Note: we expect caller to verify that the rel actually is a system
1335  * catalog. If it isn't, no great harm is done, just a wasted sinval message.
1336  */
1337 void
1339 {
1340  Oid databaseId;
1341 
1343 
1344  if (IsSharedRelation(catalogId))
1345  databaseId = InvalidOid;
1346  else
1347  databaseId = MyDatabaseId;
1348 
1349  RegisterCatalogInvalidation(databaseId, catalogId);
1350 }
1351 
1352 /*
1353  * CacheInvalidateRelcache
1354  * Register invalidation of the specified relation's relcache entry
1355  * at end of command.
1356  *
1357  * This is used in places that need to force relcache rebuild but aren't
1358  * changing any of the tuples recognized as contributors to the relcache
1359  * entry by CacheInvalidateHeapTuple. (An example is dropping an index.)
1360  */
1361 void
1363 {
1364  Oid databaseId;
1365  Oid relationId;
1366 
1368 
1369  relationId = RelationGetRelid(relation);
1370  if (relation->rd_rel->relisshared)
1371  databaseId = InvalidOid;
1372  else
1373  databaseId = MyDatabaseId;
1374 
1375  RegisterRelcacheInvalidation(databaseId, relationId);
1376 }
1377 
1378 /*
1379  * CacheInvalidateRelcacheAll
1380  * Register invalidation of the whole relcache at the end of command.
1381  *
1382  * This is used by alter publication as changes in publications may affect
1383  * large number of tables.
1384  */
1385 void
1387 {
1389 
1391 }
1392 
1393 /*
1394  * CacheInvalidateRelcacheByTuple
1395  * As above, but relation is identified by passing its pg_class tuple.
1396  */
1397 void
1399 {
1400  Form_pg_class classtup = (Form_pg_class) GETSTRUCT(classTuple);
1401  Oid databaseId;
1402  Oid relationId;
1403 
1405 
1406  relationId = classtup->oid;
1407  if (classtup->relisshared)
1408  databaseId = InvalidOid;
1409  else
1410  databaseId = MyDatabaseId;
1411  RegisterRelcacheInvalidation(databaseId, relationId);
1412 }
1413 
1414 /*
1415  * CacheInvalidateRelcacheByRelid
1416  * As above, but relation is identified by passing its OID.
1417  * This is the least efficient of the three options; use one of
1418  * the above routines if you have a Relation or pg_class tuple.
1419  */
1420 void
1422 {
1423  HeapTuple tup;
1424 
1426 
1427  tup = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
1428  if (!HeapTupleIsValid(tup))
1429  elog(ERROR, "cache lookup failed for relation %u", relid);
1431  ReleaseSysCache(tup);
1432 }
1433 
1434 
1435 /*
1436  * CacheInvalidateSmgr
1437  * Register invalidation of smgr references to a physical relation.
1438  *
1439  * Sending this type of invalidation msg forces other backends to close open
1440  * smgr entries for the rel. This should be done to flush dangling open-file
1441  * references when the physical rel is being dropped or truncated. Because
1442  * these are nontransactional (i.e., not-rollback-able) operations, we just
1443  * send the inval message immediately without any queuing.
1444  *
1445  * Note: in most cases there will have been a relcache flush issued against
1446  * the rel at the logical level. We need a separate smgr-level flush because
1447  * it is possible for backends to have open smgr entries for rels they don't
1448  * have a relcache entry for, e.g. because the only thing they ever did with
1449  * the rel is write out dirty shared buffers.
1450  *
1451  * Note: because these messages are nontransactional, they won't be captured
1452  * in commit/abort WAL entries. Instead, calls to CacheInvalidateSmgr()
1453  * should happen in low-level smgr.c routines, which are executed while
1454  * replaying WAL as well as when creating it.
1455  *
1456  * Note: In order to avoid bloating SharedInvalidationMessage, we store only
1457  * three bytes of the backend ID using what would otherwise be padding space.
1458  * Thus, the maximum possible backend ID is 2^23-1.
1459  */
1460 void
1462 {
1464 
1465  msg.sm.id = SHAREDINVALSMGR_ID;
1466  msg.sm.backend_hi = rnode.backend >> 16;
1467  msg.sm.backend_lo = rnode.backend & 0xffff;
1468  msg.sm.rnode = rnode.node;
1469  /* check AddCatcacheInvalidationMessage() for an explanation */
1470  VALGRIND_MAKE_MEM_DEFINED(&msg, sizeof(msg));
1471 
1472  SendSharedInvalidMessages(&msg, 1);
1473 }
1474 
1475 /*
1476  * CacheInvalidateRelmap
1477  * Register invalidation of the relation mapping for a database,
1478  * or for the shared catalogs if databaseId is zero.
1479  *
1480  * Sending this type of invalidation msg forces other backends to re-read
1481  * the indicated relation mapping file. It is also necessary to send a
1482  * relcache inval for the specific relations whose mapping has been altered,
1483  * else the relcache won't get updated with the new filenode data.
1484  *
1485  * Note: because these messages are nontransactional, they won't be captured
1486  * in commit/abort WAL entries. Instead, calls to CacheInvalidateRelmap()
1487  * should happen in low-level relmapper.c routines, which are executed while
1488  * replaying WAL as well as when creating it.
1489  */
1490 void
1492 {
1494 
1495  msg.rm.id = SHAREDINVALRELMAP_ID;
1496  msg.rm.dbId = databaseId;
1497  /* check AddCatcacheInvalidationMessage() for an explanation */
1498  VALGRIND_MAKE_MEM_DEFINED(&msg, sizeof(msg));
1499 
1500  SendSharedInvalidMessages(&msg, 1);
1501 }
1502 
1503 
1504 /*
1505  * CacheRegisterSyscacheCallback
1506  * Register the specified function to be called for all future
1507  * invalidation events in the specified cache. The cache ID and the
1508  * hash value of the tuple being invalidated will be passed to the
1509  * function.
1510  *
1511  * NOTE: Hash value zero will be passed if a cache reset request is received.
1512  * In this case the called routines should flush all cached state.
1513  * Yes, there's a possibility of a false match to zero, but it doesn't seem
1514  * worth troubling over, especially since most of the current callees just
1515  * flush all cached state anyway.
1516  */
1517 void
1520  Datum arg)
1521 {
1522  if (cacheid < 0 || cacheid >= SysCacheSize)
1523  elog(FATAL, "invalid cache ID: %d", cacheid);
1525  elog(FATAL, "out of syscache_callback_list slots");
1526 
1527  if (syscache_callback_links[cacheid] == 0)
1528  {
1529  /* first callback for this cache */
1531  }
1532  else
1533  {
1534  /* add to end of chain, so that older callbacks are called first */
1535  int i = syscache_callback_links[cacheid] - 1;
1536 
1537  while (syscache_callback_list[i].link > 0)
1538  i = syscache_callback_list[i].link - 1;
1540  }
1541 
1546 
1548 }
1549 
1550 /*
1551  * CacheRegisterRelcacheCallback
1552  * Register the specified function to be called for all future
1553  * relcache invalidation events. The OID of the relation being
1554  * invalidated will be passed to the function.
1555  *
1556  * NOTE: InvalidOid will be passed if a cache reset request is received.
1557  * In this case the called routines should flush all cached state.
1558  */
1559 void
1561  Datum arg)
1562 {
1564  elog(FATAL, "out of relcache_callback_list slots");
1565 
1568 
1570 }
1571 
1572 /*
1573  * CallSyscacheCallbacks
1574  *
1575  * This is exported so that CatalogCacheFlushCatalog can call it, saving
1576  * this module from knowing which catcache IDs correspond to which catalogs.
1577  */
1578 void
1579 CallSyscacheCallbacks(int cacheid, uint32 hashvalue)
1580 {
1581  int i;
1582 
1583  if (cacheid < 0 || cacheid >= SysCacheSize)
1584  elog(ERROR, "invalid cache ID: %d", cacheid);
1585 
1586  i = syscache_callback_links[cacheid] - 1;
1587  while (i >= 0)
1588  {
1589  struct SYSCACHECALLBACK *ccitem = syscache_callback_list + i;
1590 
1591  Assert(ccitem->id == cacheid);
1592  ccitem->function(ccitem->arg, cacheid, hashvalue);
1593  i = ccitem->link - 1;
1594  }
1595 }
1596 
1597 /*
1598  * LogLogicalInvalidations
1599  *
1600  * Emit WAL for invalidations caused by the current command.
1601  *
1602  * This is currently only used for logging invalidations at the command end
1603  * or at commit time if any invalidations are pending.
1604  */
1605 void
1607 {
1608  xl_xact_invals xlrec;
1609  InvalidationMsgsGroup *group;
1610  int nmsgs;
1611 
1612  /* Quick exit if we haven't done anything with invalidation messages. */
1613  if (transInvalInfo == NULL)
1614  return;
1615 
1616  group = &transInvalInfo->CurrentCmdInvalidMsgs;
1617  nmsgs = NumMessagesInGroup(group);
1618 
1619  if (nmsgs > 0)
1620  {
1621  /* prepare record */
1622  memset(&xlrec, 0, MinSizeOfXactInvals);
1623  xlrec.nmsgs = nmsgs;
1624 
1625  /* perform insertion */
1626  XLogBeginInsert();
1627  XLogRegisterData((char *) (&xlrec), MinSizeOfXactInvals);
1629  XLogRegisterData((char *) msgs,
1630  n * sizeof(SharedInvalidationMessage)));
1632  XLogRegisterData((char *) msgs,
1633  n * sizeof(SharedInvalidationMessage)));
1634  XLogInsert(RM_XACT_ID, XLOG_XACT_INVALIDATIONS);
1635  }
1636 }
static void AddSnapshotInvalidationMessage(InvalidationMsgsGroup *group, Oid dbId, Oid relId)
Definition: inval.c:473
signed short int16
Definition: c.h:428
void CacheInvalidateSmgr(RelFileNodeBackend rnode)
Definition: inval.c:1461
bool IsToastRelation(Relation relation)
Definition: catalog.c:146
bool IsCatalogRelation(Relation relation)
Definition: catalog.c:104
SharedInvalSnapshotMsg sn
Definition: sinval.h:121
void(* RelcacheCallbackFunction)(Datum arg, Oid relid)
Definition: inval.h:24
#define VALGRIND_MAKE_MEM_DEFINED(addr, size)
Definition: memdebug.h:26
void CacheInvalidateHeapTuple(Relation relation, HeapTuple tuple, HeapTuple newtuple)
Definition: inval.c:1206
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
void AtEOXact_Inval(bool isCommit)
Definition: inval.c:1027
MemoryContext TopTransactionContext
Definition: mcxt.c:53
void AcceptInvalidationMessages(void)
Definition: inval.c:745
SharedInvalRelcacheMsg rc
Definition: sinval.h:118
void CommandEndInvalidationMessages(void)
Definition: inval.c:1172
static struct RELCACHECALLBACK relcache_callback_list[MAX_RELCACHE_CALLBACKS]
#define SetSubGroupToFollow(targetgroup, priorgroup, subgroup)
Definition: inval.c:181
void RelationCacheInvalidate(bool debug_discard)
Definition: relcache.c:2912
#define MAX_RELCACHE_CALLBACKS
Definition: inval.c:253
static int relcache_callback_count
Definition: inval.c:273
#define XLOG_XACT_INVALIDATIONS
Definition: xact.h:154
RelcacheCallbackFunction function
Definition: inval.c:269
#define RelCacheMsgs
Definition: inval.c:162
#define CatCacheMsgs
Definition: inval.c:161
bool RelationIdIsInInitFile(Oid relationId)
Definition: relcache.c:6510
MemoryContext CurTransactionContext
Definition: mcxt.c:54
void PrepareToInvalidateCacheTuple(Relation relation, HeapTuple tuple, HeapTuple newtuple, void(*function)(int, uint32, Oid))
Definition: catcache.c:2009
struct TransInvalidationInfo * parent
Definition: inval.c:222
void LogLogicalInvalidations(void)
Definition: inval.c:1606
static int recursion_depth
Definition: elog.c:149
void CacheInvalidateRelmap(Oid databaseId)
Definition: inval.c:1491
static TransInvalidationInfo * transInvalInfo
Definition: inval.c:237
Form_pg_class rd_rel
Definition: rel.h:109
unsigned int Oid
Definition: postgres_ext.h:31
SharedInvalidationMessage * msgs
Definition: inval.c:167
void RelationMapInvalidate(bool shared)
Definition: relmapper.c:403
#define DEBUG4
Definition: elog.h:22
int debug_discard_caches
Definition: inval.c:240
#define OidIsValid(objectId)
Definition: c.h:710
void InvalidateSystemCaches(void)
Definition: inval.c:701
int trace_recovery(int trace_level)
Definition: elog.c:3597
static void AddInvalidationMessage(InvalidationMsgsGroup *group, int subgroup, const SharedInvalidationMessage *msg)
Definition: inval.c:290
void CacheRegisterRelcacheCallback(RelcacheCallbackFunction func, Datum arg)
Definition: inval.c:1560
int16 link
Definition: inval.c:258
void pfree(void *pointer)
Definition: mcxt.c:1169
#define ProcessMessageSubGroupMulti(group, subgroup, codeFragment)
Definition: inval.c:372
#define SysCacheSize
Definition: syscache.h:116
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define ERROR
Definition: elog.h:46
#define XLogLogicalInfoActive()
Definition: xlog.h:183
#define FATAL
Definition: elog.h:49
void ReceiveSharedInvalidMessages(void(*invalFunction)(SharedInvalidationMessage *msg), void(*resetFunction)(void))
Definition: sinval.c:71
struct InvalidationMsgsGroup InvalidationMsgsGroup
#define SHAREDINVALRELCACHE_ID
Definition: sinval.h:76
SharedInvalRelmapMsg rm
Definition: sinval.h:120
#define SHAREDINVALRELMAP_ID
Definition: sinval.h:96
void(* SyscacheCallbackFunction)(Datum arg, int cacheid, uint32 hashvalue)
Definition: inval.h:23
#define MAX_SYSCACHE_CALLBACKS
Definition: inval.c:252
struct TransInvalidationInfo TransInvalidationInfo
void CacheInvalidateRelcacheByRelid(Oid relid)
Definition: inval.c:1421
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:207
void PostPrepare_Inval(void)
Definition: inval.c:864
unsigned int uint32
Definition: c.h:441
SharedInvalCatcacheMsg cc
Definition: sinval.h:116
#define MinSizeOfXactInvals
Definition: xact.h:257
void smgrclosenode(RelFileNodeBackend rnode)
Definition: smgr.c:310
SharedInvalCatalogMsg cat
Definition: sinval.h:117
void InvalidateCatalogSnapshot(void)
Definition: snapmgr.c:456
char * GetDatabasePath(Oid dbNode, Oid spcNode)
Definition: relpath.c:110
static void PrepareInvalidationState(void)
Definition: inval.c:794
static struct SYSCACHECALLBACK syscache_callback_list[MAX_SYSCACHE_CALLBACKS]
signed char int8
Definition: c.h:427
FormData_pg_index * Form_pg_index
Definition: pg_index.h:69
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1150
void XLogRegisterData(char *data, int len)
Definition: xloginsert.c:340
bool RelcacheInitFileInval
Definition: inval.c:234
XLogRecPtr XLogInsert(RmgrId rmid, uint8 info)
Definition: xloginsert.c:434
void CacheInvalidateRelcacheAll(void)
Definition: inval.c:1386
void CacheRegisterSyscacheCallback(int cacheid, SyscacheCallbackFunction func, Datum arg)
Definition: inval.c:1518
uintptr_t Datum
Definition: postgres.h:411
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1198
static void ProcessInvalidationMessages(InvalidationMsgsGroup *group, void(*func)(SharedInvalidationMessage *msg))
Definition: inval.c:514
static void AddCatcacheInvalidationMessage(InvalidationMsgsGroup *group, int id, uint32 hashValue, Oid dbId)
Definition: inval.c:395
static InvalMessageArray InvalMessageArrays[2]
Definition: inval.c:171
void CallSyscacheCallbacks(int cacheid, uint32 hashvalue)
Definition: inval.c:1579
Oid MyDatabaseId
Definition: globals.c:88
static void RegisterCatalogInvalidation(Oid dbId, Oid catId)
Definition: inval.c:558
void RelationCacheInitFilePostInvalidate(void)
Definition: relcache.c:6575
bool IsSharedRelation(Oid relationId)
Definition: catalog.c:244
static int syscache_callback_count
Definition: inval.c:265
static void AddCatalogInvalidationMessage(InvalidationMsgsGroup *group, Oid dbId, Oid catId)
Definition: inval.c:423
void * MemoryContextAllocZero(MemoryContext context, Size size)
Definition: mcxt.c:906
#define InvalidOid
Definition: postgres_ext.h:36
static void RegisterRelcacheInvalidation(Oid dbId, Oid relId)
Definition: inval.c:570
#define SHAREDINVALSNAPSHOT_ID
Definition: sinval.h:104
#define NumMessagesInGroup(group)
Definition: inval.c:197
void ProcessCommittedInvalidationMessages(SharedInvalidationMessage *msgs, int nmsgs, bool RelcacheInitFileInval, Oid dbid, Oid tsid)
Definition: inval.c:962
RelFileNode node
Definition: relfilenode.h:74
int GetCurrentTransactionNestLevel(void)
Definition: xact.c:858
char * DatabasePath
Definition: globals.c:96
static void AppendInvalidationMessageSubGroup(InvalidationMsgsGroup *dest, InvalidationMsgsGroup *src, int subgroup)
Definition: inval.c:330
FormData_pg_constraint * Form_pg_constraint
void CacheInvalidateCatalog(Oid catalogId)
Definition: inval.c:1338
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
void RelationCacheInitFilePreInvalidate(void)
Definition: relcache.c:6550
static void RegisterCatcacheInvalidation(int cacheId, uint32 hashValue, Oid dbId)
Definition: inval.c:544
#define Assert(condition)
Definition: c.h:804
bool RelationInvalidatesSnapshotsOnly(Oid relid)
Definition: syscache.c:1507
SharedInvalSmgrMsg sm
Definition: sinval.h:119
void SysCacheInvalidate(int cacheId, uint32 hashValue)
Definition: syscache.c:1483
void CatalogCacheFlushCatalog(Oid catId)
Definition: catcache.c:719
#define SetGroupToFollow(targetgroup, priorgroup)
Definition: inval.c:188
BackendId backend
Definition: relfilenode.h:75
void RelationCacheInvalidateEntry(Oid relationId)
Definition: relcache.c:2856
void SendSharedInvalidMessages(const SharedInvalidationMessage *msgs, int n)
Definition: sinval.c:49
void ResetCatalogCaches(void)
Definition: catcache.c:689
InvalidationMsgsGroup PriorCmdInvalidMsgs
Definition: inval.c:231
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:1182
struct InvalMessageArray InvalMessageArray
static int16 syscache_callback_links[SysCacheSize]
Definition: inval.c:263
uint16 backend_lo
Definition: sinval.h:92
void CacheInvalidateRelcache(Relation relation)
Definition: inval.c:1362
#define IsBootstrapProcessingMode()
Definition: miscadmin.h:406
FormData_pg_class * Form_pg_class
Definition: pg_class.h:153
void LocalExecuteInvalidationMessage(SharedInvalidationMessage *msg)
Definition: inval.c:614
#define SHAREDINVALCATALOG_ID
Definition: sinval.h:67
void AtEOSubXact_Inval(bool isCommit)
Definition: inval.c:1084
int xactGetCommittedInvalidationMessages(SharedInvalidationMessage **msgs, bool *RelcacheInitFileInval)
Definition: inval.c:883
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:863
static void AppendInvalidationMessages(InvalidationMsgsGroup *dest, InvalidationMsgsGroup *src)
Definition: inval.c:500
#define elog(elevel,...)
Definition: elog.h:232
int i
RelFileNode rnode
Definition: sinval.h:93
static void ProcessInvalidationMessagesMulti(InvalidationMsgsGroup *group, void(*func)(const SharedInvalidationMessage *msgs, int n))
Definition: inval.c:526
InvalidationMsgsGroup CurrentCmdInvalidMsgs
Definition: inval.c:228
void * arg
#define SHAREDINVALSMGR_ID
Definition: sinval.h:85
void InvalidateSystemCachesExtended(bool debug_discard)
Definition: inval.c:707
static void AddRelcacheInvalidationMessage(InvalidationMsgsGroup *group, Oid dbId, Oid relId)
Definition: inval.c:441
void CacheInvalidateRelcacheByTuple(HeapTuple classTuple)
Definition: inval.c:1398
CommandId GetCurrentCommandId(bool used)
Definition: xact.c:762
void XLogBeginInsert(void)
Definition: xloginsert.c:135
#define ProcessMessageSubGroup(group, subgroup, codeFragment)
Definition: inval.c:354
#define RelationGetRelid(relation)
Definition: rel.h:477
int nmsgs
Definition: xact.h:254
static void RegisterSnapshotInvalidation(Oid dbId, Oid relId)
Definition: inval.c:600
SyscacheCallbackFunction function
Definition: inval.c:259