LCOV - differential code coverage report
Current view: top level - src/backend/catalog - storage.c (source / functions) Coverage Total Hit UBC GNC CBC DCB
Current: 4b3c9325757dfd8f2312e9f1a8decf4431f344ae vs e87b024bfb8dd55e3049b1b6e6ab4e810cf1abc8 Lines: 94.8 % 345 327 18 7 320 1
Current Date: 2026-11-28 16:48:44 +0900 Functions: 100.0 % 19 19 1 18
Baseline: lcov-20261128-baseline Branches: 77.2 % 224 173 51 6 167
Baseline Date: 2026-11-28 16:48:48 +0900 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
(7,30] days: 100.0 % 9 9 7 2
(30,360] days: 80.0 % 5 4 1 4
(360..) days: 94.9 % 331 314 17 314
Function coverage date bins:
(360..) days: 100.0 % 19 19 1 18
Branch coverage date bins:
(7,30] days: 87.5 % 8 7 1 6 1
(360..) days: 76.9 % 216 166 50 166

 Age         Owner                    Branch data    TLA  Line data    Source code
                                  1                 :                : /*-------------------------------------------------------------------------
                                  2                 :                :  *
                                  3                 :                :  * storage.c
                                  4                 :                :  *    code to create and destroy physical storage for relations
                                  5                 :                :  *
                                  6                 :                :  * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
                                  7                 :                :  * Portions Copyright (c) 1994, Regents of the University of California
                                  8                 :                :  *
                                  9                 :                :  *
                                 10                 :                :  * IDENTIFICATION
                                 11                 :                :  *    src/backend/catalog/storage.c
                                 12                 :                :  *
                                 13                 :                :  * NOTES
                                 14                 :                :  *    Some of this code used to be in storage/smgr/smgr.c, and the
                                 15                 :                :  *    function names still reflect that.
                                 16                 :                :  *
                                 17                 :                :  *-------------------------------------------------------------------------
                                 18                 :                :  */
                                 19                 :                : 
                                 20                 :                : #include "postgres.h"
                                 21                 :                : 
                                 22                 :                : #include "access/visibilitymap.h"
                                 23                 :                : #include "access/xact.h"
                                 24                 :                : #include "access/xlog.h"
                                 25                 :                : #include "access/xloginsert.h"
                                 26                 :                : #include "access/xlogutils.h"
                                 27                 :                : #include "catalog/storage.h"
                                 28                 :                : #include "catalog/storage_xlog.h"
                                 29                 :                : #include "miscadmin.h"
                                 30                 :                : #include "pgstat.h"
                                 31                 :                : #include "storage/bulk_write.h"
                                 32                 :                : #include "storage/freespace.h"
                                 33                 :                : #include "storage/proc.h"
                                 34                 :                : #include "storage/smgr.h"
                                 35                 :                : #include "utils/hsearch.h"
                                 36                 :                : #include "utils/memutils.h"
                                 37                 :                : #include "utils/rel.h"
                                 38                 :                : 
                                 39                 :                : /* GUC variables */
                                 40                 :                : int         wal_skip_threshold = 2048;  /* in kilobytes */
                                 41                 :                : 
                                 42                 :                : /*
                                 43                 :                :  * We keep a list of all relations (represented as RelFileLocator values)
                                 44                 :                :  * that have been created or deleted in the current transaction.  When
                                 45                 :                :  * a relation is created, we create the physical file immediately, but
                                 46                 :                :  * remember it so that we can delete the file again if the current
                                 47                 :                :  * transaction is aborted.  Conversely, a deletion request is NOT
                                 48                 :                :  * executed immediately, but is just entered in the list.  When and if
                                 49                 :                :  * the transaction commits, we can delete the physical file.
                                 50                 :                :  *
                                 51                 :                :  * To handle subtransactions, every entry is marked with its transaction
                                 52                 :                :  * nesting level.  At subtransaction commit, we reassign the subtransaction's
                                 53                 :                :  * entries to the parent nesting level.  At subtransaction abort, we can
                                 54                 :                :  * immediately execute the abort-time actions for all entries of the current
                                 55                 :                :  * nesting level.
                                 56                 :                :  *
                                 57                 :                :  * NOTE: the list is kept in TopMemoryContext to be sure it won't disappear
                                 58                 :                :  * unbetimes.  It'd probably be OK to keep it in TopTransactionContext,
                                 59                 :                :  * but I'm being paranoid.
                                 60                 :                :  */
                                 61                 :                : 
                                 62                 :                : typedef struct PendingRelDelete
                                 63                 :                : {
                                 64                 :                :     RelFileLocator rlocator;    /* relation that may need to be deleted */
                                 65                 :                :     ProcNumber  procNumber;     /* INVALID_PROC_NUMBER if not a temp rel */
                                 66                 :                :     bool        atCommit;       /* T=delete at commit; F=delete at abort */
                                 67                 :                :     int         nestLevel;      /* xact nesting level of request */
                                 68                 :                :     struct PendingRelDelete *next;  /* linked-list link */
                                 69                 :                : } PendingRelDelete;
                                 70                 :                : 
                                 71                 :                : typedef struct PendingRelSync
                                 72                 :                : {
                                 73                 :                :     RelFileLocator rlocator;
                                 74                 :                :     bool        is_truncated;   /* Has the file experienced truncation? */
                                 75                 :                : } PendingRelSync;
                                 76                 :                : 
                                 77                 :                : static PendingRelDelete *pendingDeletes = NULL; /* head of linked list */
                                 78                 :                : static HTAB *pendingSyncHash = NULL;
                                 79                 :                : 
                                 80                 :                : 
                                 81                 :                : /*
                                 82                 :                :  * AddPendingSync
                                 83                 :                :  *      Queue an at-commit fsync.
                                 84                 :                :  */
                                 85                 :                : static void
 1606 rhaas@postgresql.org       86                 :CBC       34707 : AddPendingSync(const RelFileLocator *rlocator)
                                 87                 :                : {
                                 88                 :                :     PendingRelSync *pending;
                                 89                 :                :     bool        found;
                                 90                 :                : 
                                 91                 :                :     /* create the hash if not yet */
 2429 noah@leadboat.com          92         [ +  + ]:          34707 :     if (!pendingSyncHash)
                                 93                 :                :     {
                                 94                 :                :         HASHCTL     ctl;
                                 95                 :                : 
 1606 rhaas@postgresql.org       96                 :           2048 :         ctl.keysize = sizeof(RelFileLocator);
 2429 noah@leadboat.com          97                 :           2048 :         ctl.entrysize = sizeof(PendingRelSync);
                                 98                 :           2048 :         ctl.hcxt = TopTransactionContext;
                                 99                 :           2048 :         pendingSyncHash = hash_create("pending sync hash", 16, &ctl,
                                100                 :                :                                       HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
                                101                 :                :     }
                                102                 :                : 
 1606 rhaas@postgresql.org      103                 :          34707 :     pending = hash_search(pendingSyncHash, rlocator, HASH_ENTER, &found);
 2429 noah@leadboat.com         104         [ -  + ]:          34707 :     Assert(!found);
                                105                 :          34707 :     pending->is_truncated = false;
                                106                 :          34707 : }
                                107                 :                : 
                                108                 :                : /*
                                109                 :                :  * RelationCreateStorage
                                110                 :                :  *      Create physical storage for a relation.
                                111                 :                :  *
                                112                 :                :  * Create the underlying disk file storage for the relation. This only
                                113                 :                :  * creates the main fork; additional forks are created lazily by the
                                114                 :                :  * modules that need them.
                                115                 :                :  *
                                116                 :                :  * This function is transactional. The creation is WAL-logged, and if the
                                117                 :                :  * transaction aborts later on, the storage will be destroyed.  A caller
                                118                 :                :  * that does not want the storage to be destroyed in case of an abort may
                                119                 :                :  * pass register_delete = false.
                                120                 :                :  */
                                121                 :                : SMgrRelation
 1606 rhaas@postgresql.org      122                 :         146104 : RelationCreateStorage(RelFileLocator rlocator, char relpersistence,
                                123                 :                :                       bool register_delete)
                                124                 :                : {
                                125                 :                :     SMgrRelation srel;
                                126                 :                :     ProcNumber  procNumber;
                                127                 :                :     bool        needs_wal;
                                128                 :                : 
 2429 noah@leadboat.com         129         [ -  + ]:         146104 :     Assert(!IsInParallelMode());    /* couldn't update pendingSyncHash */
                                130                 :                : 
 5829 rhaas@postgresql.org      131   [ +  +  +  - ]:         146104 :     switch (relpersistence)
                                132                 :                :     {
                                133                 :           4643 :         case RELPERSISTENCE_TEMP:
 1000 heikki.linnakangas@i      134         [ +  - ]:           4643 :             procNumber = ProcNumberForTempRelations();
 5829 rhaas@postgresql.org      135                 :           4643 :             needs_wal = false;
                                136                 :           4643 :             break;
 5813                           137                 :            384 :         case RELPERSISTENCE_UNLOGGED:
 1000 heikki.linnakangas@i      138                 :            384 :             procNumber = INVALID_PROC_NUMBER;
 5813 rhaas@postgresql.org      139                 :            384 :             needs_wal = false;
                                140                 :            384 :             break;
 5829                           141                 :         141077 :         case RELPERSISTENCE_PERMANENT:
 1000 heikki.linnakangas@i      142                 :         141077 :             procNumber = INVALID_PROC_NUMBER;
 5829 rhaas@postgresql.org      143                 :         141077 :             needs_wal = true;
                                144                 :         141077 :             break;
 5829 rhaas@postgresql.org      145                 :UBC           0 :         default:
                                146         [ #  # ]:              0 :             elog(ERROR, "invalid relpersistence: %c", relpersistence);
                                147                 :                :             return NULL;        /* placate compiler */
                                148                 :                :     }
                                149                 :                : 
 1000 heikki.linnakangas@i      150                 :CBC      146104 :     srel = smgropen(rlocator, procNumber);
 6583                           151                 :         146104 :     smgrcreate(srel, MAIN_FORKNUM, false);
                                152                 :                : 
 5829 rhaas@postgresql.org      153         [ +  + ]:         146104 :     if (needs_wal)
 1606                           154                 :         141077 :         log_smgrcreate(&srel->smgr_rlocator.locator, MAIN_FORKNUM);
                                155                 :                : 
                                156                 :                :     /*
                                157                 :                :      * Add the relation to the list of stuff to delete at abort, if we are
                                158                 :                :      * asked to do so.
                                159                 :                :      */
 1705                           160         [ +  + ]:         146104 :     if (register_delete)
                                161                 :                :     {
                                162                 :                :         PendingRelDelete *pending;
                                163                 :                : 
                                164                 :                :         pending = (PendingRelDelete *)
                                165                 :          81037 :             MemoryContextAlloc(TopMemoryContext, sizeof(PendingRelDelete));
 1606                           166                 :          81037 :         pending->rlocator = rlocator;
 1000 heikki.linnakangas@i      167                 :          81037 :         pending->procNumber = procNumber;
 1705 rhaas@postgresql.org      168                 :          81037 :         pending->atCommit = false;   /* delete if abort */
                                169                 :          81037 :         pending->nestLevel = GetCurrentTransactionNestLevel();
                                170                 :          81037 :         pending->next = pendingDeletes;
                                171                 :          81037 :         pendingDeletes = pending;
                                172                 :                :     }
                                173                 :                : 
 2429 noah@leadboat.com         174   [ +  +  +  + ]:         146104 :     if (relpersistence == RELPERSISTENCE_PERMANENT && !XLogIsNeeded())
                                175                 :                :     {
 1000 heikki.linnakangas@i      176         [ -  + ]:          34514 :         Assert(procNumber == INVALID_PROC_NUMBER);
 1606 rhaas@postgresql.org      177                 :          34514 :         AddPendingSync(&rlocator);
                                178                 :                :     }
                                179                 :                : 
 2770 andres@anarazel.de        180                 :         146104 :     return srel;
                                181                 :                : }
                                182                 :                : 
                                183                 :                : /*
                                184                 :                :  * Perform XLogInsert of an XLOG_SMGR_CREATE record to WAL.
                                185                 :                :  */
                                186                 :                : void
 1606 rhaas@postgresql.org      187                 :         162868 : log_smgrcreate(const RelFileLocator *rlocator, ForkNumber forkNum)
                                188                 :                : {
                                189                 :                :     xl_smgr_create xlrec;
                                190                 :                : 
                                191                 :                :     /*
                                192                 :                :      * Make an XLOG entry reporting the file creation.
                                193                 :                :      */
                                194                 :         162868 :     xlrec.rlocator = *rlocator;
 5813                           195                 :         162868 :     xlrec.forkNum = forkNum;
                                196                 :                : 
 4391 heikki.linnakangas@i      197                 :         162868 :     XLogBeginInsert();
  655 peter@eisentraut.org      198                 :         162868 :     XLogRegisterData(&xlrec, sizeof(xlrec));
 4391 heikki.linnakangas@i      199                 :         162868 :     XLogInsert(RM_SMGR_ID, XLOG_SMGR_CREATE | XLR_SPECIAL_REL_UPDATE);
 5813 rhaas@postgresql.org      200                 :         162868 : }
                                201                 :                : 
                                202                 :                : /*
                                203                 :                :  * RelationDropStorage
                                204                 :                :  *      Schedule unlinking of physical storage at transaction commit.
                                205                 :                :  */
                                206                 :                : void
 6583 heikki.linnakangas@i      207                 :          51393 : RelationDropStorage(Relation rel)
                                208                 :                : {
                                209                 :                :     PendingRelDelete *pending;
                                210                 :                : 
                                211                 :                :     /* Add the relation to the list of stuff to delete at commit */
                                212                 :                :     pending = (PendingRelDelete *)
                                213                 :          51393 :         MemoryContextAlloc(TopMemoryContext, sizeof(PendingRelDelete));
 1606 rhaas@postgresql.org      214                 :          51393 :     pending->rlocator = rel->rd_locator;
 1000 heikki.linnakangas@i      215                 :          51393 :     pending->procNumber = rel->rd_backend;
 6583                           216                 :          51393 :     pending->atCommit = true;    /* delete if commit */
                                217                 :          51393 :     pending->nestLevel = GetCurrentTransactionNestLevel();
                                218                 :          51393 :     pending->next = pendingDeletes;
                                219                 :          51393 :     pendingDeletes = pending;
                                220                 :                : 
                                221                 :                :     /*
                                222                 :                :      * NOTE: if the relation was created in this transaction, it will now be
                                223                 :                :      * present in the pending-delete list twice, once with atCommit true and
                                224                 :                :      * once with atCommit false.  Hence, it will be physically deleted at end
                                225                 :                :      * of xact in either case (and the other entry will be ignored by
                                226                 :                :      * smgrDoPendingDeletes, so no error will occur).  We could instead remove
                                227                 :                :      * the existing list entry and delete the physical file immediately, but
                                228                 :                :      * for now I'll keep the logic simple.
                                229                 :                :      */
                                230                 :                : 
                                231                 :          51393 :     RelationCloseSmgr(rel);
                                232                 :          51393 : }
                                233                 :                : 
                                234                 :                : /*
                                235                 :                :  * RelationPreserveStorage
                                236                 :                :  *      Mark a relation as not to be deleted after all.
                                237                 :                :  *
                                238                 :                :  * We need this function because relation mapping changes are committed
                                239                 :                :  * separately from commit of the whole transaction, so it's still possible
                                240                 :                :  * for the transaction to abort after the mapping update is done.
                                241                 :                :  * When a new physical relation is installed in the map, it would be
                                242                 :                :  * scheduled for delete-on-abort, so we'd delete it, and be in trouble.
                                243                 :                :  * The relation mapper fixes this by telling us to not delete such relations
                                244                 :                :  * after all as part of its commit.
                                245                 :                :  *
                                246                 :                :  * We also use this to reuse an old build of an index during ALTER TABLE, this
                                247                 :                :  * time removing the delete-at-commit entry.
                                248                 :                :  *
                                249                 :                :  * No-op if the relation is not among those scheduled for deletion.
                                250                 :                :  */
                                251                 :                : void
 1606 rhaas@postgresql.org      252                 :           6173 : RelationPreserveStorage(RelFileLocator rlocator, bool atCommit)
                                253                 :                : {
                                254                 :                :     PendingRelDelete *pending;
                                255                 :                :     PendingRelDelete *prev;
                                256                 :                :     PendingRelDelete *next;
                                257                 :                : 
 6138 tgl@sss.pgh.pa.us         258                 :           6173 :     prev = NULL;
                                259         [ +  + ]:          36082 :     for (pending = pendingDeletes; pending != NULL; pending = next)
                                260                 :                :     {
                                261                 :          29909 :         next = pending->next;
 1606 rhaas@postgresql.org      262   [ +  +  +  -  :          29909 :         if (RelFileLocatorEquals(rlocator, pending->rlocator)
                                              +  - ]
 5612                           263         [ +  + ]:            585 :             && pending->atCommit == atCommit)
                                264                 :                :         {
                                265                 :                :             /* unlink and delete list entry */
 6138 tgl@sss.pgh.pa.us         266         [ +  + ]:            581 :             if (prev)
                                267                 :            425 :                 prev->next = next;
                                268                 :                :             else
                                269                 :            156 :                 pendingDeletes = next;
                                270                 :            581 :             pfree(pending);
                                271                 :                :             /* prev does not change */
                                272                 :                :         }
                                273                 :                :         else
                                274                 :                :         {
                                275                 :                :             /* unrelated entry, don't touch it */
                                276                 :          29328 :             prev = pending;
                                277                 :                :         }
                                278                 :                :     }
                                279                 :           6173 : }
                                280                 :                : 
                                281                 :                : /*
                                282                 :                :  * RelationTruncate
                                283                 :                :  *      Physically truncate a relation to the specified number of blocks.
                                284                 :                :  *
                                285                 :                :  * This includes getting rid of any buffers for the blocks that are to be
                                286                 :                :  * dropped.
                                287                 :                :  */
                                288                 :                : void
 6583 heikki.linnakangas@i      289                 :            779 : RelationTruncate(Relation rel, BlockNumber nblocks)
                                290                 :                : {
                                291                 :                :     bool        fsm;
                                292                 :                :     bool        vm;
 2622 fujii@postgresql.org      293                 :            779 :     bool        need_fsm_vacuum = false;
                                294                 :                :     ForkNumber  forks[MAX_FORKNUM];
                                295                 :                :     BlockNumber old_blocks[MAX_FORKNUM];
                                296                 :                :     BlockNumber blocks[MAX_FORKNUM];
 2389 tgl@sss.pgh.pa.us         297                 :            779 :     int         nforks = 0;
                                298                 :                :     SMgrRelation reln;
                                299                 :                : 
                                300                 :                :     /*
                                301                 :                :      * Make sure smgr_targblock etc aren't pointing somewhere past new end.
                                302                 :                :      * (Note: don't rely on this reln pointer below this loop.)
                                303                 :                :      */
 1965                           304                 :            779 :     reln = RelationGetSmgr(rel);
                                305                 :            779 :     reln->smgr_targblock = InvalidBlockNumber;
 2311 tmunro@postgresql.or      306         [ +  + ]:           3895 :     for (int i = 0; i <= MAX_FORKNUM; ++i)
 1965 tgl@sss.pgh.pa.us         307                 :           3116 :         reln->smgr_cached_nblocks[i] = InvalidBlockNumber;
                                308                 :                : 
                                309                 :                :     /* Prepare for truncation of MAIN fork of the relation */
 2622 fujii@postgresql.org      310                 :            779 :     forks[nforks] = MAIN_FORKNUM;
  708 tmunro@postgresql.or      311                 :            779 :     old_blocks[nforks] = smgrnblocks(reln, MAIN_FORKNUM);
 2622 fujii@postgresql.org      312                 :            779 :     blocks[nforks] = nblocks;
                                313                 :            779 :     nforks++;
                                314                 :                : 
                                315                 :                :     /* Prepare for truncation of the FSM if it exists */
 1965 tgl@sss.pgh.pa.us         316                 :            779 :     fsm = smgrexists(RelationGetSmgr(rel), FSM_FORKNUM);
 6583 heikki.linnakangas@i      317         [ +  + ]:            779 :     if (fsm)
                                318                 :                :     {
 2622 fujii@postgresql.org      319                 :            256 :         blocks[nforks] = FreeSpaceMapPrepareTruncateRel(rel, nblocks);
                                320         [ +  - ]:            256 :         if (BlockNumberIsValid(blocks[nforks]))
                                321                 :                :         {
                                322                 :            256 :             forks[nforks] = FSM_FORKNUM;
  708 tmunro@postgresql.or      323                 :            256 :             old_blocks[nforks] = smgrnblocks(reln, FSM_FORKNUM);
 2622 fujii@postgresql.org      324                 :            256 :             nforks++;
                                325                 :            256 :             need_fsm_vacuum = true;
                                326                 :                :         }
                                327                 :                :     }
                                328                 :                : 
                                329                 :                :     /* Prepare for truncation of the visibility map too if it exists */
 1965 tgl@sss.pgh.pa.us         330                 :            779 :     vm = smgrexists(RelationGetSmgr(rel), VISIBILITYMAP_FORKNUM);
 6569 heikki.linnakangas@i      331         [ +  + ]:            779 :     if (vm)
                                332                 :                :     {
 2622 fujii@postgresql.org      333                 :            256 :         blocks[nforks] = visibilitymap_prepare_truncate(rel, nblocks);
                                334         [ +  + ]:            256 :         if (BlockNumberIsValid(blocks[nforks]))
                                335                 :                :         {
                                336                 :             90 :             forks[nforks] = VISIBILITYMAP_FORKNUM;
  708 tmunro@postgresql.or      337                 :             90 :             old_blocks[nforks] = smgrnblocks(reln, VISIBILITYMAP_FORKNUM);
 2622 fujii@postgresql.org      338                 :             90 :             nforks++;
                                339                 :                :         }
                                340                 :                :     }
                                341                 :                : 
 2429 noah@leadboat.com         342                 :            779 :     RelationPreTruncate(rel);
                                343                 :                : 
                                344                 :                :     /*
                                345                 :                :      * The code which follows can interact with concurrent checkpoints in two
                                346                 :                :      * separate ways.
                                347                 :                :      *
                                348                 :                :      * First, the truncation operation might drop buffers that the checkpoint
                                349                 :                :      * otherwise would have flushed. If it does, then it's essential that the
                                350                 :                :      * files actually get truncated on disk before the checkpoint record is
                                351                 :                :      * written. Otherwise, if reply begins from that checkpoint, the
                                352                 :                :      * to-be-truncated blocks might still exist on disk but have older
                                353                 :                :      * contents than expected, which can cause replay to fail. It's OK for the
                                354                 :                :      * blocks to not exist on disk at all, but not for them to have the wrong
                                355                 :                :      * contents. For this reason, we need to set DELAY_CHKPT_COMPLETE while
                                356                 :                :      * this code executes.
                                357                 :                :      *
                                358                 :                :      * Second, the call to smgrtruncate() below will in turn call
                                359                 :                :      * RegisterSyncRequest(). We need the sync request created by that call to
                                360                 :                :      * be processed before the checkpoint completes. CheckPointGuts() will
                                361                 :                :      * call ProcessSyncRequests(), but if we register our sync request after
                                362                 :                :      * that happens, then the WAL record for the truncation could end up
                                363                 :                :      * preceding the checkpoint record, while the actual sync doesn't happen
                                364                 :                :      * until the next checkpoint. To prevent that, we need to set
                                365                 :                :      * DELAY_CHKPT_START here. That way, if the XLOG_SMGR_TRUNCATE precedes
                                366                 :                :      * the redo pointer of a concurrent checkpoint, we're guaranteed that the
                                367                 :                :      * corresponding sync request will be processed before the checkpoint
                                368                 :                :      * completes.
                                369                 :                :      */
  725 tmunro@postgresql.or      370         [ -  + ]:            779 :     Assert((MyProc->delayChkptFlags & (DELAY_CHKPT_START | DELAY_CHKPT_COMPLETE)) == 0);
                                371                 :            779 :     MyProc->delayChkptFlags |= DELAY_CHKPT_START | DELAY_CHKPT_COMPLETE;
                                372                 :                : 
                                373                 :                :     /*
                                374                 :                :      * We WAL-log the truncation first and then truncate in a critical
                                375                 :                :      * section. Truncation drops buffers, even if dirty, and then truncates
                                376                 :                :      * disk files. All of that work needs to complete before the lock is
                                377                 :                :      * released, or else old versions of pages on disk that are missing recent
                                378                 :                :      * changes would become accessible again.  We'll try the whole operation
                                379                 :                :      * again in crash recovery if we panic, but even then we can't give up
                                380                 :                :      * because we don't want standbys' relation sizes to diverge and break
                                381                 :                :      * replay or visibility invariants downstream.  The critical section also
                                382                 :                :      * suppresses interrupts.
                                383                 :                :      *
                                384                 :                :      * (See also visibilitymap.c if changing this code.)
                                385                 :                :      */
  708                           386                 :            779 :     START_CRIT_SECTION();
                                387                 :                : 
 5829 rhaas@postgresql.org      388   [ +  +  +  +  :            779 :     if (RelationNeedsWAL(rel))
                                        +  -  +  - ]
                                389                 :                :     {
                                390                 :                :         /*
                                391                 :                :          * Make an XLOG entry reporting the file truncation.
                                392                 :                :          */
                                393                 :                :         XLogRecPtr  lsn;
                                394                 :                :         xl_smgr_truncate xlrec;
                                395                 :                : 
 6583 heikki.linnakangas@i      396                 :            274 :         xlrec.blkno = nblocks;
 1606 rhaas@postgresql.org      397                 :            274 :         xlrec.rlocator = rel->rd_locator;
 3816                           398                 :            274 :         xlrec.flags = SMGR_TRUNCATE_ALL;
                                399                 :                : 
 4391 heikki.linnakangas@i      400                 :            274 :         XLogBeginInsert();
  655 peter@eisentraut.org      401                 :            274 :         XLogRegisterData(&xlrec, sizeof(xlrec));
                                402                 :                : 
 4391 heikki.linnakangas@i      403                 :            274 :         lsn = XLogInsert(RM_SMGR_ID,
                                404                 :                :                          XLOG_SMGR_TRUNCATE | XLR_SPECIAL_REL_UPDATE);
                                405                 :                : 
                                406                 :                :         /*
                                407                 :                :          * Flush, because otherwise the truncation of the main relation might
                                408                 :                :          * hit the disk before the WAL record, and the truncation of the FSM
                                409                 :                :          * or visibility map. If we crashed during that window, we'd be left
                                410                 :                :          * with a truncated heap, but the FSM or visibility map would still
                                411                 :                :          * contain entries for the non-existent heap pages, and standbys would
                                412                 :                :          * also never replay the truncation.
                                413                 :                :          */
  708 tmunro@postgresql.or      414                 :            274 :         XLogFlush(lsn);
                                415                 :                :     }
                                416                 :                : 
                                417                 :                :     /*
                                418                 :                :      * This will first remove any buffers from the buffer pool that should no
                                419                 :                :      * longer exist after truncation is complete, and then truncate the
                                420                 :                :      * corresponding files on disk.
                                421                 :                :      */
                                422                 :            779 :     smgrtruncate(RelationGetSmgr(rel), forks, nforks, old_blocks, blocks);
                                423                 :                : 
                                424         [ -  + ]:            779 :     END_CRIT_SECTION();
                                425                 :                : 
                                426                 :                :     /* We've done all the critical work, so checkpoints are OK now. */
  725                           427                 :            779 :     MyProc->delayChkptFlags &= ~(DELAY_CHKPT_START | DELAY_CHKPT_COMPLETE);
                                428                 :                : 
                                429                 :                :     /*
                                430                 :                :      * Update upper-level FSM pages to account for the truncation. This is
                                431                 :                :      * important because the just-truncated pages were likely marked as
                                432                 :                :      * all-free, and would be preferentially selected.
                                433                 :                :      *
                                434                 :                :      * NB: There's no point in delaying checkpoints until this is done.
                                435                 :                :      * Because the FSM is not WAL-logged, we have to be prepared for the
                                436                 :                :      * possibility of corruption after a crash anyway.
                                437                 :                :      */
 2622 fujii@postgresql.org      438         [ +  + ]:            779 :     if (need_fsm_vacuum)
                                439                 :            256 :         FreeSpaceMapVacuumRange(rel, nblocks, InvalidBlockNumber);
 6583 heikki.linnakangas@i      440                 :            779 : }
                                441                 :                : 
                                442                 :                : /*
                                443                 :                :  * RelationPreTruncate
                                444                 :                :  *      Perform AM-independent work before a physical truncation.
                                445                 :                :  *
                                446                 :                :  * If an access method's relation_nontransactional_truncate does not call
                                447                 :                :  * RelationTruncate(), it must call this before decreasing the table size.
                                448                 :                :  */
                                449                 :                : void
 2429 noah@leadboat.com         450                 :            779 : RelationPreTruncate(Relation rel)
                                451                 :                : {
                                452                 :                :     PendingRelSync *pending;
                                453                 :                : 
                                454         [ +  - ]:            779 :     if (!pendingSyncHash)
                                455                 :            779 :         return;
                                456                 :                : 
 1965 tgl@sss.pgh.pa.us         457                 :UBC           0 :     pending = hash_search(pendingSyncHash,
 1606 rhaas@postgresql.org      458                 :              0 :                           &(RelationGetSmgr(rel)->smgr_rlocator.locator),
                                459                 :                :                           HASH_FIND, NULL);
 2429 noah@leadboat.com         460         [ #  # ]:              0 :     if (pending)
                                461                 :              0 :         pending->is_truncated = true;
                                462                 :                : }
                                463                 :                : 
                                464                 :                : /*
                                465                 :                :  * Copy a fork's data, block by block.
                                466                 :                :  *
                                467                 :                :  * Note that this requires that there is no dirty data in shared buffers. If
                                468                 :                :  * it's possible that there are, callers need to flush those using
                                469                 :                :  * e.g. FlushRelationBuffers(rel).
                                470                 :                :  *
                                471                 :                :  * Also note that this is frequently called via locutions such as
                                472                 :                :  *      RelationCopyStorage(RelationGetSmgr(rel), ...);
                                473                 :                :  * That's safe only because we perform only smgr and WAL operations here.
                                474                 :                :  * If we invoked anything else, a relcache flush could cause our SMgrRelation
                                475                 :                :  * argument to become a dangling pointer.
                                476                 :                :  */
                                477                 :                : void
 2802 andres@anarazel.de        478                 :CBC         130 : RelationCopyStorage(SMgrRelation src, SMgrRelation dst,
                                479                 :                :                     ForkNumber forkNum, char relpersistence, bool page_std)
                                480                 :                : {
                                481                 :                :     bool        use_wal;
                                482                 :                :     bool        copying_initfork;
                                483                 :                :     BlockNumber nblocks;
                                484                 :                :     BlockNumber blkno;
                                485                 :                :     BulkWriteState *bulkstate;
                                486                 :                : 
                                487                 :                :     /*
                                488                 :                :      * The init fork for an unlogged relation in many respects has to be
                                489                 :                :      * treated the same as normal relation, changes need to be WAL logged and
                                490                 :                :      * it needs to be synced to disk.
                                491                 :                :      */
                                492   [ -  +  -  - ]:            130 :     copying_initfork = relpersistence == RELPERSISTENCE_UNLOGGED &&
                                493                 :                :         forkNum == INIT_FORKNUM;
                                494                 :                : 
                                495                 :                :     /*
                                496                 :                :      * We need to log the copied data in WAL iff WAL archiving/streaming is
                                497                 :                :      * enabled AND it's a permanent relation.  This gives the same answer as
                                498                 :                :      * "RelationNeedsWAL(rel) || copying_initfork", because we know the
                                499                 :                :      * current operation created new relation storage.
                                500                 :                :      */
                                501   [ +  +  +  + ]:            150 :     use_wal = XLogIsNeeded() &&
                                502         [ -  + ]:             20 :         (relpersistence == RELPERSISTENCE_PERMANENT || copying_initfork);
                                503                 :                : 
 1009 heikki.linnakangas@i      504                 :            130 :     bulkstate = smgr_bulk_start_smgr(dst, forkNum, use_wal);
                                505                 :                : 
 2802 andres@anarazel.de        506                 :            130 :     nblocks = smgrnblocks(src, forkNum);
                                507                 :                : 
                                508         [ +  + ]:            926 :     for (blkno = 0; blkno < nblocks; blkno++)
                                509                 :                :     {
                                510                 :                :         BulkWriteBuffer buf;
    8 melanieplageman@gmai      511                 :GNC         796 :         bool        allow_page_std = page_std;
                                512                 :                :         int         piv_flags;
                                513                 :                :         bool        checksum_failure;
                                514                 :                :         bool        verified;
                                515                 :                : 
                                516                 :                :         /* If we got a cancel signal during the copy of the data, quit */
 2802 andres@anarazel.de        517         [ -  + ]:CBC         796 :         CHECK_FOR_INTERRUPTS();
                                518                 :                : 
 1009 heikki.linnakangas@i      519                 :            796 :         buf = smgr_bulk_get_buf(bulkstate);
                                520                 :            796 :         smgrread(src, forkNum, blkno, (Page) buf);
                                521                 :                : 
  608 andres@anarazel.de        522                 :            796 :         piv_flags = PIV_LOG_WARNING;
                                523         [ -  + ]:            796 :         if (ignore_checksum_failure)
  608 andres@anarazel.de        524                 :UBC           0 :             piv_flags |= PIV_IGNORE_CHECKSUM_FAILURE;
  608 andres@anarazel.de        525                 :CBC         796 :         verified = PageIsVerified((Page) buf, blkno, piv_flags,
                                526                 :                :                                   &checksum_failure);
  609                           527         [ -  + ]:            796 :         if (checksum_failure)
                                528                 :                :         {
  609 andres@anarazel.de        529                 :UBC           0 :             RelFileLocatorBackend rloc = src->smgr_rlocator;
                                530                 :                : 
  608                           531                 :              0 :             pgstat_prepare_report_checksum_failure(rloc.locator.dbOid);
  609                           532                 :              0 :             pgstat_report_checksum_failures_in_db(rloc.locator.dbOid, 1);
                                533                 :                :         }
                                534                 :                : 
  609 andres@anarazel.de        535         [ -  + ]:CBC         796 :         if (!verified)
                                536                 :                :         {
                                537                 :                :             /*
                                538                 :                :              * For paranoia's sake, capture the file path before invoking the
                                539                 :                :              * ereport machinery.  This guards against the possibility of a
                                540                 :                :              * relcache flush caused by, e.g., an errcontext callback.
                                541                 :                :              * (errcontext callbacks shouldn't be risking any such thing, but
                                542                 :                :              * people have been known to forget that rule.)
                                543                 :                :              */
  641 andres@anarazel.de        544                 :UBC           0 :             RelPathStr  relpath = relpathbackend(src->smgr_rlocator.locator,
                                545                 :                :                                                  src->smgr_rlocator.backend,
                                546                 :                :                                                  forkNum);
                                547                 :                : 
 2802                           548         [ #  # ]:              0 :             ereport(ERROR,
                                549                 :                :                     (errcode(ERRCODE_DATA_CORRUPTED),
                                550                 :                :                      errmsg("invalid page in block %u of relation \"%s\"",
                                551                 :                :                             blkno, relpath.str)));
                                552                 :                :         }
                                553                 :                : 
                                554                 :                :         /*
                                555                 :                :          * For page layouts we don't recognize, hole removal is still safe if
                                556                 :                :          * the exact range that WAL would omit contains only zeroes.
                                557                 :                :          */
    8 melanieplageman@gmai      558   [ +  +  +  +  :GNC         819 :         if (use_wal && !allow_page_std &&
                                              +  + ]
                                559                 :             23 :             PageFreeSpaceBoundsAreValid((Page) buf))
                                560                 :                :         {
                                561                 :             16 :             PageHeader  phdr = (PageHeader) buf;
                                562                 :                : 
                                563                 :                :             allow_page_std =
                                564                 :             16 :                 pg_memory_is_all_zeros((char *) buf + phdr->pd_lower,
                                565                 :             16 :                                        phdr->pd_upper - phdr->pd_lower);
                                566                 :                :         }
                                567                 :                : 
                                568                 :            796 :         smgr_bulk_write(bulkstate, blkno, buf, allow_page_std);
                                569                 :                :     }
 1009 heikki.linnakangas@i      570                 :CBC         130 :     smgr_bulk_finish(bulkstate);
 2802 andres@anarazel.de        571                 :            130 : }
                                572                 :                : 
                                573                 :                : /*
                                574                 :                :  * RelFileLocatorSkippingWAL
                                575                 :                :  *      Check if a BM_PERMANENT relfilelocator is using WAL.
                                576                 :                :  *
                                577                 :                :  * Changes to certain relations must not write WAL; see "Skipping WAL for
                                578                 :                :  * New RelFileLocator" in src/backend/access/transam/README.  Though it is
                                579                 :                :  * known from Relation efficiently, this function is intended for the code
                                580                 :                :  * paths not having access to Relation.
                                581                 :                :  */
                                582                 :                : bool
 1606 rhaas@postgresql.org      583                 :         420215 : RelFileLocatorSkippingWAL(RelFileLocator rlocator)
                                584                 :                : {
 2429 noah@leadboat.com         585   [ +  +  +  + ]:         706416 :     if (!pendingSyncHash ||
 1606 rhaas@postgresql.org      586                 :         286201 :         hash_search(pendingSyncHash, &rlocator, HASH_FIND, NULL) == NULL)
 2429 noah@leadboat.com         587                 :         413509 :         return false;
                                588                 :                : 
                                589                 :           6706 :     return true;
                                590                 :                : }
                                591                 :                : 
                                592                 :                : /*
                                593                 :                :  * EstimatePendingSyncsSpace
                                594                 :                :  *      Estimate space needed to pass syncs to parallel workers.
                                595                 :                :  */
                                596                 :                : Size
                                597                 :            683 : EstimatePendingSyncsSpace(void)
                                598                 :                : {
                                599                 :                :     int64       entries;
                                600                 :                : 
                                601         [ +  + ]:            683 :     entries = pendingSyncHash ? hash_get_num_entries(pendingSyncHash) : 0;
 1606 rhaas@postgresql.org      602                 :            683 :     return mul_size(1 + entries, sizeof(RelFileLocator));
                                603                 :                : }
                                604                 :                : 
                                605                 :                : /*
                                606                 :                :  * SerializePendingSyncs
                                607                 :                :  *      Serialize syncs for parallel workers.
                                608                 :                :  */
                                609                 :                : void
 2429 noah@leadboat.com         610                 :            683 : SerializePendingSyncs(Size maxSize, char *startAddress)
                                611                 :                : {
                                612                 :                :     HTAB       *tmphash;
                                613                 :                :     HASHCTL     ctl;
                                614                 :                :     HASH_SEQ_STATUS scan;
                                615                 :                :     PendingRelSync *sync;
                                616                 :                :     PendingRelDelete *delete;
                                617                 :                :     RelFileLocator *src;
 1606 rhaas@postgresql.org      618                 :            683 :     RelFileLocator *dest = (RelFileLocator *) startAddress;
                                619                 :                : 
 2429 noah@leadboat.com         620         [ +  + ]:            683 :     if (!pendingSyncHash)
                                621                 :            681 :         goto terminate;
                                622                 :                : 
                                623                 :                :     /* Create temporary hash to collect active relfilelocators */
 1606 rhaas@postgresql.org      624                 :              2 :     ctl.keysize = sizeof(RelFileLocator);
                                625                 :              2 :     ctl.entrysize = sizeof(RelFileLocator);
 2429 noah@leadboat.com         626                 :              2 :     ctl.hcxt = CurrentMemoryContext;
 1606 rhaas@postgresql.org      627                 :              2 :     tmphash = hash_create("tmp relfilelocators",
                                628                 :                :                           hash_get_num_entries(pendingSyncHash), &ctl,
                                629                 :                :                           HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
                                630                 :                : 
                                631                 :                :     /* collect all rlocator from pending syncs */
 2429 noah@leadboat.com         632                 :              2 :     hash_seq_init(&scan, pendingSyncHash);
                                633         [ +  + ]:             99 :     while ((sync = (PendingRelSync *) hash_seq_search(&scan)))
 1606 rhaas@postgresql.org      634                 :             97 :         (void) hash_search(tmphash, &sync->rlocator, HASH_ENTER, NULL);
                                635                 :                : 
                                636                 :                :     /* remove deleted rnodes */
 2429 noah@leadboat.com         637         [ +  + ]:            100 :     for (delete = pendingDeletes; delete != NULL; delete = delete->next)
                                638         [ -  + ]:             98 :         if (delete->atCommit)
 1391 peter@eisentraut.org      639                 :UBC           0 :             (void) hash_search(tmphash, &delete->rlocator,
                                640                 :                :                                HASH_REMOVE, NULL);
                                641                 :                : 
 2429 noah@leadboat.com         642                 :CBC           2 :     hash_seq_init(&scan, tmphash);
 1606 rhaas@postgresql.org      643         [ +  + ]:             99 :     while ((src = (RelFileLocator *) hash_seq_search(&scan)))
 2429 noah@leadboat.com         644                 :             97 :         *dest++ = *src;
                                645                 :                : 
                                646                 :              2 :     hash_destroy(tmphash);
                                647                 :                : 
                                648                 :            683 : terminate:
 1606 rhaas@postgresql.org      649   [ +  +  -  +  :            683 :     MemSet(dest, 0, sizeof(RelFileLocator));
                                     -  -  -  -  -  
                                                 - ]
 2429 noah@leadboat.com         650                 :            683 : }
                                651                 :                : 
                                652                 :                : /*
                                653                 :                :  * RestorePendingSyncs
                                654                 :                :  *      Restore syncs within a parallel worker.
                                655                 :                :  *
                                656                 :                :  * RelationNeedsWAL() and RelFileLocatorSkippingWAL() must offer the correct
                                657                 :                :  * answer to parallel workers.  Only smgrDoPendingSyncs() reads the
                                658                 :                :  * is_truncated field, at end of transaction.  Hence, don't restore it.
                                659                 :                :  */
                                660                 :                : void
                                661                 :           2049 : RestorePendingSyncs(char *startAddress)
                                662                 :                : {
                                663                 :                :     RelFileLocator *rlocator;
                                664                 :                : 
                                665         [ -  + ]:           2049 :     Assert(pendingSyncHash == NULL);
 1606 rhaas@postgresql.org      666         [ +  + ]:           2242 :     for (rlocator = (RelFileLocator *) startAddress; rlocator->relNumber != 0;
                                667                 :            193 :          rlocator++)
                                668                 :            193 :         AddPendingSync(rlocator);
 2429 noah@leadboat.com         669                 :           2049 : }
                                670                 :                : 
                                671                 :                : /*
                                672                 :                :  *  smgrDoPendingDeletes() -- Take care of relation deletes at end of xact.
                                673                 :                :  *
                                674                 :                :  * This also runs when aborting a subxact; we want to clean up a failed
                                675                 :                :  * subxact immediately.
                                676                 :                :  *
                                677                 :                :  * Note: It's possible that we're being asked to remove a relation that has
                                678                 :                :  * no physical storage in any fork. In particular, it's possible that we're
                                679                 :                :  * cleaning up an old temporary relation for which RemovePgTempFiles has
                                680                 :                :  * already recovered the physical storage.
                                681                 :                :  */
                                682                 :                : void
 6583 heikki.linnakangas@i      683                 :         447538 : smgrDoPendingDeletes(bool isCommit)
                                684                 :                : {
                                685                 :         447538 :     int         nestLevel = GetCurrentTransactionNestLevel();
                                686                 :                :     PendingRelDelete *pending;
                                687                 :                :     PendingRelDelete *prev;
                                688                 :                :     PendingRelDelete *next;
 5063 alvherre@alvh.no-ip.      689                 :         447538 :     int         nrels = 0,
 4726                           690                 :         447538 :                 maxrels = 0;
                                691                 :         447538 :     SMgrRelation *srels = NULL;
                                692                 :                : 
 6583 heikki.linnakangas@i      693                 :         447538 :     prev = NULL;
                                694         [ +  + ]:         585497 :     for (pending = pendingDeletes; pending != NULL; pending = next)
                                695                 :                :     {
                                696                 :         137959 :         next = pending->next;
                                697         [ +  + ]:         137959 :         if (pending->nestLevel < nestLevel)
                                698                 :                :         {
                                699                 :                :             /* outer-level entries should not be processed yet */
                                700                 :           6198 :             prev = pending;
                                701                 :                :         }
                                702                 :                :         else
                                703                 :                :         {
                                704                 :                :             /* unlink list entry first, so we don't retry on failure */
                                705         [ -  + ]:         131761 :             if (prev)
 6583 heikki.linnakangas@i      706                 :UBC           0 :                 prev->next = next;
                                707                 :                :             else
 6583 heikki.linnakangas@i      708                 :CBC      131761 :                 pendingDeletes = next;
                                709                 :                :             /* do deletion if called for */
                                710         [ +  + ]:         131761 :             if (pending->atCommit == isCommit)
                                711                 :                :             {
                                712                 :                :                 SMgrRelation srel;
                                713                 :                : 
 1000                           714                 :          53795 :                 srel = smgropen(pending->rlocator, pending->procNumber);
                                715                 :                : 
                                716                 :                :                 /* allocate the initial array, or extend it, if needed */
 4726 alvherre@alvh.no-ip.      717         [ +  + ]:          53795 :                 if (maxrels == 0)
                                718                 :                :                 {
                                719                 :          15809 :                     maxrels = 8;
  353 michael@paquier.xyz       720                 :          15809 :                     srels = palloc_array(SMgrRelation, maxrels);
                                721                 :                :                 }
 4726 alvherre@alvh.no-ip.      722         [ +  + ]:          37986 :                 else if (maxrels <= nrels)
                                723                 :                :                 {
 5063                           724                 :           1184 :                     maxrels *= 2;
  353 michael@paquier.xyz       725                 :           1184 :                     srels = repalloc_array(srels, SMgrRelation, maxrels);
                                726                 :                :                 }
                                727                 :                : 
 5063 alvherre@alvh.no-ip.      728                 :          53795 :                 srels[nrels++] = srel;
                                729                 :                :             }
                                730                 :                :             /* must explicitly free the list entry */
 6583 heikki.linnakangas@i      731                 :         131761 :             pfree(pending);
                                732                 :                :             /* prev does not change */
                                733                 :                :         }
                                734                 :                :     }
                                735                 :                : 
 5063 alvherre@alvh.no-ip.      736         [ +  + ]:         447538 :     if (nrels > 0)
                                737                 :                :     {
                                738                 :          15809 :         smgrdounlinkall(srels, nrels, false);
                                739                 :                : 
 2275 tgl@sss.pgh.pa.us         740         [ +  + ]:          69604 :         for (int i = 0; i < nrels; i++)
 5063 alvherre@alvh.no-ip.      741                 :          53795 :             smgrclose(srels[i]);
                                742                 :                : 
 4726                           743                 :          15809 :         pfree(srels);
                                744                 :                :     }
 6583 heikki.linnakangas@i      745                 :         447538 : }
                                746                 :                : 
                                747                 :                : /*
                                748                 :                :  *  smgrDoPendingSyncs() -- Take care of relation syncs at end of xact.
                                749                 :                :  */
                                750                 :                : void
 2429 noah@leadboat.com         751                 :         442353 : smgrDoPendingSyncs(bool isCommit, bool isParallelWorker)
                                752                 :                : {
                                753                 :                :     PendingRelDelete *pending;
                                754                 :         442353 :     int         nrels = 0,
                                755                 :         442353 :                 maxrels = 0;
                                756                 :         442353 :     SMgrRelation *srels = NULL;
                                757                 :                :     HASH_SEQ_STATUS scan;
                                758                 :                :     PendingRelSync *pendingsync;
                                759                 :                : 
                                760         [ -  + ]:         442353 :     Assert(GetCurrentTransactionNestLevel() == 1);
                                761                 :                : 
                                762         [ +  + ]:         442353 :     if (!pendingSyncHash)
                                763                 :         440312 :         return;                 /* no relation needs sync */
                                764                 :                : 
                                765                 :                :     /* Abort -- just throw away all pending syncs */
                                766         [ +  + ]:           2048 :     if (!isCommit)
                                767                 :                :     {
                                768                 :              4 :         pendingSyncHash = NULL;
                                769                 :              4 :         return;
                                770                 :                :     }
                                771                 :                : 
                                772                 :           2044 :     AssertPendingSyncs_RelationCache();
                                773                 :                : 
                                774                 :                :     /* Parallel worker -- just throw away all pending syncs */
                                775         [ +  + ]:           2044 :     if (isParallelWorker)
                                776                 :                :     {
                                777                 :              3 :         pendingSyncHash = NULL;
                                778                 :              3 :         return;
                                779                 :                :     }
                                780                 :                : 
                                781                 :                :     /* Skip syncing nodes that smgrDoPendingDeletes() will delete. */
                                782         [ +  + ]:           9478 :     for (pending = pendingDeletes; pending != NULL; pending = pending->next)
                                783         [ +  + ]:           7437 :         if (pending->atCommit)
 1391 peter@eisentraut.org      784                 :           1960 :             (void) hash_search(pendingSyncHash, &pending->rlocator,
                                785                 :                :                                HASH_REMOVE, NULL);
                                786                 :                : 
 2429 noah@leadboat.com         787                 :           2041 :     hash_seq_init(&scan, pendingSyncHash);
                                788         [ +  + ]:          36444 :     while ((pendingsync = (PendingRelSync *) hash_seq_search(&scan)))
                                789                 :                :     {
                                790                 :                :         ForkNumber  fork;
                                791                 :                :         BlockNumber nblocks[MAX_FORKNUM + 1];
  667 tgl@sss.pgh.pa.us         792                 :          34403 :         uint64      total_blocks = 0;
                                793                 :                :         SMgrRelation srel;
                                794                 :                : 
 1000 heikki.linnakangas@i      795                 :          34403 :         srel = smgropen(pendingsync->rlocator, INVALID_PROC_NUMBER);
                                796                 :                : 
                                797                 :                :         /*
                                798                 :                :          * We emit newpage WAL records for smaller relations.
                                799                 :                :          *
                                800                 :                :          * Small WAL records have a chance to be flushed along with other
                                801                 :                :          * backends' WAL records.  We emit WAL records instead of syncing for
                                802                 :                :          * files that are smaller than a certain threshold, expecting faster
                                803                 :                :          * commit.  The threshold is defined by the GUC wal_skip_threshold.
                                804                 :                :          */
 2429 noah@leadboat.com         805         [ +  - ]:          34403 :         if (!pendingsync->is_truncated)
                                806                 :                :         {
                                807         [ +  + ]:         172015 :             for (fork = 0; fork <= MAX_FORKNUM; fork++)
                                808                 :                :             {
                                809         [ +  + ]:         137612 :                 if (smgrexists(srel, fork))
                                810                 :                :                 {
                                811                 :          44051 :                     BlockNumber n = smgrnblocks(srel, fork);
                                812                 :                : 
                                813                 :                :                     /* we shouldn't come here for unlogged relations */
                                814         [ -  + ]:          44051 :                     Assert(fork != INIT_FORKNUM);
                                815                 :          44051 :                     nblocks[fork] = n;
                                816                 :          44051 :                     total_blocks += n;
                                817                 :                :                 }
                                818                 :                :                 else
                                819                 :          93561 :                     nblocks[fork] = InvalidBlockNumber;
                                820                 :                :             }
                                821                 :                :         }
                                822                 :                : 
                                823                 :                :         /*
                                824                 :                :          * Sync file or emit WAL records for its contents.
                                825                 :                :          *
                                826                 :                :          * Although we emit WAL record if the file is small enough, do file
                                827                 :                :          * sync regardless of the size if the file has experienced a
                                828                 :                :          * truncation. It is because the file would be followed by trailing
                                829                 :                :          * garbage blocks after a crash recovery if, while a past longer file
                                830                 :                :          * had been flushed out, we omitted syncing-out of the file and
                                831                 :                :          * emitted WAL instead.  You might think that we could choose WAL if
                                832                 :                :          * the current main fork is longer than ever, but there's a case where
                                833                 :                :          * main fork is longer than ever but FSM fork gets shorter.
                                834                 :                :          */
                                835         [ +  - ]:          34403 :         if (pendingsync->is_truncated ||
  667 tgl@sss.pgh.pa.us         836         [ +  + ]:          34403 :             total_blocks >= wal_skip_threshold * (uint64) 1024 / BLCKSZ)
                                837                 :                :         {
                                838                 :                :             /* allocate the initial array, or extend it, if needed */
 2429 noah@leadboat.com         839         [ +  - ]:              4 :             if (maxrels == 0)
                                840                 :                :             {
                                841                 :              4 :                 maxrels = 8;
  353 michael@paquier.xyz       842                 :              4 :                 srels = palloc_array(SMgrRelation, maxrels);
                                843                 :                :             }
 2429 noah@leadboat.com         844         [ #  # ]:UBC           0 :             else if (maxrels <= nrels)
                                845                 :                :             {
                                846                 :              0 :                 maxrels *= 2;
  353 michael@paquier.xyz       847                 :              0 :                 srels = repalloc_array(srels, SMgrRelation, maxrels);
                                848                 :                :             }
                                849                 :                : 
 2429 noah@leadboat.com         850                 :CBC           4 :             srels[nrels++] = srel;
                                851                 :                :         }
                                852                 :                :         else
                                853                 :                :         {
                                854                 :                :             /* Emit WAL records for all blocks.  The file is small enough. */
                                855         [ +  + ]:         171995 :             for (fork = 0; fork <= MAX_FORKNUM; fork++)
                                856                 :                :             {
                                857                 :         137596 :                 int         n = nblocks[fork];
                                858                 :                :                 Relation    rel;
                                859                 :                : 
                                860         [ +  + ]:         137596 :                 if (!BlockNumberIsValid(n))
                                861                 :          93552 :                     continue;
                                862                 :                : 
                                863                 :                :                 /*
                                864                 :                :                  * Emit WAL for the whole file.  Unfortunately we don't know
                                865                 :                :                  * what kind of a page this is, so we have to log the full
                                866                 :                :                  * page including any unused space.  ReadBufferExtended()
                                867                 :                :                  * counts some pgstat events; unfortunately, we discard them.
                                868                 :                :                  */
 1606 rhaas@postgresql.org      869                 :          44044 :                 rel = CreateFakeRelcacheEntry(srel->smgr_rlocator.locator);
 2429 noah@leadboat.com         870                 :          44044 :                 log_newpage_range(rel, fork, 0, n, false);
                                871                 :          44044 :                 FreeFakeRelcacheEntry(rel);
                                872                 :                :             }
                                873                 :                :         }
                                874                 :                :     }
                                875                 :                : 
                                876                 :           2041 :     pendingSyncHash = NULL;
                                877                 :                : 
                                878         [ +  + ]:           2041 :     if (nrels > 0)
                                879                 :                :     {
                                880                 :              4 :         smgrdosyncall(srels, nrels);
                                881                 :              4 :         pfree(srels);
                                882                 :                :     }
                                883                 :                : }
                                884                 :                : 
                                885                 :                : /*
                                886                 :                :  * smgrGetPendingDeletes() -- Get a list of non-temp relations to be deleted.
                                887                 :                :  *
                                888                 :                :  * The return value is the number of relations scheduled for termination.
                                889                 :                :  * *ptr is set to point to a freshly-palloc'd array of RelFileLocators.
                                890                 :                :  * If there are no relations to be deleted, *ptr is set to NULL.
                                891                 :                :  *
                                892                 :                :  * Only non-temporary relations are included in the returned list.  This is OK
                                893                 :                :  * because the list is used only in contexts where temporary relations don't
                                894                 :                :  * matter: we're either writing to the two-phase state file (and transactions
                                895                 :                :  * that have touched temp tables can't be prepared) or we're writing to xlog
                                896                 :                :  * (and all temporary files will be zapped if we restart anyway, so no need
                                897                 :                :  * for redo to do it also).
                                898                 :                :  *
                                899                 :                :  * Note that the list does not include anything scheduled for termination
                                900                 :                :  * by upper-level transactions.
                                901                 :                :  */
                                902                 :                : int
 1606 rhaas@postgresql.org      903                 :         413337 : smgrGetPendingDeletes(bool forCommit, RelFileLocator **ptr)
                                904                 :                : {
 6583 heikki.linnakangas@i      905                 :         413337 :     int         nestLevel = GetCurrentTransactionNestLevel();
                                906                 :                :     int         nrels;
                                907                 :                :     RelFileLocator *rptr;
                                908                 :                :     PendingRelDelete *pending;
                                909                 :                : 
                                910                 :         413337 :     nrels = 0;
                                911         [ +  + ]:         549273 :     for (pending = pendingDeletes; pending != NULL; pending = pending->next)
                                912                 :                :     {
 5951 rhaas@postgresql.org      913   [ +  +  +  + ]:         135936 :         if (pending->nestLevel >= nestLevel && pending->atCommit == forCommit
 1000 heikki.linnakangas@i      914         [ +  + ]:          53883 :             && pending->procNumber == INVALID_PROC_NUMBER)
 6583                           915                 :          49240 :             nrels++;
                                916                 :                :     }
                                917         [ +  + ]:         413337 :     if (nrels == 0)
                                918                 :                :     {
                                919                 :         398687 :         *ptr = NULL;
                                920                 :         398687 :         return 0;
                                921                 :                :     }
  353 michael@paquier.xyz       922                 :          14650 :     rptr = palloc_array(RelFileLocator, nrels);
 6583 heikki.linnakangas@i      923                 :          14650 :     *ptr = rptr;
                                924         [ +  + ]:          75849 :     for (pending = pendingDeletes; pending != NULL; pending = pending->next)
                                925                 :                :     {
 5951 rhaas@postgresql.org      926   [ +  +  +  + ]:          61199 :         if (pending->nestLevel >= nestLevel && pending->atCommit == forCommit
 1000 heikki.linnakangas@i      927         [ +  + ]:          49349 :             && pending->procNumber == INVALID_PROC_NUMBER)
                                928                 :                :         {
 1606 rhaas@postgresql.org      929                 :          49240 :             *rptr = pending->rlocator;
 6583 heikki.linnakangas@i      930                 :          49240 :             rptr++;
                                931                 :                :         }
                                932                 :                :     }
                                933                 :          14650 :     return nrels;
                                934                 :                : }
                                935                 :                : 
                                936                 :                : /*
                                937                 :                :  *  PostPrepare_smgr -- Clean up after a successful PREPARE
                                938                 :                :  *
                                939                 :                :  * What we have to do here is throw away the in-memory state about pending
                                940                 :                :  * relation deletes.  It's all been recorded in the 2PC state file and
                                941                 :                :  * it's no longer smgr's job to worry about it.
                                942                 :                :  */
                                943                 :                : void
                                944                 :            307 : PostPrepare_smgr(void)
                                945                 :                : {
                                946                 :                :     PendingRelDelete *pending;
                                947                 :                :     PendingRelDelete *next;
                                948                 :                : 
                                949         [ +  + ]:            395 :     for (pending = pendingDeletes; pending != NULL; pending = next)
                                950                 :                :     {
                                951                 :             88 :         next = pending->next;
                                952                 :             88 :         pendingDeletes = next;
                                953                 :                :         /* must explicitly free the list entry */
                                954                 :             88 :         pfree(pending);
                                955                 :                :     }
                                956                 :            307 : }
                                957                 :                : 
                                958                 :                : 
                                959                 :                : /*
                                960                 :                :  * AtSubCommit_smgr() --- Take care of subtransaction commit.
                                961                 :                :  *
                                962                 :                :  * Reassign all items in the pending-deletes list to the parent transaction.
                                963                 :                :  */
                                964                 :                : void
                                965                 :          17415 : AtSubCommit_smgr(void)
                                966                 :                : {
                                967                 :          17415 :     int         nestLevel = GetCurrentTransactionNestLevel();
                                968                 :                :     PendingRelDelete *pending;
                                969                 :                : 
                                970         [ +  + ]:          17760 :     for (pending = pendingDeletes; pending != NULL; pending = pending->next)
                                971                 :                :     {
                                972         [ +  + ]:            345 :         if (pending->nestLevel >= nestLevel)
                                973                 :            168 :             pending->nestLevel = nestLevel - 1;
                                974                 :                :     }
                                975                 :          17415 : }
                                976                 :                : 
                                977                 :                : /*
                                978                 :                :  * AtSubAbort_smgr() --- Take care of subtransaction abort.
                                979                 :                :  *
                                980                 :                :  * Delete created relations and forget about deleted relations.
                                981                 :                :  * We can execute these operations immediately because we know this
                                982                 :                :  * subtransaction will not commit.
                                983                 :                :  */
                                984                 :                : void
                                985                 :           5716 : AtSubAbort_smgr(void)
                                986                 :                : {
                                987                 :           5716 :     smgrDoPendingDeletes(false);
                                988                 :           5716 : }
                                989                 :                : 
                                990                 :                : void
 4391                           991                 :          17742 : smgr_redo(XLogReaderState *record)
                                992                 :                : {
                                993                 :          17742 :     XLogRecPtr  lsn = record->EndRecPtr;
                                994                 :          17742 :     uint8       info = XLogRecGetInfo(record) & ~XLR_INFO_MASK;
                                995                 :                : 
                                996                 :                :     /* Backup blocks are not used in smgr records */
                                997         [ -  + ]:          17742 :     Assert(!XLogRecHasAnyBlockRefs(record));
                                998                 :                : 
 6583                           999         [ +  + ]:          17742 :     if (info == XLOG_SMGR_CREATE)
                               1000                 :                :     {
                               1001                 :          17682 :         xl_smgr_create *xlrec = (xl_smgr_create *) XLogRecGetData(record);
                               1002                 :                :         SMgrRelation reln;
                               1003                 :                : 
 1000                          1004                 :          17682 :         reln = smgropen(xlrec->rlocator, INVALID_PROC_NUMBER);
 5813 rhaas@postgresql.org     1005                 :          17682 :         smgrcreate(reln, xlrec->forkNum, true);
                               1006                 :                :     }
 6583 heikki.linnakangas@i     1007         [ +  - ]:             60 :     else if (info == XLOG_SMGR_TRUNCATE)
                               1008                 :                :     {
                               1009                 :             60 :         xl_smgr_truncate *xlrec = (xl_smgr_truncate *) XLogRecGetData(record);
                               1010                 :                :         SMgrRelation reln;
                               1011                 :                :         Relation    rel;
                               1012                 :                :         ForkNumber  forks[MAX_FORKNUM];
                               1013                 :                :         BlockNumber blocks[MAX_FORKNUM];
                               1014                 :                :         BlockNumber old_blocks[MAX_FORKNUM];
 2389 tgl@sss.pgh.pa.us        1015                 :             60 :         int         nforks = 0;
 2622 fujii@postgresql.org     1016                 :             60 :         bool        need_fsm_vacuum = false;
                               1017                 :                : 
 1000 heikki.linnakangas@i     1018                 :             60 :         reln = smgropen(xlrec->rlocator, INVALID_PROC_NUMBER);
                               1019                 :                : 
                               1020                 :                :         /*
                               1021                 :                :          * Forcibly create relation if it doesn't exist (which suggests that
                               1022                 :                :          * it was dropped somewhere later in the WAL sequence).  As in
                               1023                 :                :          * XLogReadBufferForRedo, we prefer to recreate the rel and replay the
                               1024                 :                :          * log as best we can until the drop is seen.
                               1025                 :                :          */
 6583                          1026                 :             60 :         smgrcreate(reln, MAIN_FORKNUM, true);
                               1027                 :                : 
                               1028                 :                :         /*
                               1029                 :                :          * Before we perform the truncation, update minimum recovery point to
                               1030                 :                :          * cover this WAL record. Once the relation is truncated, there's no
                               1031                 :                :          * going back. The buffer manager enforces the WAL-first rule for
                               1032                 :                :          * normal updates to relation files, so that the minimum recovery
                               1033                 :                :          * point is always updated before the corresponding change in the data
                               1034                 :                :          * file is flushed to disk. We have to do the same manually here.
                               1035                 :                :          *
                               1036                 :                :          * Doing this before the truncation means that if the truncation fails
                               1037                 :                :          * for some reason, you cannot start up the system even after restart,
                               1038                 :                :          * until you fix the underlying situation so that the truncation will
                               1039                 :                :          * succeed. Alternatively, we could update the minimum recovery point
                               1040                 :                :          * after truncation, but that would leave a small window where the
                               1041                 :                :          * WAL-first rule could be violated.
                               1042                 :                :          */
 5101                          1043                 :             60 :         XLogFlush(lsn);
                               1044                 :                : 
                               1045                 :                :         /* Prepare for truncation of MAIN fork */
 3816 rhaas@postgresql.org     1046         [ +  + ]:             60 :         if ((xlrec->flags & SMGR_TRUNCATE_HEAP) != 0)
                               1047                 :                :         {
 2622 fujii@postgresql.org     1048                 :             59 :             forks[nforks] = MAIN_FORKNUM;
  708 tmunro@postgresql.or     1049                 :             59 :             old_blocks[nforks] = smgrnblocks(reln, MAIN_FORKNUM);
 2622 fujii@postgresql.org     1050                 :             59 :             blocks[nforks] = xlrec->blkno;
                               1051                 :             59 :             nforks++;
                               1052                 :                : 
                               1053                 :                :             /* Also tell xlogutils.c about it */
 1606 rhaas@postgresql.org     1054                 :             59 :             XLogTruncateRelation(xlrec->rlocator, MAIN_FORKNUM, xlrec->blkno);
                               1055                 :                :         }
                               1056                 :                : 
                               1057                 :                :         /* Prepare for truncation of FSM and VM too */
                               1058                 :             60 :         rel = CreateFakeRelcacheEntry(xlrec->rlocator);
                               1059                 :                : 
 3816                          1060   [ +  +  +  + ]:            119 :         if ((xlrec->flags & SMGR_TRUNCATE_FSM) != 0 &&
                               1061                 :             59 :             smgrexists(reln, FSM_FORKNUM))
                               1062                 :                :         {
 2622 fujii@postgresql.org     1063                 :             41 :             blocks[nforks] = FreeSpaceMapPrepareTruncateRel(rel, xlrec->blkno);
                               1064         [ +  - ]:             41 :             if (BlockNumberIsValid(blocks[nforks]))
                               1065                 :                :             {
                               1066                 :             41 :                 forks[nforks] = FSM_FORKNUM;
  708 tmunro@postgresql.or     1067                 :             41 :                 old_blocks[nforks] = smgrnblocks(reln, FSM_FORKNUM);
 2622 fujii@postgresql.org     1068                 :             41 :                 nforks++;
                               1069                 :             41 :                 need_fsm_vacuum = true;
                               1070                 :                :             }
                               1071                 :                :         }
    9 melanieplageman@gmai     1072         [ +  - ]:             60 :         if ((xlrec->flags & SMGR_TRUNCATE_VM) != 0)
                               1073                 :                :         {
                               1074                 :                :             /*
                               1075                 :                :              * Also tell xlogutils.c about it. Do this even if the VM fork is
                               1076                 :                :              * already short enough (e.g. replaying again after a crash), as
                               1077                 :                :              * earlier records may have logged invalid pages for it.
                               1078                 :                :              */
                               1079                 :             60 :             XLogTruncateRelation(xlrec->rlocator, VISIBILITYMAP_FORKNUM,
                               1080                 :                :                                  visibilitymap_truncation_length(xlrec->blkno));
                               1081                 :                : 
 2622 fujii@postgresql.org     1082                 :             60 :             blocks[nforks] = visibilitymap_prepare_truncate(rel, xlrec->blkno);
                               1083                 :                : 
                               1084         [ +  + ]:             60 :             if (BlockNumberIsValid(blocks[nforks]))
                               1085                 :                :             {
                               1086                 :             17 :                 forks[nforks] = VISIBILITYMAP_FORKNUM;
  708 tmunro@postgresql.or     1087                 :             17 :                 old_blocks[nforks] = smgrnblocks(reln, VISIBILITYMAP_FORKNUM);
 2622 fujii@postgresql.org     1088                 :             17 :                 nforks++;
                               1089                 :                :             }
                               1090                 :                :         }
                               1091                 :                : 
                               1092                 :                :         /* Do the real work to truncate relation forks */
                               1093         [ +  + ]:             60 :         if (nforks > 0)
                               1094                 :                :         {
  708 tmunro@postgresql.or     1095                 :             59 :             START_CRIT_SECTION();
                               1096                 :             59 :             smgrtruncate(reln, forks, nforks, old_blocks, blocks);
                               1097         [ -  + ]:             59 :             END_CRIT_SECTION();
                               1098                 :                :         }
                               1099                 :                : 
                               1100                 :                :         /*
                               1101                 :                :          * Update upper-level FSM pages to account for the truncation. This is
                               1102                 :                :          * important because the just-truncated pages were likely marked as
                               1103                 :                :          * all-free, and would be preferentially selected.
                               1104                 :                :          */
 2622 fujii@postgresql.org     1105         [ +  + ]:             60 :         if (need_fsm_vacuum)
                               1106                 :             41 :             FreeSpaceMapVacuumRange(rel, xlrec->blkno,
                               1107                 :                :                                     InvalidBlockNumber);
                               1108                 :                : 
 6136 tgl@sss.pgh.pa.us        1109                 :             60 :         FreeFakeRelcacheEntry(rel);
                               1110                 :                :     }
                               1111                 :                :     else
 6583 heikki.linnakangas@i     1112         [ #  # ]:UBC           0 :         elog(PANIC, "smgr_redo: unknown op code %u", info);
 6583 heikki.linnakangas@i     1113                 :CBC       17742 : }
        

Generated by: LCOV version 2.0-1