LCOV - code coverage report
Current view: top level - src/backend/access/heap - rewriteheap.c (source / functions) Hit Total Coverage
Test: PostgreSQL 13beta1 Lines: 267 322 82.9 %
Date: 2020-06-01 00:06:26 Functions: 11 12 91.7 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : /*-------------------------------------------------------------------------
       2             :  *
       3             :  * rewriteheap.c
       4             :  *    Support functions to rewrite tables.
       5             :  *
       6             :  * These functions provide a facility to completely rewrite a heap, while
       7             :  * preserving visibility information and update chains.
       8             :  *
       9             :  * INTERFACE
      10             :  *
      11             :  * The caller is responsible for creating the new heap, all catalog
      12             :  * changes, supplying the tuples to be written to the new heap, and
      13             :  * rebuilding indexes.  The caller must hold AccessExclusiveLock on the
      14             :  * target table, because we assume no one else is writing into it.
      15             :  *
      16             :  * To use the facility:
      17             :  *
      18             :  * begin_heap_rewrite
      19             :  * while (fetch next tuple)
      20             :  * {
      21             :  *     if (tuple is dead)
      22             :  *         rewrite_heap_dead_tuple
      23             :  *     else
      24             :  *     {
      25             :  *         // do any transformations here if required
      26             :  *         rewrite_heap_tuple
      27             :  *     }
      28             :  * }
      29             :  * end_heap_rewrite
      30             :  *
      31             :  * The contents of the new relation shouldn't be relied on until after
      32             :  * end_heap_rewrite is called.
      33             :  *
      34             :  *
      35             :  * IMPLEMENTATION
      36             :  *
      37             :  * This would be a fairly trivial affair, except that we need to maintain
      38             :  * the ctid chains that link versions of an updated tuple together.
      39             :  * Since the newly stored tuples will have tids different from the original
      40             :  * ones, if we just copied t_ctid fields to the new table the links would
      41             :  * be wrong.  When we are required to copy a (presumably recently-dead or
      42             :  * delete-in-progress) tuple whose ctid doesn't point to itself, we have
      43             :  * to substitute the correct ctid instead.
      44             :  *
      45             :  * For each ctid reference from A -> B, we might encounter either A first
      46             :  * or B first.  (Note that a tuple in the middle of a chain is both A and B
      47             :  * of different pairs.)
      48             :  *
      49             :  * If we encounter A first, we'll store the tuple in the unresolved_tups
      50             :  * hash table. When we later encounter B, we remove A from the hash table,
      51             :  * fix the ctid to point to the new location of B, and insert both A and B
      52             :  * to the new heap.
      53             :  *
      54             :  * If we encounter B first, we can insert B to the new heap right away.
      55             :  * We then add an entry to the old_new_tid_map hash table showing B's
      56             :  * original tid (in the old heap) and new tid (in the new heap).
      57             :  * When we later encounter A, we get the new location of B from the table,
      58             :  * and can write A immediately with the correct ctid.
      59             :  *
      60             :  * Entries in the hash tables can be removed as soon as the later tuple
      61             :  * is encountered.  That helps to keep the memory usage down.  At the end,
      62             :  * both tables are usually empty; we should have encountered both A and B
      63             :  * of each pair.  However, it's possible for A to be RECENTLY_DEAD and B
      64             :  * entirely DEAD according to HeapTupleSatisfiesVacuum, because the test
      65             :  * for deadness using OldestXmin is not exact.  In such a case we might
      66             :  * encounter B first, and skip it, and find A later.  Then A would be added
      67             :  * to unresolved_tups, and stay there until end of the rewrite.  Since
      68             :  * this case is very unusual, we don't worry about the memory usage.
      69             :  *
      70             :  * Using in-memory hash tables means that we use some memory for each live
      71             :  * update chain in the table, from the time we find one end of the
      72             :  * reference until we find the other end.  That shouldn't be a problem in
      73             :  * practice, but if you do something like an UPDATE without a where-clause
      74             :  * on a large table, and then run CLUSTER in the same transaction, you
      75             :  * could run out of memory.  It doesn't seem worthwhile to add support for
      76             :  * spill-to-disk, as there shouldn't be that many RECENTLY_DEAD tuples in a
      77             :  * table under normal circumstances.  Furthermore, in the typical scenario
      78             :  * of CLUSTERing on an unchanging key column, we'll see all the versions
      79             :  * of a given tuple together anyway, and so the peak memory usage is only
      80             :  * proportional to the number of RECENTLY_DEAD versions of a single row, not
      81             :  * in the whole table.  Note that if we do fail halfway through a CLUSTER,
      82             :  * the old table is still valid, so failure is not catastrophic.
      83             :  *
      84             :  * We can't use the normal heap_insert function to insert into the new
      85             :  * heap, because heap_insert overwrites the visibility information.
      86             :  * We use a special-purpose raw_heap_insert function instead, which
      87             :  * is optimized for bulk inserting a lot of tuples, knowing that we have
      88             :  * exclusive access to the heap.  raw_heap_insert builds new pages in
      89             :  * local storage.  When a page is full, or at the end of the process,
      90             :  * we insert it to WAL as a single record and then write it to disk
      91             :  * directly through smgr.  Note, however, that any data sent to the new
      92             :  * heap's TOAST table will go through the normal bufmgr.
      93             :  *
      94             :  *
      95             :  * Portions Copyright (c) 1996-2020, PostgreSQL Global Development Group
      96             :  * Portions Copyright (c) 1994-5, Regents of the University of California
      97             :  *
      98             :  * IDENTIFICATION
      99             :  *    src/backend/access/heap/rewriteheap.c
     100             :  *
     101             :  *-------------------------------------------------------------------------
     102             :  */
     103             : #include "postgres.h"
     104             : 
     105             : #include <sys/stat.h>
     106             : #include <unistd.h>
     107             : 
     108             : #include "access/heapam.h"
     109             : #include "access/heapam_xlog.h"
     110             : #include "access/heaptoast.h"
     111             : #include "access/rewriteheap.h"
     112             : #include "access/transam.h"
     113             : #include "access/xact.h"
     114             : #include "access/xloginsert.h"
     115             : #include "catalog/catalog.h"
     116             : #include "lib/ilist.h"
     117             : #include "miscadmin.h"
     118             : #include "pgstat.h"
     119             : #include "replication/logical.h"
     120             : #include "replication/slot.h"
     121             : #include "storage/bufmgr.h"
     122             : #include "storage/fd.h"
     123             : #include "storage/procarray.h"
     124             : #include "storage/smgr.h"
     125             : #include "utils/memutils.h"
     126             : #include "utils/rel.h"
     127             : 
     128             : /*
     129             :  * State associated with a rewrite operation. This is opaque to the user
     130             :  * of the rewrite facility.
     131             :  */
     132             : typedef struct RewriteStateData
     133             : {
     134             :     Relation    rs_old_rel;     /* source heap */
     135             :     Relation    rs_new_rel;     /* destination heap */
     136             :     Page        rs_buffer;      /* page currently being built */
     137             :     BlockNumber rs_blockno;     /* block where page will go */
     138             :     bool        rs_buffer_valid;    /* T if any tuples in buffer */
     139             :     bool        rs_logical_rewrite; /* do we need to do logical rewriting */
     140             :     TransactionId rs_oldest_xmin;   /* oldest xmin used by caller to determine
     141             :                                      * tuple visibility */
     142             :     TransactionId rs_freeze_xid;    /* Xid that will be used as freeze cutoff
     143             :                                      * point */
     144             :     TransactionId rs_logical_xmin;  /* Xid that will be used as cutoff point
     145             :                                      * for logical rewrites */
     146             :     MultiXactId rs_cutoff_multi;    /* MultiXactId that will be used as cutoff
     147             :                                      * point for multixacts */
     148             :     MemoryContext rs_cxt;       /* for hash tables and entries and tuples in
     149             :                                  * them */
     150             :     XLogRecPtr  rs_begin_lsn;   /* XLogInsertLsn when starting the rewrite */
     151             :     HTAB       *rs_unresolved_tups; /* unmatched A tuples */
     152             :     HTAB       *rs_old_new_tid_map; /* unmatched B tuples */
     153             :     HTAB       *rs_logical_mappings;    /* logical remapping files */
     154             :     uint32      rs_num_rewrite_mappings;    /* # in memory mappings */
     155             : }           RewriteStateData;
     156             : 
     157             : /*
     158             :  * The lookup keys for the hash tables are tuple TID and xmin (we must check
     159             :  * both to avoid false matches from dead tuples).  Beware that there is
     160             :  * probably some padding space in this struct; it must be zeroed out for
     161             :  * correct hashtable operation.
     162             :  */
     163             : typedef struct
     164             : {
     165             :     TransactionId xmin;         /* tuple xmin */
     166             :     ItemPointerData tid;        /* tuple location in old heap */
     167             : } TidHashKey;
     168             : 
     169             : /*
     170             :  * Entry structures for the hash tables
     171             :  */
     172             : typedef struct
     173             : {
     174             :     TidHashKey  key;            /* expected xmin/old location of B tuple */
     175             :     ItemPointerData old_tid;    /* A's location in the old heap */
     176             :     HeapTuple   tuple;          /* A's tuple contents */
     177             : } UnresolvedTupData;
     178             : 
     179             : typedef UnresolvedTupData *UnresolvedTup;
     180             : 
     181             : typedef struct
     182             : {
     183             :     TidHashKey  key;            /* actual xmin/old location of B tuple */
     184             :     ItemPointerData new_tid;    /* where we put it in the new heap */
     185             : } OldToNewMappingData;
     186             : 
     187             : typedef OldToNewMappingData *OldToNewMapping;
     188             : 
     189             : /*
     190             :  * In-Memory data for an xid that might need logical remapping entries
     191             :  * to be logged.
     192             :  */
     193             : typedef struct RewriteMappingFile
     194             : {
     195             :     TransactionId xid;          /* xid that might need to see the row */
     196             :     int         vfd;            /* fd of mappings file */
     197             :     off_t       off;            /* how far have we written yet */
     198             :     uint32      num_mappings;   /* number of in-memory mappings */
     199             :     dlist_head  mappings;       /* list of in-memory mappings */
     200             :     char        path[MAXPGPATH];    /* path, for error messages */
     201             : } RewriteMappingFile;
     202             : 
     203             : /*
     204             :  * A single In-Memory logical rewrite mapping, hanging off
     205             :  * RewriteMappingFile->mappings.
     206             :  */
     207             : typedef struct RewriteMappingDataEntry
     208             : {
     209             :     LogicalRewriteMappingData map;  /* map between old and new location of the
     210             :                                      * tuple */
     211             :     dlist_node  node;
     212             : } RewriteMappingDataEntry;
     213             : 
     214             : 
     215             : /* prototypes for internal functions */
     216             : static void raw_heap_insert(RewriteState state, HeapTuple tup);
     217             : 
     218             : /* internal logical remapping prototypes */
     219             : static void logical_begin_heap_rewrite(RewriteState state);
     220             : static void logical_rewrite_heap_tuple(RewriteState state, ItemPointerData old_tid, HeapTuple new_tuple);
     221             : static void logical_end_heap_rewrite(RewriteState state);
     222             : 
     223             : 
     224             : /*
     225             :  * Begin a rewrite of a table
     226             :  *
     227             :  * old_heap     old, locked heap relation tuples will be read from
     228             :  * new_heap     new, locked heap relation to insert tuples to
     229             :  * oldest_xmin  xid used by the caller to determine which tuples are dead
     230             :  * freeze_xid   xid before which tuples will be frozen
     231             :  * cutoff_multi multixact before which multis will be removed
     232             :  *
     233             :  * Returns an opaque RewriteState, allocated in current memory context,
     234             :  * to be used in subsequent calls to the other functions.
     235             :  */
     236             : RewriteState
     237         326 : begin_heap_rewrite(Relation old_heap, Relation new_heap, TransactionId oldest_xmin,
     238             :                    TransactionId freeze_xid, MultiXactId cutoff_multi)
     239             : {
     240             :     RewriteState state;
     241             :     MemoryContext rw_cxt;
     242             :     MemoryContext old_cxt;
     243             :     HASHCTL     hash_ctl;
     244             : 
     245             :     /*
     246             :      * To ease cleanup, make a separate context that will contain the
     247             :      * RewriteState struct itself plus all subsidiary data.
     248             :      */
     249         326 :     rw_cxt = AllocSetContextCreate(CurrentMemoryContext,
     250             :                                    "Table rewrite",
     251             :                                    ALLOCSET_DEFAULT_SIZES);
     252         326 :     old_cxt = MemoryContextSwitchTo(rw_cxt);
     253             : 
     254             :     /* Create and fill in the state struct */
     255         326 :     state = palloc0(sizeof(RewriteStateData));
     256             : 
     257         326 :     state->rs_old_rel = old_heap;
     258         326 :     state->rs_new_rel = new_heap;
     259         326 :     state->rs_buffer = (Page) palloc(BLCKSZ);
     260             :     /* new_heap needn't be empty, just locked */
     261         326 :     state->rs_blockno = RelationGetNumberOfBlocks(new_heap);
     262         326 :     state->rs_buffer_valid = false;
     263         326 :     state->rs_oldest_xmin = oldest_xmin;
     264         326 :     state->rs_freeze_xid = freeze_xid;
     265         326 :     state->rs_cutoff_multi = cutoff_multi;
     266         326 :     state->rs_cxt = rw_cxt;
     267             : 
     268             :     /* Initialize hash tables used to track update chains */
     269         326 :     memset(&hash_ctl, 0, sizeof(hash_ctl));
     270         326 :     hash_ctl.keysize = sizeof(TidHashKey);
     271         326 :     hash_ctl.entrysize = sizeof(UnresolvedTupData);
     272         326 :     hash_ctl.hcxt = state->rs_cxt;
     273             : 
     274         326 :     state->rs_unresolved_tups =
     275         326 :         hash_create("Rewrite / Unresolved ctids",
     276             :                     128,        /* arbitrary initial size */
     277             :                     &hash_ctl,
     278             :                     HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
     279             : 
     280         326 :     hash_ctl.entrysize = sizeof(OldToNewMappingData);
     281             : 
     282         326 :     state->rs_old_new_tid_map =
     283         326 :         hash_create("Rewrite / Old to new tid map",
     284             :                     128,        /* arbitrary initial size */
     285             :                     &hash_ctl,
     286             :                     HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
     287             : 
     288         326 :     MemoryContextSwitchTo(old_cxt);
     289             : 
     290         326 :     logical_begin_heap_rewrite(state);
     291             : 
     292         326 :     return state;
     293             : }
     294             : 
     295             : /*
     296             :  * End a rewrite.
     297             :  *
     298             :  * state and any other resources are freed.
     299             :  */
     300             : void
     301         326 : end_heap_rewrite(RewriteState state)
     302             : {
     303             :     HASH_SEQ_STATUS seq_status;
     304             :     UnresolvedTup unresolved;
     305             : 
     306             :     /*
     307             :      * Write any remaining tuples in the UnresolvedTups table. If we have any
     308             :      * left, they should in fact be dead, but let's err on the safe side.
     309             :      */
     310         326 :     hash_seq_init(&seq_status, state->rs_unresolved_tups);
     311             : 
     312         326 :     while ((unresolved = hash_seq_search(&seq_status)) != NULL)
     313             :     {
     314           0 :         ItemPointerSetInvalid(&unresolved->tuple->t_data->t_ctid);
     315           0 :         raw_heap_insert(state, unresolved->tuple);
     316             :     }
     317             : 
     318             :     /* Write the last page, if any */
     319         326 :     if (state->rs_buffer_valid)
     320             :     {
     321         250 :         if (RelationNeedsWAL(state->rs_new_rel))
     322         150 :             log_newpage(&state->rs_new_rel->rd_node,
     323             :                         MAIN_FORKNUM,
     324             :                         state->rs_blockno,
     325             :                         state->rs_buffer,
     326             :                         true);
     327         250 :         RelationOpenSmgr(state->rs_new_rel);
     328             : 
     329         250 :         PageSetChecksumInplace(state->rs_buffer, state->rs_blockno);
     330             : 
     331         250 :         smgrextend(state->rs_new_rel->rd_smgr, MAIN_FORKNUM, state->rs_blockno,
     332         250 :                    (char *) state->rs_buffer, true);
     333             :     }
     334             : 
     335             :     /*
     336             :      * When we WAL-logged rel pages, we must nonetheless fsync them.  The
     337             :      * reason is the same as in storage.c's RelationCopyStorage(): we're
     338             :      * writing data that's not in shared buffers, and so a CHECKPOINT
     339             :      * occurring during the rewriteheap operation won't have fsync'd data we
     340             :      * wrote before the checkpoint.
     341             :      */
     342         326 :     if (RelationNeedsWAL(state->rs_new_rel))
     343         166 :         smgrimmedsync(state->rs_new_rel->rd_smgr, MAIN_FORKNUM);
     344             : 
     345         326 :     logical_end_heap_rewrite(state);
     346             : 
     347             :     /* Deleting the context frees everything */
     348         326 :     MemoryContextDelete(state->rs_cxt);
     349         326 : }
     350             : 
     351             : /*
     352             :  * Add a tuple to the new heap.
     353             :  *
     354             :  * Visibility information is copied from the original tuple, except that
     355             :  * we "freeze" very-old tuples.  Note that since we scribble on new_tuple,
     356             :  * it had better be temp storage not a pointer to the original tuple.
     357             :  *
     358             :  * state        opaque state as returned by begin_heap_rewrite
     359             :  * old_tuple    original tuple in the old heap
     360             :  * new_tuple    new, rewritten tuple to be inserted to new heap
     361             :  */
     362             : void
     363      483010 : rewrite_heap_tuple(RewriteState state,
     364             :                    HeapTuple old_tuple, HeapTuple new_tuple)
     365             : {
     366             :     MemoryContext old_cxt;
     367             :     ItemPointerData old_tid;
     368             :     TidHashKey  hashkey;
     369             :     bool        found;
     370             :     bool        free_new;
     371             : 
     372      483010 :     old_cxt = MemoryContextSwitchTo(state->rs_cxt);
     373             : 
     374             :     /*
     375             :      * Copy the original tuple's visibility information into new_tuple.
     376             :      *
     377             :      * XXX we might later need to copy some t_infomask2 bits, too? Right now,
     378             :      * we intentionally clear the HOT status bits.
     379             :      */
     380      483010 :     memcpy(&new_tuple->t_data->t_choice.t_heap,
     381      483010 :            &old_tuple->t_data->t_choice.t_heap,
     382             :            sizeof(HeapTupleFields));
     383             : 
     384      483010 :     new_tuple->t_data->t_infomask &= ~HEAP_XACT_MASK;
     385      483010 :     new_tuple->t_data->t_infomask2 &= ~HEAP2_XACT_MASK;
     386      966020 :     new_tuple->t_data->t_infomask |=
     387      483010 :         old_tuple->t_data->t_infomask & HEAP_XACT_MASK;
     388             : 
     389             :     /*
     390             :      * While we have our hands on the tuple, we may as well freeze any
     391             :      * eligible xmin or xmax, so that future VACUUM effort can be saved.
     392             :      */
     393     1449030 :     heap_freeze_tuple(new_tuple->t_data,
     394      483010 :                       state->rs_old_rel->rd_rel->relfrozenxid,
     395      483010 :                       state->rs_old_rel->rd_rel->relminmxid,
     396             :                       state->rs_freeze_xid,
     397             :                       state->rs_cutoff_multi);
     398             : 
     399             :     /*
     400             :      * Invalid ctid means that ctid should point to the tuple itself. We'll
     401             :      * override it later if the tuple is part of an update chain.
     402             :      */
     403      483010 :     ItemPointerSetInvalid(&new_tuple->t_data->t_ctid);
     404             : 
     405             :     /*
     406             :      * If the tuple has been updated, check the old-to-new mapping hash table.
     407             :      */
     408      505312 :     if (!((old_tuple->t_data->t_infomask & HEAP_XMAX_INVALID) ||
     409       22302 :           HeapTupleHeaderIsOnlyLocked(old_tuple->t_data)) &&
     410       22302 :         !HeapTupleHeaderIndicatesMovedPartitions(old_tuple->t_data) &&
     411       22302 :         !(ItemPointerEquals(&(old_tuple->t_self),
     412       22302 :                             &(old_tuple->t_data->t_ctid))))
     413             :     {
     414             :         OldToNewMapping mapping;
     415             : 
     416         808 :         memset(&hashkey, 0, sizeof(hashkey));
     417         808 :         hashkey.xmin = HeapTupleHeaderGetUpdateXid(old_tuple->t_data);
     418         808 :         hashkey.tid = old_tuple->t_data->t_ctid;
     419             : 
     420             :         mapping = (OldToNewMapping)
     421         808 :             hash_search(state->rs_old_new_tid_map, &hashkey,
     422             :                         HASH_FIND, NULL);
     423             : 
     424         808 :         if (mapping != NULL)
     425             :         {
     426             :             /*
     427             :              * We've already copied the tuple that t_ctid points to, so we can
     428             :              * set the ctid of this tuple to point to the new location, and
     429             :              * insert it right away.
     430             :              */
     431         366 :             new_tuple->t_data->t_ctid = mapping->new_tid;
     432             : 
     433             :             /* We don't need the mapping entry anymore */
     434         366 :             hash_search(state->rs_old_new_tid_map, &hashkey,
     435             :                         HASH_REMOVE, &found);
     436             :             Assert(found);
     437             :         }
     438             :         else
     439             :         {
     440             :             /*
     441             :              * We haven't seen the tuple t_ctid points to yet. Stash this
     442             :              * tuple into unresolved_tups to be written later.
     443             :              */
     444             :             UnresolvedTup unresolved;
     445             : 
     446         442 :             unresolved = hash_search(state->rs_unresolved_tups, &hashkey,
     447             :                                      HASH_ENTER, &found);
     448             :             Assert(!found);
     449             : 
     450         442 :             unresolved->old_tid = old_tuple->t_self;
     451         442 :             unresolved->tuple = heap_copytuple(new_tuple);
     452             : 
     453             :             /*
     454             :              * We can't do anything more now, since we don't know where the
     455             :              * tuple will be written.
     456             :              */
     457         442 :             MemoryContextSwitchTo(old_cxt);
     458         442 :             return;
     459             :         }
     460             :     }
     461             : 
     462             :     /*
     463             :      * Now we will write the tuple, and then check to see if it is the B tuple
     464             :      * in any new or known pair.  When we resolve a known pair, we will be
     465             :      * able to write that pair's A tuple, and then we have to check if it
     466             :      * resolves some other pair.  Hence, we need a loop here.
     467             :      */
     468      482568 :     old_tid = old_tuple->t_self;
     469      482568 :     free_new = false;
     470             : 
     471             :     for (;;)
     472         442 :     {
     473             :         ItemPointerData new_tid;
     474             : 
     475             :         /* Insert the tuple and find out where it's put in new_heap */
     476      483010 :         raw_heap_insert(state, new_tuple);
     477      483010 :         new_tid = new_tuple->t_self;
     478             : 
     479      483010 :         logical_rewrite_heap_tuple(state, old_tid, new_tuple);
     480             : 
     481             :         /*
     482             :          * If the tuple is the updated version of a row, and the prior version
     483             :          * wouldn't be DEAD yet, then we need to either resolve the prior
     484             :          * version (if it's waiting in rs_unresolved_tups), or make an entry
     485             :          * in rs_old_new_tid_map (so we can resolve it when we do see it). The
     486             :          * previous tuple's xmax would equal this one's xmin, so it's
     487             :          * RECENTLY_DEAD if and only if the xmin is not before OldestXmin.
     488             :          */
     489      483010 :         if ((new_tuple->t_data->t_infomask & HEAP_UPDATED) &&
     490        5872 :             !TransactionIdPrecedes(HeapTupleHeaderGetXmin(new_tuple->t_data),
     491             :                                    state->rs_oldest_xmin))
     492             :         {
     493             :             /*
     494             :              * Okay, this is B in an update pair.  See if we've seen A.
     495             :              */
     496             :             UnresolvedTup unresolved;
     497             : 
     498         808 :             memset(&hashkey, 0, sizeof(hashkey));
     499         808 :             hashkey.xmin = HeapTupleHeaderGetXmin(new_tuple->t_data);
     500         808 :             hashkey.tid = old_tid;
     501             : 
     502         808 :             unresolved = hash_search(state->rs_unresolved_tups, &hashkey,
     503             :                                      HASH_FIND, NULL);
     504             : 
     505         808 :             if (unresolved != NULL)
     506             :             {
     507             :                 /*
     508             :                  * We have seen and memorized the previous tuple already. Now
     509             :                  * that we know where we inserted the tuple its t_ctid points
     510             :                  * to, fix its t_ctid and insert it to the new heap.
     511             :                  */
     512         442 :                 if (free_new)
     513         100 :                     heap_freetuple(new_tuple);
     514         442 :                 new_tuple = unresolved->tuple;
     515         442 :                 free_new = true;
     516         442 :                 old_tid = unresolved->old_tid;
     517         442 :                 new_tuple->t_data->t_ctid = new_tid;
     518             : 
     519             :                 /*
     520             :                  * We don't need the hash entry anymore, but don't free its
     521             :                  * tuple just yet.
     522             :                  */
     523         442 :                 hash_search(state->rs_unresolved_tups, &hashkey,
     524             :                             HASH_REMOVE, &found);
     525             :                 Assert(found);
     526             : 
     527             :                 /* loop back to insert the previous tuple in the chain */
     528         442 :                 continue;
     529             :             }
     530             :             else
     531             :             {
     532             :                 /*
     533             :                  * Remember the new tid of this tuple. We'll use it to set the
     534             :                  * ctid when we find the previous tuple in the chain.
     535             :                  */
     536             :                 OldToNewMapping mapping;
     537             : 
     538         366 :                 mapping = hash_search(state->rs_old_new_tid_map, &hashkey,
     539             :                                       HASH_ENTER, &found);
     540             :                 Assert(!found);
     541             : 
     542         366 :                 mapping->new_tid = new_tid;
     543             :             }
     544             :         }
     545             : 
     546             :         /* Done with this (chain of) tuples, for now */
     547      482568 :         if (free_new)
     548         342 :             heap_freetuple(new_tuple);
     549      482568 :         break;
     550             :     }
     551             : 
     552      482568 :     MemoryContextSwitchTo(old_cxt);
     553             : }
     554             : 
     555             : /*
     556             :  * Register a dead tuple with an ongoing rewrite. Dead tuples are not
     557             :  * copied to the new table, but we still make note of them so that we
     558             :  * can release some resources earlier.
     559             :  *
     560             :  * Returns true if a tuple was removed from the unresolved_tups table.
     561             :  * This indicates that that tuple, previously thought to be "recently dead",
     562             :  * is now known really dead and won't be written to the output.
     563             :  */
     564             : bool
     565       10186 : rewrite_heap_dead_tuple(RewriteState state, HeapTuple old_tuple)
     566             : {
     567             :     /*
     568             :      * If we have already seen an earlier tuple in the update chain that
     569             :      * points to this tuple, let's forget about that earlier tuple. It's in
     570             :      * fact dead as well, our simple xmax < OldestXmin test in
     571             :      * HeapTupleSatisfiesVacuum just wasn't enough to detect it. It happens
     572             :      * when xmin of a tuple is greater than xmax, which sounds
     573             :      * counter-intuitive but is perfectly valid.
     574             :      *
     575             :      * We don't bother to try to detect the situation the other way round,
     576             :      * when we encounter the dead tuple first and then the recently dead one
     577             :      * that points to it. If that happens, we'll have some unmatched entries
     578             :      * in the UnresolvedTups hash table at the end. That can happen anyway,
     579             :      * because a vacuum might have removed the dead tuple in the chain before
     580             :      * us.
     581             :      */
     582             :     UnresolvedTup unresolved;
     583             :     TidHashKey  hashkey;
     584             :     bool        found;
     585             : 
     586       10186 :     memset(&hashkey, 0, sizeof(hashkey));
     587       10186 :     hashkey.xmin = HeapTupleHeaderGetXmin(old_tuple->t_data);
     588       10186 :     hashkey.tid = old_tuple->t_self;
     589             : 
     590       10186 :     unresolved = hash_search(state->rs_unresolved_tups, &hashkey,
     591             :                              HASH_FIND, NULL);
     592             : 
     593       10186 :     if (unresolved != NULL)
     594             :     {
     595             :         /* Need to free the contained tuple as well as the hashtable entry */
     596           0 :         heap_freetuple(unresolved->tuple);
     597           0 :         hash_search(state->rs_unresolved_tups, &hashkey,
     598             :                     HASH_REMOVE, &found);
     599             :         Assert(found);
     600           0 :         return true;
     601             :     }
     602             : 
     603       10186 :     return false;
     604             : }
     605             : 
     606             : /*
     607             :  * Insert a tuple to the new relation.  This has to track heap_insert
     608             :  * and its subsidiary functions!
     609             :  *
     610             :  * t_self of the tuple is set to the new TID of the tuple. If t_ctid of the
     611             :  * tuple is invalid on entry, it's replaced with the new TID as well (in
     612             :  * the inserted data only, not in the caller's copy).
     613             :  */
     614             : static void
     615      483010 : raw_heap_insert(RewriteState state, HeapTuple tup)
     616             : {
     617      483010 :     Page        page = state->rs_buffer;
     618             :     Size        pageFreeSpace,
     619             :                 saveFreeSpace;
     620             :     Size        len;
     621             :     OffsetNumber newoff;
     622             :     HeapTuple   heaptup;
     623             : 
     624             :     /*
     625             :      * If the new tuple is too big for storage or contains already toasted
     626             :      * out-of-line attributes from some other relation, invoke the toaster.
     627             :      *
     628             :      * Note: below this point, heaptup is the data we actually intend to store
     629             :      * into the relation; tup is the caller's original untoasted data.
     630             :      */
     631      483010 :     if (state->rs_new_rel->rd_rel->relkind == RELKIND_TOASTVALUE)
     632             :     {
     633             :         /* toast table entries should never be recursively toasted */
     634             :         Assert(!HeapTupleHasExternal(tup));
     635           0 :         heaptup = tup;
     636             :     }
     637      483010 :     else if (HeapTupleHasExternal(tup) || tup->t_len > TOAST_TUPLE_THRESHOLD)
     638         432 :     {
     639         432 :         int         options = HEAP_INSERT_SKIP_FSM;
     640             : 
     641             :         /*
     642             :          * While rewriting the heap for VACUUM FULL / CLUSTER, make sure data
     643             :          * for the TOAST table are not logically decoded.  The main heap is
     644             :          * WAL-logged as XLOG FPI records, which are not logically decoded.
     645             :          */
     646         432 :         options |= HEAP_INSERT_NO_LOGICAL;
     647             : 
     648         432 :         heaptup = heap_toast_insert_or_update(state->rs_new_rel, tup, NULL,
     649             :                                               options);
     650             :     }
     651             :     else
     652      482578 :         heaptup = tup;
     653             : 
     654      483010 :     len = MAXALIGN(heaptup->t_len); /* be conservative */
     655             : 
     656             :     /*
     657             :      * If we're gonna fail for oversize tuple, do it right away
     658             :      */
     659      483010 :     if (len > MaxHeapTupleSize)
     660           0 :         ereport(ERROR,
     661             :                 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
     662             :                  errmsg("row is too big: size %zu, maximum size %zu",
     663             :                         len, MaxHeapTupleSize)));
     664             : 
     665             :     /* Compute desired extra freespace due to fillfactor option */
     666      483010 :     saveFreeSpace = RelationGetTargetPageFreeSpace(state->rs_new_rel,
     667             :                                                    HEAP_DEFAULT_FILLFACTOR);
     668             : 
     669             :     /* Now we can check to see if there's enough free space already. */
     670      483010 :     if (state->rs_buffer_valid)
     671             :     {
     672      482760 :         pageFreeSpace = PageGetHeapFreeSpace(page);
     673             : 
     674      482760 :         if (len + saveFreeSpace > pageFreeSpace)
     675             :         {
     676             :             /* Doesn't fit, so write out the existing page */
     677             : 
     678             :             /* XLOG stuff */
     679        6946 :             if (RelationNeedsWAL(state->rs_new_rel))
     680        2380 :                 log_newpage(&state->rs_new_rel->rd_node,
     681             :                             MAIN_FORKNUM,
     682             :                             state->rs_blockno,
     683             :                             page,
     684             :                             true);
     685             : 
     686             :             /*
     687             :              * Now write the page. We say skipFsync = true because there's no
     688             :              * need for smgr to schedule an fsync for this write; we'll do it
     689             :              * ourselves in end_heap_rewrite.
     690             :              */
     691        6946 :             RelationOpenSmgr(state->rs_new_rel);
     692             : 
     693        6946 :             PageSetChecksumInplace(page, state->rs_blockno);
     694             : 
     695        6946 :             smgrextend(state->rs_new_rel->rd_smgr, MAIN_FORKNUM,
     696             :                        state->rs_blockno, (char *) page, true);
     697             : 
     698        6946 :             state->rs_blockno++;
     699        6946 :             state->rs_buffer_valid = false;
     700             :         }
     701             :     }
     702             : 
     703      483010 :     if (!state->rs_buffer_valid)
     704             :     {
     705             :         /* Initialize a new empty page */
     706        7196 :         PageInit(page, BLCKSZ, 0);
     707        7196 :         state->rs_buffer_valid = true;
     708             :     }
     709             : 
     710             :     /* And now we can insert the tuple into the page */
     711      483010 :     newoff = PageAddItem(page, (Item) heaptup->t_data, heaptup->t_len,
     712             :                          InvalidOffsetNumber, false, true);
     713      483010 :     if (newoff == InvalidOffsetNumber)
     714           0 :         elog(ERROR, "failed to add tuple");
     715             : 
     716             :     /* Update caller's t_self to the actual position where it was stored */
     717      483010 :     ItemPointerSet(&(tup->t_self), state->rs_blockno, newoff);
     718             : 
     719             :     /*
     720             :      * Insert the correct position into CTID of the stored tuple, too, if the
     721             :      * caller didn't supply a valid CTID.
     722             :      */
     723      483010 :     if (!ItemPointerIsValid(&tup->t_data->t_ctid))
     724             :     {
     725             :         ItemId      newitemid;
     726             :         HeapTupleHeader onpage_tup;
     727             : 
     728      482202 :         newitemid = PageGetItemId(page, newoff);
     729      482202 :         onpage_tup = (HeapTupleHeader) PageGetItem(page, newitemid);
     730             : 
     731      482202 :         onpage_tup->t_ctid = tup->t_self;
     732             :     }
     733             : 
     734             :     /* If heaptup is a private copy, release it. */
     735      483010 :     if (heaptup != tup)
     736         432 :         heap_freetuple(heaptup);
     737      483010 : }
     738             : 
     739             : /* ------------------------------------------------------------------------
     740             :  * Logical rewrite support
     741             :  *
     742             :  * When doing logical decoding - which relies on using cmin/cmax of catalog
     743             :  * tuples, via xl_heap_new_cid records - heap rewrites have to log enough
     744             :  * information to allow the decoding backend to updates its internal mapping
     745             :  * of (relfilenode,ctid) => (cmin, cmax) to be correct for the rewritten heap.
     746             :  *
     747             :  * For that, every time we find a tuple that's been modified in a catalog
     748             :  * relation within the xmin horizon of any decoding slot, we log a mapping
     749             :  * from the old to the new location.
     750             :  *
     751             :  * To deal with rewrites that abort the filename of a mapping file contains
     752             :  * the xid of the transaction performing the rewrite, which then can be
     753             :  * checked before being read in.
     754             :  *
     755             :  * For efficiency we don't immediately spill every single map mapping for a
     756             :  * row to disk but only do so in batches when we've collected several of them
     757             :  * in memory or when end_heap_rewrite() has been called.
     758             :  *
     759             :  * Crash-Safety: This module diverts from the usual patterns of doing WAL
     760             :  * since it cannot rely on checkpoint flushing out all buffers and thus
     761             :  * waiting for exclusive locks on buffers. Usually the XLogInsert() covering
     762             :  * buffer modifications is performed while the buffer(s) that are being
     763             :  * modified are exclusively locked guaranteeing that both the WAL record and
     764             :  * the modified heap are on either side of the checkpoint. But since the
     765             :  * mapping files we log aren't in shared_buffers that interlock doesn't work.
     766             :  *
     767             :  * Instead we simply write the mapping files out to disk, *before* the
     768             :  * XLogInsert() is performed. That guarantees that either the XLogInsert() is
     769             :  * inserted after the checkpoint's redo pointer or that the checkpoint (via
     770             :  * CheckPointLogicalRewriteHeap()) has flushed the (partial) mapping file to
     771             :  * disk. That leaves the tail end that has not yet been flushed open to
     772             :  * corruption, which is solved by including the current offset in the
     773             :  * xl_heap_rewrite_mapping records and truncating the mapping file to it
     774             :  * during replay. Every time a rewrite is finished all generated mapping files
     775             :  * are synced to disk.
     776             :  *
     777             :  * Note that if we were only concerned about crash safety we wouldn't have to
     778             :  * deal with WAL logging at all - an fsync() at the end of a rewrite would be
     779             :  * sufficient for crash safety. Any mapping that hasn't been safely flushed to
     780             :  * disk has to be by an aborted (explicitly or via a crash) transaction and is
     781             :  * ignored by virtue of the xid in its name being subject to a
     782             :  * TransactionDidCommit() check. But we want to support having standbys via
     783             :  * physical replication, both for availability and to do logical decoding
     784             :  * there.
     785             :  * ------------------------------------------------------------------------
     786             :  */
     787             : 
     788             : /*
     789             :  * Do preparations for logging logical mappings during a rewrite if
     790             :  * necessary. If we detect that we don't need to log anything we'll prevent
     791             :  * any further action by the various logical rewrite functions.
     792             :  */
     793             : static void
     794         326 : logical_begin_heap_rewrite(RewriteState state)
     795             : {
     796             :     HASHCTL     hash_ctl;
     797             :     TransactionId logical_xmin;
     798             : 
     799             :     /*
     800             :      * We only need to persist these mappings if the rewritten table can be
     801             :      * accessed during logical decoding, if not, we can skip doing any
     802             :      * additional work.
     803             :      */
     804         326 :     state->rs_logical_rewrite =
     805         326 :         RelationIsAccessibleInLogicalDecoding(state->rs_old_rel);
     806             : 
     807         326 :     if (!state->rs_logical_rewrite)
     808         286 :         return;
     809             : 
     810          40 :     ProcArrayGetReplicationSlotXmin(NULL, &logical_xmin);
     811             : 
     812             :     /*
     813             :      * If there are no logical slots in progress we don't need to do anything,
     814             :      * there cannot be any remappings for relevant rows yet. The relation's
     815             :      * lock protects us against races.
     816             :      */
     817          40 :     if (logical_xmin == InvalidTransactionId)
     818             :     {
     819           0 :         state->rs_logical_rewrite = false;
     820           0 :         return;
     821             :     }
     822             : 
     823          40 :     state->rs_logical_xmin = logical_xmin;
     824          40 :     state->rs_begin_lsn = GetXLogInsertRecPtr();
     825          40 :     state->rs_num_rewrite_mappings = 0;
     826             : 
     827          40 :     memset(&hash_ctl, 0, sizeof(hash_ctl));
     828          40 :     hash_ctl.keysize = sizeof(TransactionId);
     829          40 :     hash_ctl.entrysize = sizeof(RewriteMappingFile);
     830          40 :     hash_ctl.hcxt = state->rs_cxt;
     831             : 
     832          40 :     state->rs_logical_mappings =
     833          40 :         hash_create("Logical rewrite mapping",
     834             :                     128,        /* arbitrary initial size */
     835             :                     &hash_ctl,
     836             :                     HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
     837             : }
     838             : 
     839             : /*
     840             :  * Flush all logical in-memory mappings to disk, but don't fsync them yet.
     841             :  */
     842             : static void
     843          18 : logical_heap_rewrite_flush_mappings(RewriteState state)
     844             : {
     845             :     HASH_SEQ_STATUS seq_status;
     846             :     RewriteMappingFile *src;
     847             :     dlist_mutable_iter iter;
     848             : 
     849             :     Assert(state->rs_logical_rewrite);
     850             : 
     851             :     /* no logical rewrite in progress, no need to iterate over mappings */
     852          18 :     if (state->rs_num_rewrite_mappings == 0)
     853           0 :         return;
     854             : 
     855          18 :     elog(DEBUG1, "flushing %u logical rewrite mapping entries",
     856             :          state->rs_num_rewrite_mappings);
     857             : 
     858          18 :     hash_seq_init(&seq_status, state->rs_logical_mappings);
     859         196 :     while ((src = (RewriteMappingFile *) hash_seq_search(&seq_status)) != NULL)
     860             :     {
     861             :         char       *waldata;
     862             :         char       *waldata_start;
     863             :         xl_heap_rewrite_mapping xlrec;
     864             :         Oid         dboid;
     865             :         uint32      len;
     866             :         int         written;
     867             : 
     868             :         /* this file hasn't got any new mappings */
     869         178 :         if (src->num_mappings == 0)
     870           0 :             continue;
     871             : 
     872         178 :         if (state->rs_old_rel->rd_rel->relisshared)
     873           0 :             dboid = InvalidOid;
     874             :         else
     875         178 :             dboid = MyDatabaseId;
     876             : 
     877         178 :         xlrec.num_mappings = src->num_mappings;
     878         178 :         xlrec.mapped_rel = RelationGetRelid(state->rs_old_rel);
     879         178 :         xlrec.mapped_xid = src->xid;
     880         178 :         xlrec.mapped_db = dboid;
     881         178 :         xlrec.offset = src->off;
     882         178 :         xlrec.start_lsn = state->rs_begin_lsn;
     883             : 
     884             :         /* write all mappings consecutively */
     885         178 :         len = src->num_mappings * sizeof(LogicalRewriteMappingData);
     886         178 :         waldata_start = waldata = palloc(len);
     887             : 
     888             :         /*
     889             :          * collect data we need to write out, but don't modify ondisk data yet
     890             :          */
     891        1502 :         dlist_foreach_modify(iter, &src->mappings)
     892             :         {
     893             :             RewriteMappingDataEntry *pmap;
     894             : 
     895        1324 :             pmap = dlist_container(RewriteMappingDataEntry, node, iter.cur);
     896             : 
     897        1324 :             memcpy(waldata, &pmap->map, sizeof(pmap->map));
     898        1324 :             waldata += sizeof(pmap->map);
     899             : 
     900             :             /* remove from the list and free */
     901        1324 :             dlist_delete(&pmap->node);
     902        1324 :             pfree(pmap);
     903             : 
     904             :             /* update bookkeeping */
     905        1324 :             state->rs_num_rewrite_mappings--;
     906        1324 :             src->num_mappings--;
     907             :         }
     908             : 
     909             :         Assert(src->num_mappings == 0);
     910             :         Assert(waldata == waldata_start + len);
     911             : 
     912             :         /*
     913             :          * Note that we deviate from the usual WAL coding practices here,
     914             :          * check the above "Logical rewrite support" comment for reasoning.
     915             :          */
     916         178 :         written = FileWrite(src->vfd, waldata_start, len, src->off,
     917             :                             WAIT_EVENT_LOGICAL_REWRITE_WRITE);
     918         178 :         if (written != len)
     919           0 :             ereport(ERROR,
     920             :                     (errcode_for_file_access(),
     921             :                      errmsg("could not write to file \"%s\", wrote %d of %d: %m", src->path,
     922             :                             written, len)));
     923         178 :         src->off += len;
     924             : 
     925         178 :         XLogBeginInsert();
     926         178 :         XLogRegisterData((char *) (&xlrec), sizeof(xlrec));
     927         178 :         XLogRegisterData(waldata_start, len);
     928             : 
     929             :         /* write xlog record */
     930         178 :         XLogInsert(RM_HEAP2_ID, XLOG_HEAP2_REWRITE);
     931             : 
     932         178 :         pfree(waldata_start);
     933             :     }
     934             :     Assert(state->rs_num_rewrite_mappings == 0);
     935             : }
     936             : 
     937             : /*
     938             :  * Logical remapping part of end_heap_rewrite().
     939             :  */
     940             : static void
     941         326 : logical_end_heap_rewrite(RewriteState state)
     942             : {
     943             :     HASH_SEQ_STATUS seq_status;
     944             :     RewriteMappingFile *src;
     945             : 
     946             :     /* done, no logical rewrite in progress */
     947         326 :     if (!state->rs_logical_rewrite)
     948         286 :         return;
     949             : 
     950             :     /* writeout remaining in-memory entries */
     951          40 :     if (state->rs_num_rewrite_mappings > 0)
     952          18 :         logical_heap_rewrite_flush_mappings(state);
     953             : 
     954             :     /* Iterate over all mappings we have written and fsync the files. */
     955          40 :     hash_seq_init(&seq_status, state->rs_logical_mappings);
     956         218 :     while ((src = (RewriteMappingFile *) hash_seq_search(&seq_status)) != NULL)
     957             :     {
     958         178 :         if (FileSync(src->vfd, WAIT_EVENT_LOGICAL_REWRITE_SYNC) != 0)
     959           0 :             ereport(data_sync_elevel(ERROR),
     960             :                     (errcode_for_file_access(),
     961             :                      errmsg("could not fsync file \"%s\": %m", src->path)));
     962         178 :         FileClose(src->vfd);
     963             :     }
     964             :     /* memory context cleanup will deal with the rest */
     965             : }
     966             : 
     967             : /*
     968             :  * Log a single (old->new) mapping for 'xid'.
     969             :  */
     970             : static void
     971        1324 : logical_rewrite_log_mapping(RewriteState state, TransactionId xid,
     972             :                             LogicalRewriteMappingData *map)
     973             : {
     974             :     RewriteMappingFile *src;
     975             :     RewriteMappingDataEntry *pmap;
     976             :     Oid         relid;
     977             :     bool        found;
     978             : 
     979        1324 :     relid = RelationGetRelid(state->rs_old_rel);
     980             : 
     981             :     /* look for existing mappings for this 'mapped' xid */
     982        1324 :     src = hash_search(state->rs_logical_mappings, &xid,
     983             :                       HASH_ENTER, &found);
     984             : 
     985             :     /*
     986             :      * We haven't yet had the need to map anything for this xid, create
     987             :      * per-xid data structures.
     988             :      */
     989        1324 :     if (!found)
     990             :     {
     991             :         char        path[MAXPGPATH];
     992             :         Oid         dboid;
     993             : 
     994         178 :         if (state->rs_old_rel->rd_rel->relisshared)
     995           0 :             dboid = InvalidOid;
     996             :         else
     997         178 :             dboid = MyDatabaseId;
     998             : 
     999         178 :         snprintf(path, MAXPGPATH,
    1000             :                  "pg_logical/mappings/" LOGICAL_REWRITE_FORMAT,
    1001             :                  dboid, relid,
    1002         178 :                  (uint32) (state->rs_begin_lsn >> 32),
    1003         178 :                  (uint32) state->rs_begin_lsn,
    1004             :                  xid, GetCurrentTransactionId());
    1005             : 
    1006         178 :         dlist_init(&src->mappings);
    1007         178 :         src->num_mappings = 0;
    1008         178 :         src->off = 0;
    1009         178 :         memcpy(src->path, path, sizeof(path));
    1010         178 :         src->vfd = PathNameOpenFile(path,
    1011             :                                     O_CREAT | O_EXCL | O_WRONLY | PG_BINARY);
    1012         178 :         if (src->vfd < 0)
    1013           0 :             ereport(ERROR,
    1014             :                     (errcode_for_file_access(),
    1015             :                      errmsg("could not create file \"%s\": %m", path)));
    1016             :     }
    1017             : 
    1018        1324 :     pmap = MemoryContextAlloc(state->rs_cxt,
    1019             :                               sizeof(RewriteMappingDataEntry));
    1020        1324 :     memcpy(&pmap->map, map, sizeof(LogicalRewriteMappingData));
    1021        1324 :     dlist_push_tail(&src->mappings, &pmap->node);
    1022        1324 :     src->num_mappings++;
    1023        1324 :     state->rs_num_rewrite_mappings++;
    1024             : 
    1025             :     /*
    1026             :      * Write out buffer every time we've too many in-memory entries across all
    1027             :      * mapping files.
    1028             :      */
    1029        1324 :     if (state->rs_num_rewrite_mappings >= 1000 /* arbitrary number */ )
    1030           0 :         logical_heap_rewrite_flush_mappings(state);
    1031        1324 : }
    1032             : 
    1033             : /*
    1034             :  * Perform logical remapping for a tuple that's mapped from old_tid to
    1035             :  * new_tuple->t_self by rewrite_heap_tuple() if necessary for the tuple.
    1036             :  */
    1037             : static void
    1038      483010 : logical_rewrite_heap_tuple(RewriteState state, ItemPointerData old_tid,
    1039             :                            HeapTuple new_tuple)
    1040             : {
    1041      483010 :     ItemPointerData new_tid = new_tuple->t_self;
    1042      483010 :     TransactionId cutoff = state->rs_logical_xmin;
    1043             :     TransactionId xmin;
    1044             :     TransactionId xmax;
    1045      483010 :     bool        do_log_xmin = false;
    1046      483010 :     bool        do_log_xmax = false;
    1047             :     LogicalRewriteMappingData map;
    1048             : 
    1049             :     /* no logical rewrite in progress, we don't need to log anything */
    1050      483010 :     if (!state->rs_logical_rewrite)
    1051      481716 :         return;
    1052             : 
    1053       44470 :     xmin = HeapTupleHeaderGetXmin(new_tuple->t_data);
    1054             :     /* use *GetUpdateXid to correctly deal with multixacts */
    1055       44470 :     xmax = HeapTupleHeaderGetUpdateXid(new_tuple->t_data);
    1056             : 
    1057             :     /*
    1058             :      * Log the mapping iff the tuple has been created recently.
    1059             :      */
    1060       44470 :     if (TransactionIdIsNormal(xmin) && !TransactionIdPrecedes(xmin, cutoff))
    1061         976 :         do_log_xmin = true;
    1062             : 
    1063       44470 :     if (!TransactionIdIsNormal(xmax))
    1064             :     {
    1065             :         /*
    1066             :          * no xmax is set, can't have any permanent ones, so this check is
    1067             :          * sufficient
    1068             :          */
    1069             :     }
    1070         906 :     else if (HEAP_XMAX_IS_LOCKED_ONLY(new_tuple->t_data->t_infomask))
    1071             :     {
    1072             :         /* only locked, we don't care */
    1073             :     }
    1074         906 :     else if (!TransactionIdPrecedes(xmax, cutoff))
    1075             :     {
    1076             :         /* tuple has been deleted recently, log */
    1077         906 :         do_log_xmax = true;
    1078             :     }
    1079             : 
    1080             :     /* if neither needs to be logged, we're done */
    1081       44470 :     if (!do_log_xmin && !do_log_xmax)
    1082       43176 :         return;
    1083             : 
    1084             :     /* fill out mapping information */
    1085        1294 :     map.old_node = state->rs_old_rel->rd_node;
    1086        1294 :     map.old_tid = old_tid;
    1087        1294 :     map.new_node = state->rs_new_rel->rd_node;
    1088        1294 :     map.new_tid = new_tid;
    1089             : 
    1090             :     /* ---
    1091             :      * Now persist the mapping for the individual xids that are affected. We
    1092             :      * need to log for both xmin and xmax if they aren't the same transaction
    1093             :      * since the mapping files are per "affected" xid.
    1094             :      * We don't muster all that much effort detecting whether xmin and xmax
    1095             :      * are actually the same transaction, we just check whether the xid is the
    1096             :      * same disregarding subtransactions. Logging too much is relatively
    1097             :      * harmless and we could never do the check fully since subtransaction
    1098             :      * data is thrown away during restarts.
    1099             :      * ---
    1100             :      */
    1101        1294 :     if (do_log_xmin)
    1102         976 :         logical_rewrite_log_mapping(state, xmin, &map);
    1103             :     /* separately log mapping for xmax unless it'd be redundant */
    1104        1294 :     if (do_log_xmax && !TransactionIdEquals(xmin, xmax))
    1105         348 :         logical_rewrite_log_mapping(state, xmax, &map);
    1106             : }
    1107             : 
    1108             : /*
    1109             :  * Replay XLOG_HEAP2_REWRITE records
    1110             :  */
    1111             : void
    1112           0 : heap_xlog_logical_rewrite(XLogReaderState *r)
    1113             : {
    1114             :     char        path[MAXPGPATH];
    1115             :     int         fd;
    1116             :     xl_heap_rewrite_mapping *xlrec;
    1117             :     uint32      len;
    1118             :     char       *data;
    1119             : 
    1120           0 :     xlrec = (xl_heap_rewrite_mapping *) XLogRecGetData(r);
    1121             : 
    1122           0 :     snprintf(path, MAXPGPATH,
    1123             :              "pg_logical/mappings/" LOGICAL_REWRITE_FORMAT,
    1124             :              xlrec->mapped_db, xlrec->mapped_rel,
    1125           0 :              (uint32) (xlrec->start_lsn >> 32),
    1126           0 :              (uint32) xlrec->start_lsn,
    1127           0 :              xlrec->mapped_xid, XLogRecGetXid(r));
    1128             : 
    1129           0 :     fd = OpenTransientFile(path,
    1130             :                            O_CREAT | O_WRONLY | PG_BINARY);
    1131           0 :     if (fd < 0)
    1132           0 :         ereport(ERROR,
    1133             :                 (errcode_for_file_access(),
    1134             :                  errmsg("could not create file \"%s\": %m", path)));
    1135             : 
    1136             :     /*
    1137             :      * Truncate all data that's not guaranteed to have been safely fsynced (by
    1138             :      * previous record or by the last checkpoint).
    1139             :      */
    1140           0 :     pgstat_report_wait_start(WAIT_EVENT_LOGICAL_REWRITE_TRUNCATE);
    1141           0 :     if (ftruncate(fd, xlrec->offset) != 0)
    1142           0 :         ereport(ERROR,
    1143             :                 (errcode_for_file_access(),
    1144             :                  errmsg("could not truncate file \"%s\" to %u: %m",
    1145             :                         path, (uint32) xlrec->offset)));
    1146           0 :     pgstat_report_wait_end();
    1147             : 
    1148           0 :     data = XLogRecGetData(r) + sizeof(*xlrec);
    1149             : 
    1150           0 :     len = xlrec->num_mappings * sizeof(LogicalRewriteMappingData);
    1151             : 
    1152             :     /* write out tail end of mapping file (again) */
    1153           0 :     errno = 0;
    1154           0 :     pgstat_report_wait_start(WAIT_EVENT_LOGICAL_REWRITE_MAPPING_WRITE);
    1155           0 :     if (pg_pwrite(fd, data, len, xlrec->offset) != len)
    1156             :     {
    1157             :         /* if write didn't set errno, assume problem is no disk space */
    1158           0 :         if (errno == 0)
    1159           0 :             errno = ENOSPC;
    1160           0 :         ereport(ERROR,
    1161             :                 (errcode_for_file_access(),
    1162             :                  errmsg("could not write to file \"%s\": %m", path)));
    1163             :     }
    1164           0 :     pgstat_report_wait_end();
    1165             : 
    1166             :     /*
    1167             :      * Now fsync all previously written data. We could improve things and only
    1168             :      * do this for the last write to a file, but the required bookkeeping
    1169             :      * doesn't seem worth the trouble.
    1170             :      */
    1171           0 :     pgstat_report_wait_start(WAIT_EVENT_LOGICAL_REWRITE_MAPPING_SYNC);
    1172           0 :     if (pg_fsync(fd) != 0)
    1173           0 :         ereport(data_sync_elevel(ERROR),
    1174             :                 (errcode_for_file_access(),
    1175             :                  errmsg("could not fsync file \"%s\": %m", path)));
    1176           0 :     pgstat_report_wait_end();
    1177             : 
    1178           0 :     if (CloseTransientFile(fd) != 0)
    1179           0 :         ereport(ERROR,
    1180             :                 (errcode_for_file_access(),
    1181             :                  errmsg("could not close file \"%s\": %m", path)));
    1182           0 : }
    1183             : 
    1184             : /* ---
    1185             :  * Perform a checkpoint for logical rewrite mappings
    1186             :  *
    1187             :  * This serves two tasks:
    1188             :  * 1) Remove all mappings not needed anymore based on the logical restart LSN
    1189             :  * 2) Flush all remaining mappings to disk, so that replay after a checkpoint
    1190             :  *    only has to deal with the parts of a mapping that have been written out
    1191             :  *    after the checkpoint started.
    1192             :  * ---
    1193             :  */
    1194             : void
    1195        3172 : CheckPointLogicalRewriteHeap(void)
    1196             : {
    1197             :     XLogRecPtr  cutoff;
    1198             :     XLogRecPtr  redo;
    1199             :     DIR        *mappings_dir;
    1200             :     struct dirent *mapping_de;
    1201             :     char        path[MAXPGPATH + 20];
    1202             : 
    1203             :     /*
    1204             :      * We start of with a minimum of the last redo pointer. No new decoding
    1205             :      * slot will start before that, so that's a safe upper bound for removal.
    1206             :      */
    1207        3172 :     redo = GetRedoRecPtr();
    1208             : 
    1209             :     /* now check for the restart ptrs from existing slots */
    1210        3172 :     cutoff = ReplicationSlotsComputeLogicalRestartLSN();
    1211             : 
    1212             :     /* don't start earlier than the restart lsn */
    1213        3172 :     if (cutoff != InvalidXLogRecPtr && redo < cutoff)
    1214           0 :         cutoff = redo;
    1215             : 
    1216        3172 :     mappings_dir = AllocateDir("pg_logical/mappings");
    1217        9872 :     while ((mapping_de = ReadDir(mappings_dir, "pg_logical/mappings")) != NULL)
    1218             :     {
    1219             :         struct stat statbuf;
    1220             :         Oid         dboid;
    1221             :         Oid         relid;
    1222             :         XLogRecPtr  lsn;
    1223             :         TransactionId rewrite_xid;
    1224             :         TransactionId create_xid;
    1225             :         uint32      hi,
    1226             :                     lo;
    1227             : 
    1228        6700 :         if (strcmp(mapping_de->d_name, ".") == 0 ||
    1229        3528 :             strcmp(mapping_de->d_name, "..") == 0)
    1230        6344 :             continue;
    1231             : 
    1232         356 :         snprintf(path, sizeof(path), "pg_logical/mappings/%s", mapping_de->d_name);
    1233         356 :         if (lstat(path, &statbuf) == 0 && !S_ISREG(statbuf.st_mode))
    1234           0 :             continue;
    1235             : 
    1236             :         /* Skip over files that cannot be ours. */
    1237         356 :         if (strncmp(mapping_de->d_name, "map-", 4) != 0)
    1238           0 :             continue;
    1239             : 
    1240         356 :         if (sscanf(mapping_de->d_name, LOGICAL_REWRITE_FORMAT,
    1241             :                    &dboid, &relid, &hi, &lo, &rewrite_xid, &create_xid) != 6)
    1242           0 :             elog(ERROR, "could not parse filename \"%s\"", mapping_de->d_name);
    1243             : 
    1244         356 :         lsn = ((uint64) hi) << 32 | lo;
    1245             : 
    1246         356 :         if (lsn < cutoff || cutoff == InvalidXLogRecPtr)
    1247             :         {
    1248         178 :             elog(DEBUG1, "removing logical rewrite file \"%s\"", path);
    1249         178 :             if (unlink(path) < 0)
    1250           0 :                 ereport(ERROR,
    1251             :                         (errcode_for_file_access(),
    1252             :                          errmsg("could not remove file \"%s\": %m", path)));
    1253             :         }
    1254             :         else
    1255             :         {
    1256             :             /* on some operating systems fsyncing a file requires O_RDWR */
    1257         178 :             int         fd = OpenTransientFile(path, O_RDWR | PG_BINARY);
    1258             : 
    1259             :             /*
    1260             :              * The file cannot vanish due to concurrency since this function
    1261             :              * is the only one removing logical mappings and it's run while
    1262             :              * CheckpointLock is held exclusively.
    1263             :              */
    1264         178 :             if (fd < 0)
    1265           0 :                 ereport(ERROR,
    1266             :                         (errcode_for_file_access(),
    1267             :                          errmsg("could not open file \"%s\": %m", path)));
    1268             : 
    1269             :             /*
    1270             :              * We could try to avoid fsyncing files that either haven't
    1271             :              * changed or have only been created since the checkpoint's start,
    1272             :              * but it's currently not deemed worth the effort.
    1273             :              */
    1274         178 :             pgstat_report_wait_start(WAIT_EVENT_LOGICAL_REWRITE_CHECKPOINT_SYNC);
    1275         178 :             if (pg_fsync(fd) != 0)
    1276           0 :                 ereport(data_sync_elevel(ERROR),
    1277             :                         (errcode_for_file_access(),
    1278             :                          errmsg("could not fsync file \"%s\": %m", path)));
    1279         178 :             pgstat_report_wait_end();
    1280             : 
    1281         178 :             if (CloseTransientFile(fd) != 0)
    1282           0 :                 ereport(ERROR,
    1283             :                         (errcode_for_file_access(),
    1284             :                          errmsg("could not close file \"%s\": %m", path)));
    1285             :         }
    1286             :     }
    1287        3172 :     FreeDir(mappings_dir);
    1288        3172 : }

Generated by: LCOV version 1.13