1 /*-------------------------------------------------------------------------
4 * POSTGRES cache invalidation dispatcher code.
6 * This is subtle stuff, so pay attention:
8 * When a tuple is updated or deleted, our standard time qualification 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 utils/time/tqual.c, and note that system catalogs are generally
12 * scanned under SnapshotNow rules by the system, or plain user snapshots
13 * for user queries.) 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.
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.
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.
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.
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. (There are cases where
43 * it'd be possible to record just one event, but we don't currently try.)
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.
54 * Also, whenever we see an operation on a pg_class or pg_attribute tuple,
55 * we register a relcache flush operation for the relation described by that
56 * tuple. pg_class updates trigger an smgr flush operation as well.
58 * We keep the relcache and smgr flush requests in lists separate from the
59 * catcache tuple flush requests. This allows us to issue all the pending
60 * catcache flushes before we issue relcache flushes, which saves us from
61 * loading a catcache tuple during relcache load only to flush it again
62 * right away. Also, we avoid queuing multiple relcache flush requests for
63 * the same relation, since a relcache flush is relatively expensive to do.
64 * (XXX is it worth testing likewise for duplicate catcache flush entries?
67 * If a relcache flush is issued for a system relation that we preload
68 * from the relcache init file, we must also delete the init file so that
69 * it will be rebuilt during the next backend restart. The actual work of
70 * manipulating the init file is in relcache.c, but we keep track of the
73 * The request lists proper are kept in CurTransactionContext of their
74 * creating (sub)transaction, since they can be forgotten on abort of that
75 * transaction but must be kept till top-level commit otherwise. For
76 * simplicity we keep the controlling list-of-lists in TopTransactionContext.
79 * Portions Copyright (c) 1996-2008, PostgreSQL Global Development Group
80 * Portions Copyright (c) 1994, Regents of the University of California
83 * $PostgreSQL: pgsql/src/backend/utils/cache/inval.c,v 1.86 2008/06/19 21:32:56 tgl Exp $
85 *-------------------------------------------------------------------------
89 #include "access/twophase_rmgr.h"
90 #include "access/xact.h"
91 #include "catalog/catalog.h"
92 #include "miscadmin.h"
93 #include "storage/sinval.h"
94 #include "storage/smgr.h"
95 #include "utils/inval.h"
96 #include "utils/memutils.h"
97 #include "utils/rel.h"
98 #include "utils/syscache.h"
102 * To minimize palloc traffic, we keep pending requests in successively-
103 * larger chunks (a slightly more sophisticated version of an expansible
104 * array). All request types can be stored as SharedInvalidationMessage
105 * records. The ordering of requests within a list is never significant.
107 typedef struct InvalidationChunk
109 struct InvalidationChunk *next; /* list link */
110 int nitems; /* # items currently stored in chunk */
111 int maxitems; /* size of allocated array in this chunk */
112 SharedInvalidationMessage msgs[1]; /* VARIABLE LENGTH ARRAY */
113 } InvalidationChunk; /* VARIABLE LENGTH STRUCTURE */
115 typedef struct InvalidationListHeader
117 InvalidationChunk *cclist; /* list of chunks holding catcache msgs */
118 InvalidationChunk *rclist; /* list of chunks holding relcache/smgr msgs */
119 } InvalidationListHeader;
122 * Invalidation info is divided into two lists:
123 * 1) events so far in current command, not yet reflected to caches.
124 * 2) events in previous commands of current transaction; these have
125 * been reflected to local caches, and must be either broadcast to
126 * other backends or rolled back from local cache when we commit
127 * or abort the transaction.
128 * Actually, we need two such lists for each level of nested transaction,
129 * so that we can discard events from an aborted subtransaction. When
130 * a subtransaction commits, we append its lists to the parent's lists.
132 * The relcache-file-invalidated flag can just be a simple boolean,
133 * since we only act on it at transaction commit; we don't care which
134 * command of the transaction set it.
138 typedef struct TransInvalidationInfo
140 /* Back link to parent transaction's info */
141 struct TransInvalidationInfo *parent;
143 /* Subtransaction nesting depth */
146 /* head of current-command event list */
147 InvalidationListHeader CurrentCmdInvalidMsgs;
149 /* head of previous-commands event list */
150 InvalidationListHeader PriorCmdInvalidMsgs;
152 /* init file must be invalidated? */
153 bool RelcacheInitFileInval;
154 } TransInvalidationInfo;
156 static TransInvalidationInfo *transInvalInfo = NULL;
159 * Dynamically-registered callback functions. Current implementation
160 * assumes there won't be very many of these at once; could improve if needed.
163 #define MAX_CACHE_CALLBACKS 20
165 static struct CACHECALLBACK
167 int16 id; /* cache number or message type id */
168 CacheCallbackFunction function;
170 } cache_callback_list[MAX_CACHE_CALLBACKS];
172 static int cache_callback_count = 0;
174 /* info values for 2PC callback */
175 #define TWOPHASE_INFO_MSG 0 /* SharedInvalidationMessage */
176 #define TWOPHASE_INFO_FILE_BEFORE 1 /* relcache file inval */
177 #define TWOPHASE_INFO_FILE_AFTER 2 /* relcache file inval */
179 static void PersistInvalidationMessage(SharedInvalidationMessage *msg);
182 /* ----------------------------------------------------------------
183 * Invalidation list support functions
185 * These three routines encapsulate processing of the "chunked"
186 * representation of what is logically just a list of messages.
187 * ----------------------------------------------------------------
191 * AddInvalidationMessage
192 * Add an invalidation message to a list (of chunks).
194 * Note that we do not pay any great attention to maintaining the original
195 * ordering of the messages.
198 AddInvalidationMessage(InvalidationChunk **listHdr,
199 SharedInvalidationMessage *msg)
201 InvalidationChunk *chunk = *listHdr;
205 /* First time through; create initial chunk */
206 #define FIRSTCHUNKSIZE 32
207 chunk = (InvalidationChunk *)
208 MemoryContextAlloc(CurTransactionContext,
209 sizeof(InvalidationChunk) +
210 (FIRSTCHUNKSIZE - 1) *sizeof(SharedInvalidationMessage));
212 chunk->maxitems = FIRSTCHUNKSIZE;
213 chunk->next = *listHdr;
216 else if (chunk->nitems >= chunk->maxitems)
218 /* Need another chunk; double size of last chunk */
219 int chunksize = 2 * chunk->maxitems;
221 chunk = (InvalidationChunk *)
222 MemoryContextAlloc(CurTransactionContext,
223 sizeof(InvalidationChunk) +
224 (chunksize - 1) *sizeof(SharedInvalidationMessage));
226 chunk->maxitems = chunksize;
227 chunk->next = *listHdr;
230 /* Okay, add message to current chunk */
231 chunk->msgs[chunk->nitems] = *msg;
236 * Append one list of invalidation message chunks to another, resetting
237 * the source chunk-list pointer to NULL.
240 AppendInvalidationMessageList(InvalidationChunk **destHdr,
241 InvalidationChunk **srcHdr)
243 InvalidationChunk *chunk = *srcHdr;
246 return; /* nothing to do */
248 while (chunk->next != NULL)
251 chunk->next = *destHdr;
259 * Process a list of invalidation messages.
261 * This is a macro that executes the given code fragment for each message in
262 * a message chunk list. The fragment should refer to the message as *msg.
264 #define ProcessMessageList(listHdr, codeFragment) \
266 InvalidationChunk *_chunk; \
267 for (_chunk = (listHdr); _chunk != NULL; _chunk = _chunk->next) \
270 for (_cindex = 0; _cindex < _chunk->nitems; _cindex++) \
272 SharedInvalidationMessage *msg = &_chunk->msgs[_cindex]; \
279 * Process a list of invalidation messages group-wise.
281 * As above, but the code fragment can handle an array of messages.
282 * The fragment should refer to the messages as msgs[], with n entries.
284 #define ProcessMessageListMulti(listHdr, codeFragment) \
286 InvalidationChunk *_chunk; \
287 for (_chunk = (listHdr); _chunk != NULL; _chunk = _chunk->next) \
289 SharedInvalidationMessage *msgs = _chunk->msgs; \
290 int n = _chunk->nitems; \
296 /* ----------------------------------------------------------------
297 * Invalidation set support functions
299 * These routines understand about the division of a logical invalidation
300 * list into separate physical lists for catcache and relcache/smgr entries.
301 * ----------------------------------------------------------------
305 * Add a catcache inval entry
308 AddCatcacheInvalidationMessage(InvalidationListHeader *hdr,
309 int id, uint32 hashValue,
310 ItemPointer tuplePtr, Oid dbId)
312 SharedInvalidationMessage msg;
314 msg.cc.id = (int16) id;
315 msg.cc.tuplePtr = *tuplePtr;
317 msg.cc.hashValue = hashValue;
318 AddInvalidationMessage(&hdr->cclist, &msg);
322 * Add a relcache inval entry
325 AddRelcacheInvalidationMessage(InvalidationListHeader *hdr,
328 SharedInvalidationMessage msg;
330 /* Don't add a duplicate item */
331 /* We assume dbId need not be checked because it will never change */
332 ProcessMessageList(hdr->rclist,
333 if (msg->rc.id == SHAREDINVALRELCACHE_ID &&
334 msg->rc.relId == relId)
337 /* OK, add the item */
338 msg.rc.id = SHAREDINVALRELCACHE_ID;
340 msg.rc.relId = relId;
341 AddInvalidationMessage(&hdr->rclist, &msg);
345 * Add an smgr inval entry
348 AddSmgrInvalidationMessage(InvalidationListHeader *hdr,
351 SharedInvalidationMessage msg;
353 /* Don't add a duplicate item */
354 ProcessMessageList(hdr->rclist,
355 if (msg->sm.id == SHAREDINVALSMGR_ID &&
356 RelFileNodeEquals(msg->sm.rnode, rnode))
359 /* OK, add the item */
360 msg.sm.id = SHAREDINVALSMGR_ID;
361 msg.sm.rnode = rnode;
362 AddInvalidationMessage(&hdr->rclist, &msg);
366 * Append one list of invalidation messages to another, resetting
367 * the source list to empty.
370 AppendInvalidationMessages(InvalidationListHeader *dest,
371 InvalidationListHeader *src)
373 AppendInvalidationMessageList(&dest->cclist, &src->cclist);
374 AppendInvalidationMessageList(&dest->rclist, &src->rclist);
378 * Execute the given function for all the messages in an invalidation list.
379 * The list is not altered.
381 * catcache entries are processed first, for reasons mentioned above.
384 ProcessInvalidationMessages(InvalidationListHeader *hdr,
385 void (*func) (SharedInvalidationMessage *msg))
387 ProcessMessageList(hdr->cclist, func(msg));
388 ProcessMessageList(hdr->rclist, func(msg));
392 * As above, but the function is able to process an array of messages
393 * rather than just one at a time.
396 ProcessInvalidationMessagesMulti(InvalidationListHeader *hdr,
397 void (*func) (const SharedInvalidationMessage *msgs, int n))
399 ProcessMessageListMulti(hdr->cclist, func(msgs, n));
400 ProcessMessageListMulti(hdr->rclist, func(msgs, n));
403 /* ----------------------------------------------------------------
404 * private support functions
405 * ----------------------------------------------------------------
409 * RegisterCatcacheInvalidation
411 * Register an invalidation event for a catcache tuple entry.
414 RegisterCatcacheInvalidation(int cacheId,
416 ItemPointer tuplePtr,
419 AddCatcacheInvalidationMessage(&transInvalInfo->CurrentCmdInvalidMsgs,
420 cacheId, hashValue, tuplePtr, dbId);
424 * RegisterRelcacheInvalidation
426 * As above, but register a relcache invalidation event.
429 RegisterRelcacheInvalidation(Oid dbId, Oid relId)
431 AddRelcacheInvalidationMessage(&transInvalInfo->CurrentCmdInvalidMsgs,
435 * Most of the time, relcache invalidation is associated with system
436 * catalog updates, but there are a few cases where it isn't. Quick
437 * hack to ensure that the next CommandCounterIncrement() will think
438 * that we need to do CommandEndInvalidationMessages().
440 (void) GetCurrentCommandId(true);
443 * If the relation being invalidated is one of those cached in the
444 * relcache init file, mark that we need to zap that file at commit.
446 if (RelationIdIsInInitFile(relId))
447 transInvalInfo->RelcacheInitFileInval = true;
451 * RegisterSmgrInvalidation
453 * As above, but register an smgr invalidation event.
456 RegisterSmgrInvalidation(RelFileNode rnode)
458 AddSmgrInvalidationMessage(&transInvalInfo->CurrentCmdInvalidMsgs,
462 * As above, just in case there is not an associated catalog change.
464 (void) GetCurrentCommandId(true);
468 * LocalExecuteInvalidationMessage
470 * Process a single invalidation message (which could be of any type).
471 * Only the local caches are flushed; this does not transmit the message
475 LocalExecuteInvalidationMessage(SharedInvalidationMessage *msg)
481 if (msg->cc.dbId == MyDatabaseId || msg->cc.dbId == 0)
483 CatalogCacheIdInvalidate(msg->cc.id,
487 for (i = 0; i < cache_callback_count; i++)
489 struct CACHECALLBACK *ccitem = cache_callback_list + i;
491 if (ccitem->id == msg->cc.id)
492 (*ccitem->function) (ccitem->arg, InvalidOid);
496 else if (msg->id == SHAREDINVALRELCACHE_ID)
498 if (msg->rc.dbId == MyDatabaseId || msg->rc.dbId == InvalidOid)
500 RelationCacheInvalidateEntry(msg->rc.relId);
502 for (i = 0; i < cache_callback_count; i++)
504 struct CACHECALLBACK *ccitem = cache_callback_list + i;
506 if (ccitem->id == SHAREDINVALRELCACHE_ID)
507 (*ccitem->function) (ccitem->arg, msg->rc.relId);
511 else if (msg->id == SHAREDINVALSMGR_ID)
514 * We could have smgr entries for relations of other databases, so no
515 * short-circuit test is possible here.
517 smgrclosenode(msg->sm.rnode);
520 elog(FATAL, "unrecognized SI message id: %d", msg->id);
524 * InvalidateSystemCaches
526 * This blows away all tuples in the system catalog caches and
527 * all the cached relation descriptors and smgr cache entries.
528 * Relation descriptors that have positive refcounts are then rebuilt.
530 * We call this when we see a shared-inval-queue overflow signal,
531 * since that tells us we've lost some shared-inval messages and hence
532 * don't know what needs to be invalidated.
535 InvalidateSystemCaches(void)
539 ResetCatalogCaches();
540 RelationCacheInvalidate(); /* gets smgr cache too */
542 for (i = 0; i < cache_callback_count; i++)
544 struct CACHECALLBACK *ccitem = cache_callback_list + i;
546 (*ccitem->function) (ccitem->arg, InvalidOid);
551 * PrepareForTupleInvalidation
552 * Detect whether invalidation of this tuple implies invalidation
553 * of catalog/relation cache entries; if so, register inval events.
556 PrepareForTupleInvalidation(Relation relation, HeapTuple tuple)
562 /* Do nothing during bootstrap */
563 if (IsBootstrapProcessingMode())
567 * We only need to worry about invalidation for tuples that are in system
568 * relations; user-relation tuples are never in catcaches and can't affect
569 * the relcache either.
571 if (!IsSystemRelation(relation))
575 * TOAST tuples can likewise be ignored here. Note that TOAST tables are
576 * considered system relations so they are not filtered by the above test.
578 if (IsToastRelation(relation))
582 * First let the catcache do its thing
584 PrepareToInvalidateCacheTuple(relation, tuple,
585 RegisterCatcacheInvalidation);
588 * Now, is this tuple one of the primary definers of a relcache entry?
590 tupleRelId = RelationGetRelid(relation);
592 if (tupleRelId == RelationRelationId)
594 Form_pg_class classtup = (Form_pg_class) GETSTRUCT(tuple);
597 relationId = HeapTupleGetOid(tuple);
598 if (classtup->relisshared)
599 databaseId = InvalidOid;
601 databaseId = MyDatabaseId;
604 * We need to send out an smgr inval as well as a relcache inval. This
605 * is needed because other backends might possibly possess smgr cache
606 * but not relcache entries for the target relation.
608 * Note: during a pg_class row update that assigns a new relfilenode
609 * or reltablespace value, we will be called on both the old and new
610 * tuples, and thus will broadcast invalidation messages showing both
611 * the old and new RelFileNode values. This ensures that other
612 * backends will close smgr references to the old file.
614 * XXX possible future cleanup: it might be better to trigger smgr
615 * flushes explicitly, rather than indirectly from pg_class updates.
617 if (classtup->reltablespace)
618 rnode.spcNode = classtup->reltablespace;
620 rnode.spcNode = MyDatabaseTableSpace;
621 rnode.dbNode = databaseId;
622 rnode.relNode = classtup->relfilenode;
623 RegisterSmgrInvalidation(rnode);
625 else if (tupleRelId == AttributeRelationId)
627 Form_pg_attribute atttup = (Form_pg_attribute) GETSTRUCT(tuple);
629 relationId = atttup->attrelid;
632 * KLUGE ALERT: we always send the relcache event with MyDatabaseId,
633 * even if the rel in question is shared (which we can't easily tell).
634 * This essentially means that only backends in this same database
635 * will react to the relcache flush request. This is in fact
636 * appropriate, since only those backends could see our pg_attribute
637 * change anyway. It looks a bit ugly though. (In practice, shared
638 * relations can't have schema changes after bootstrap, so we should
639 * never come here for a shared rel anyway.)
641 databaseId = MyDatabaseId;
643 else if (tupleRelId == IndexRelationId)
645 Form_pg_index indextup = (Form_pg_index) GETSTRUCT(tuple);
648 * When a pg_index row is updated, we should send out a relcache inval
649 * for the index relation. As above, we don't know the shared status
650 * of the index, but in practice it doesn't matter since indexes of
651 * shared catalogs can't have such updates.
653 relationId = indextup->indexrelid;
654 databaseId = MyDatabaseId;
660 * Yes. We need to register a relcache invalidation event.
662 RegisterRelcacheInvalidation(databaseId, relationId);
666 /* ----------------------------------------------------------------
668 * ----------------------------------------------------------------
672 * AcceptInvalidationMessages
673 * Read and process invalidation messages from the shared invalidation
677 * This should be called as the first step in processing a transaction.
680 AcceptInvalidationMessages(void)
682 ReceiveSharedInvalidMessages(LocalExecuteInvalidationMessage,
683 InvalidateSystemCaches);
686 * Test code to force cache flushes anytime a flush could happen.
688 * If used with CLOBBER_FREED_MEMORY, CLOBBER_CACHE_ALWAYS provides a
689 * fairly thorough test that the system contains no cache-flush hazards.
690 * However, it also makes the system unbelievably slow --- the regression
691 * tests take about 100 times longer than normal.
693 * If you're a glutton for punishment, try CLOBBER_CACHE_RECURSIVELY. This
694 * slows things by at least a factor of 10000, so I wouldn't suggest
695 * trying to run the entire regression tests that way. It's useful to try
696 * a few simple tests, to make sure that cache reload isn't subject to
697 * internal cache-flush hazards, but after you've done a few thousand
698 * recursive reloads it's unlikely you'll learn more.
700 #if defined(CLOBBER_CACHE_ALWAYS)
702 static bool in_recursion = false;
707 InvalidateSystemCaches();
708 in_recursion = false;
711 #elif defined(CLOBBER_CACHE_RECURSIVELY)
712 InvalidateSystemCaches();
718 * Initialize inval lists at start of a main transaction.
723 Assert(transInvalInfo == NULL);
724 transInvalInfo = (TransInvalidationInfo *)
725 MemoryContextAllocZero(TopTransactionContext,
726 sizeof(TransInvalidationInfo));
727 transInvalInfo->my_level = GetCurrentTransactionNestLevel();
732 * Save the inval lists state at 2PC transaction prepare.
734 * In this phase we just generate 2PC records for all the pending invalidation
738 AtPrepare_Inval(void)
740 /* Must be at top of stack */
741 Assert(transInvalInfo != NULL && transInvalInfo->parent == NULL);
744 * Relcache init file invalidation requires processing both before and
745 * after we send the SI messages.
747 if (transInvalInfo->RelcacheInitFileInval)
748 RegisterTwoPhaseRecord(TWOPHASE_RM_INVAL_ID, TWOPHASE_INFO_FILE_BEFORE,
751 AppendInvalidationMessages(&transInvalInfo->PriorCmdInvalidMsgs,
752 &transInvalInfo->CurrentCmdInvalidMsgs);
754 ProcessInvalidationMessages(&transInvalInfo->PriorCmdInvalidMsgs,
755 PersistInvalidationMessage);
757 if (transInvalInfo->RelcacheInitFileInval)
758 RegisterTwoPhaseRecord(TWOPHASE_RM_INVAL_ID, TWOPHASE_INFO_FILE_AFTER,
764 * Clean up after successful PREPARE.
766 * Here, we want to act as though the transaction aborted, so that we will
767 * undo any syscache changes it made, thereby bringing us into sync with the
768 * outside world, which doesn't believe the transaction committed yet.
770 * If the prepared transaction is later aborted, there is nothing more to
771 * do; if it commits, we will receive the consequent inval messages just
772 * like everyone else.
775 PostPrepare_Inval(void)
777 AtEOXact_Inval(false);
782 * Initialize inval lists at start of a subtransaction.
785 AtSubStart_Inval(void)
787 TransInvalidationInfo *myInfo;
789 Assert(transInvalInfo != NULL);
790 myInfo = (TransInvalidationInfo *)
791 MemoryContextAllocZero(TopTransactionContext,
792 sizeof(TransInvalidationInfo));
793 myInfo->parent = transInvalInfo;
794 myInfo->my_level = GetCurrentTransactionNestLevel();
795 transInvalInfo = myInfo;
799 * PersistInvalidationMessage
800 * Write an invalidation message to the 2PC state file.
803 PersistInvalidationMessage(SharedInvalidationMessage *msg)
805 RegisterTwoPhaseRecord(TWOPHASE_RM_INVAL_ID, TWOPHASE_INFO_MSG,
806 msg, sizeof(SharedInvalidationMessage));
810 * inval_twophase_postcommit
811 * Process an invalidation message from the 2PC state file.
814 inval_twophase_postcommit(TransactionId xid, uint16 info,
815 void *recdata, uint32 len)
817 SharedInvalidationMessage *msg;
821 case TWOPHASE_INFO_MSG:
822 msg = (SharedInvalidationMessage *) recdata;
823 Assert(len == sizeof(SharedInvalidationMessage));
824 SendSharedInvalidMessages(msg, 1);
826 case TWOPHASE_INFO_FILE_BEFORE:
827 RelationCacheInitFileInvalidate(true);
829 case TWOPHASE_INFO_FILE_AFTER:
830 RelationCacheInitFileInvalidate(false);
841 * Process queued-up invalidation messages at end of main transaction.
843 * If isCommit, we must send out the messages in our PriorCmdInvalidMsgs list
844 * to the shared invalidation message queue. Note that these will be read
845 * not only by other backends, but also by our own backend at the next
846 * transaction start (via AcceptInvalidationMessages). This means that
847 * we can skip immediate local processing of anything that's still in
848 * CurrentCmdInvalidMsgs, and just send that list out too.
850 * If not isCommit, we are aborting, and must locally process the messages
851 * in PriorCmdInvalidMsgs. No messages need be sent to other backends,
852 * since they'll not have seen our changed tuples anyway. We can forget
853 * about CurrentCmdInvalidMsgs too, since those changes haven't touched
856 * In any case, reset the various lists to empty. We need not physically
857 * free memory here, since TopTransactionContext is about to be emptied
861 * This should be called as the last step in processing a transaction.
864 AtEOXact_Inval(bool isCommit)
868 /* Must be at top of stack */
869 Assert(transInvalInfo != NULL && transInvalInfo->parent == NULL);
872 * Relcache init file invalidation requires processing both before and
873 * after we send the SI messages. However, we need not do anything
874 * unless we committed.
876 if (transInvalInfo->RelcacheInitFileInval)
877 RelationCacheInitFileInvalidate(true);
879 AppendInvalidationMessages(&transInvalInfo->PriorCmdInvalidMsgs,
880 &transInvalInfo->CurrentCmdInvalidMsgs);
882 ProcessInvalidationMessagesMulti(&transInvalInfo->PriorCmdInvalidMsgs,
883 SendSharedInvalidMessages);
885 if (transInvalInfo->RelcacheInitFileInval)
886 RelationCacheInitFileInvalidate(false);
888 else if (transInvalInfo != NULL)
890 /* Must be at top of stack */
891 Assert(transInvalInfo->parent == NULL);
893 ProcessInvalidationMessages(&transInvalInfo->PriorCmdInvalidMsgs,
894 LocalExecuteInvalidationMessage);
897 /* Need not free anything explicitly */
898 transInvalInfo = NULL;
903 * Process queued-up invalidation messages at end of subtransaction.
905 * If isCommit, process CurrentCmdInvalidMsgs if any (there probably aren't),
906 * and then attach both CurrentCmdInvalidMsgs and PriorCmdInvalidMsgs to the
907 * parent's PriorCmdInvalidMsgs list.
909 * If not isCommit, we are aborting, and must locally process the messages
910 * in PriorCmdInvalidMsgs. No messages need be sent to other backends.
911 * We can forget about CurrentCmdInvalidMsgs too, since those changes haven't
912 * touched the caches yet.
914 * In any case, pop the transaction stack. We need not physically free memory
915 * here, since CurTransactionContext is about to be emptied anyway
916 * (if aborting). Beware of the possibility of aborting the same nesting
917 * level twice, though.
920 AtEOSubXact_Inval(bool isCommit)
922 int my_level = GetCurrentTransactionNestLevel();
923 TransInvalidationInfo *myInfo = transInvalInfo;
927 /* Must be at non-top of stack */
928 Assert(myInfo != NULL && myInfo->parent != NULL);
929 Assert(myInfo->my_level == my_level);
931 /* If CurrentCmdInvalidMsgs still has anything, fix it */
932 CommandEndInvalidationMessages();
934 /* Pass up my inval messages to parent */
935 AppendInvalidationMessages(&myInfo->parent->PriorCmdInvalidMsgs,
936 &myInfo->PriorCmdInvalidMsgs);
938 /* Pending relcache inval becomes parent's problem too */
939 if (myInfo->RelcacheInitFileInval)
940 myInfo->parent->RelcacheInitFileInval = true;
942 /* Pop the transaction state stack */
943 transInvalInfo = myInfo->parent;
945 /* Need not free anything else explicitly */
948 else if (myInfo != NULL && myInfo->my_level == my_level)
950 /* Must be at non-top of stack */
951 Assert(myInfo->parent != NULL);
953 ProcessInvalidationMessages(&myInfo->PriorCmdInvalidMsgs,
954 LocalExecuteInvalidationMessage);
956 /* Pop the transaction state stack */
957 transInvalInfo = myInfo->parent;
959 /* Need not free anything else explicitly */
965 * CommandEndInvalidationMessages
966 * Process queued-up invalidation messages at end of one command
969 * Here, we send no messages to the shared queue, since we don't know yet if
970 * we will commit. We do need to locally process the CurrentCmdInvalidMsgs
971 * list, so as to flush our caches of any entries we have outdated in the
972 * current command. We then move the current-cmd list over to become part
973 * of the prior-cmds list.
976 * This should be called during CommandCounterIncrement(),
977 * after we have advanced the command ID.
980 CommandEndInvalidationMessages(void)
983 * You might think this shouldn't be called outside any transaction, but
984 * bootstrap does it, and also ABORT issued when not in a transaction. So
985 * just quietly return if no state to work on.
987 if (transInvalInfo == NULL)
990 ProcessInvalidationMessages(&transInvalInfo->CurrentCmdInvalidMsgs,
991 LocalExecuteInvalidationMessage);
992 AppendInvalidationMessages(&transInvalInfo->PriorCmdInvalidMsgs,
993 &transInvalInfo->CurrentCmdInvalidMsgs);
998 * BeginNonTransactionalInvalidation
999 * Prepare for invalidation messages for nontransactional updates.
1001 * A nontransactional invalidation is one that must be sent whether or not
1002 * the current transaction eventually commits. We arrange for all invals
1003 * queued between this call and EndNonTransactionalInvalidation() to be sent
1004 * immediately when the latter is called.
1006 * Currently, this is only used by heap_page_prune(), and only when it is
1007 * invoked during VACUUM FULL's first pass over a table. We expect therefore
1008 * that we are not inside a subtransaction and there are no already-pending
1009 * invalidations. This could be relaxed by setting up a new nesting level of
1010 * invalidation data, but for now there's no need. Note that heap_page_prune
1011 * knows that this function does not change any state, and therefore there's
1012 * no need to worry about cleaning up if there's an elog(ERROR) before
1013 * reaching EndNonTransactionalInvalidation (the invals will just be thrown
1014 * away if that happens).
1017 BeginNonTransactionalInvalidation(void)
1019 /* Must be at top of stack */
1020 Assert(transInvalInfo != NULL && transInvalInfo->parent == NULL);
1022 /* Must not have any previously-queued activity */
1023 Assert(transInvalInfo->PriorCmdInvalidMsgs.cclist == NULL);
1024 Assert(transInvalInfo->PriorCmdInvalidMsgs.rclist == NULL);
1025 Assert(transInvalInfo->CurrentCmdInvalidMsgs.cclist == NULL);
1026 Assert(transInvalInfo->CurrentCmdInvalidMsgs.rclist == NULL);
1027 Assert(transInvalInfo->RelcacheInitFileInval == false);
1031 * EndNonTransactionalInvalidation
1032 * Process queued-up invalidation messages for nontransactional updates.
1034 * We expect to find messages in CurrentCmdInvalidMsgs only (else there
1035 * was a CommandCounterIncrement within the "nontransactional" update).
1036 * We must process them locally and send them out to the shared invalidation
1039 * We must also reset the lists to empty and explicitly free memory (we can't
1040 * rely on end-of-transaction cleanup for that).
1043 EndNonTransactionalInvalidation(void)
1045 InvalidationChunk *chunk;
1046 InvalidationChunk *next;
1048 /* Must be at top of stack */
1049 Assert(transInvalInfo != NULL && transInvalInfo->parent == NULL);
1051 /* Must not have any prior-command messages */
1052 Assert(transInvalInfo->PriorCmdInvalidMsgs.cclist == NULL);
1053 Assert(transInvalInfo->PriorCmdInvalidMsgs.rclist == NULL);
1056 * At present, this function is only used for CTID-changing updates;
1057 * since the relcache init file doesn't store any tuple CTIDs, we
1058 * don't have to invalidate it. That might not be true forever
1059 * though, in which case we'd need code similar to AtEOXact_Inval.
1062 /* Send out the invals */
1063 ProcessInvalidationMessages(&transInvalInfo->CurrentCmdInvalidMsgs,
1064 LocalExecuteInvalidationMessage);
1065 ProcessInvalidationMessagesMulti(&transInvalInfo->CurrentCmdInvalidMsgs,
1066 SendSharedInvalidMessages);
1068 /* Clean up and release memory */
1069 for (chunk = transInvalInfo->CurrentCmdInvalidMsgs.cclist;
1076 for (chunk = transInvalInfo->CurrentCmdInvalidMsgs.rclist;
1083 transInvalInfo->CurrentCmdInvalidMsgs.cclist = NULL;
1084 transInvalInfo->CurrentCmdInvalidMsgs.rclist = NULL;
1085 transInvalInfo->RelcacheInitFileInval = false;
1090 * CacheInvalidateHeapTuple
1091 * Register the given tuple for invalidation at end of command
1092 * (ie, current command is creating or outdating this tuple).
1095 CacheInvalidateHeapTuple(Relation relation, HeapTuple tuple)
1097 PrepareForTupleInvalidation(relation, tuple);
1101 * CacheInvalidateRelcache
1102 * Register invalidation of the specified relation's relcache entry
1103 * at end of command.
1105 * This is used in places that need to force relcache rebuild but aren't
1106 * changing any of the tuples recognized as contributors to the relcache
1107 * entry by PrepareForTupleInvalidation. (An example is dropping an index.)
1108 * We assume in particular that relfilenode/reltablespace aren't changing
1109 * (so the rd_node value is still good).
1111 * XXX most callers of this probably don't need to force an smgr flush.
1114 CacheInvalidateRelcache(Relation relation)
1119 relationId = RelationGetRelid(relation);
1120 if (relation->rd_rel->relisshared)
1121 databaseId = InvalidOid;
1123 databaseId = MyDatabaseId;
1125 RegisterRelcacheInvalidation(databaseId, relationId);
1126 RegisterSmgrInvalidation(relation->rd_node);
1130 * CacheInvalidateRelcacheByTuple
1131 * As above, but relation is identified by passing its pg_class tuple.
1134 CacheInvalidateRelcacheByTuple(HeapTuple classTuple)
1136 Form_pg_class classtup = (Form_pg_class) GETSTRUCT(classTuple);
1141 relationId = HeapTupleGetOid(classTuple);
1142 if (classtup->relisshared)
1143 databaseId = InvalidOid;
1145 databaseId = MyDatabaseId;
1146 if (classtup->reltablespace)
1147 rnode.spcNode = classtup->reltablespace;
1149 rnode.spcNode = MyDatabaseTableSpace;
1150 rnode.dbNode = databaseId;
1151 rnode.relNode = classtup->relfilenode;
1153 RegisterRelcacheInvalidation(databaseId, relationId);
1154 RegisterSmgrInvalidation(rnode);
1158 * CacheInvalidateRelcacheByRelid
1159 * As above, but relation is identified by passing its OID.
1160 * This is the least efficient of the three options; use one of
1161 * the above routines if you have a Relation or pg_class tuple.
1164 CacheInvalidateRelcacheByRelid(Oid relid)
1168 tup = SearchSysCache(RELOID,
1169 ObjectIdGetDatum(relid),
1171 if (!HeapTupleIsValid(tup))
1172 elog(ERROR, "cache lookup failed for relation %u", relid);
1173 CacheInvalidateRelcacheByTuple(tup);
1174 ReleaseSysCache(tup);
1178 * CacheRegisterSyscacheCallback
1179 * Register the specified function to be called for all future
1180 * invalidation events in the specified cache.
1182 * NOTE: currently, the OID argument to the callback routine is not
1183 * provided for syscache callbacks; the routine doesn't really get any
1184 * useful info as to exactly what changed. It should treat every call
1185 * as a "cache flush" request.
1188 CacheRegisterSyscacheCallback(int cacheid,
1189 CacheCallbackFunction func,
1192 if (cache_callback_count >= MAX_CACHE_CALLBACKS)
1193 elog(FATAL, "out of cache_callback_list slots");
1195 cache_callback_list[cache_callback_count].id = cacheid;
1196 cache_callback_list[cache_callback_count].function = func;
1197 cache_callback_list[cache_callback_count].arg = arg;
1199 ++cache_callback_count;
1203 * CacheRegisterRelcacheCallback
1204 * Register the specified function to be called for all future
1205 * relcache invalidation events. The OID of the relation being
1206 * invalidated will be passed to the function.
1208 * NOTE: InvalidOid will be passed if a cache reset request is received.
1209 * In this case the called routines should flush all cached state.
1212 CacheRegisterRelcacheCallback(CacheCallbackFunction func,
1215 if (cache_callback_count >= MAX_CACHE_CALLBACKS)
1216 elog(FATAL, "out of cache_callback_list slots");
1218 cache_callback_list[cache_callback_count].id = SHAREDINVALRELCACHE_ID;
1219 cache_callback_list[cache_callback_count].function = func;
1220 cache_callback_list[cache_callback_count].arg = arg;
1222 ++cache_callback_count;