LCOV - code coverage report
Current view: top level - src/backend/storage/smgr - md.c (source / functions) Hit Total Coverage
Test: PostgreSQL 12devel Lines: 330 465 71.0 %
Date: 2019-01-18 15:20:34 Functions: 28 30 93.3 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : /*-------------------------------------------------------------------------
       2             :  *
       3             :  * md.c
       4             :  *    This code manages relations that reside on magnetic disk.
       5             :  *
       6             :  * Or at least, that was what the Berkeley folk had in mind when they named
       7             :  * this file.  In reality, what this code provides is an interface from
       8             :  * the smgr API to Unix-like filesystem APIs, so it will work with any type
       9             :  * of device for which the operating system provides filesystem support.
      10             :  * It doesn't matter whether the bits are on spinning rust or some other
      11             :  * storage technology.
      12             :  *
      13             :  * Portions Copyright (c) 1996-2019, PostgreSQL Global Development Group
      14             :  * Portions Copyright (c) 1994, Regents of the University of California
      15             :  *
      16             :  *
      17             :  * IDENTIFICATION
      18             :  *    src/backend/storage/smgr/md.c
      19             :  *
      20             :  *-------------------------------------------------------------------------
      21             :  */
      22             : #include "postgres.h"
      23             : 
      24             : #include <unistd.h>
      25             : #include <fcntl.h>
      26             : #include <sys/file.h>
      27             : 
      28             : #include "miscadmin.h"
      29             : #include "access/xlogutils.h"
      30             : #include "access/xlog.h"
      31             : #include "pgstat.h"
      32             : #include "portability/instr_time.h"
      33             : #include "postmaster/bgwriter.h"
      34             : #include "storage/fd.h"
      35             : #include "storage/bufmgr.h"
      36             : #include "storage/relfilenode.h"
      37             : #include "storage/smgr.h"
      38             : #include "utils/hsearch.h"
      39             : #include "utils/memutils.h"
      40             : #include "pg_trace.h"
      41             : 
      42             : 
      43             : /* intervals for calling AbsorbFsyncRequests in mdsync and mdpostckpt */
      44             : #define FSYNCS_PER_ABSORB       10
      45             : #define UNLINKS_PER_ABSORB      10
      46             : 
      47             : /*
      48             :  * Special values for the segno arg to RememberFsyncRequest.
      49             :  *
      50             :  * Note that CompactCheckpointerRequestQueue assumes that it's OK to remove an
      51             :  * fsync request from the queue if an identical, subsequent request is found.
      52             :  * See comments there before making changes here.
      53             :  */
      54             : #define FORGET_RELATION_FSYNC   (InvalidBlockNumber)
      55             : #define FORGET_DATABASE_FSYNC   (InvalidBlockNumber-1)
      56             : #define UNLINK_RELATION_REQUEST (InvalidBlockNumber-2)
      57             : 
      58             : /*
      59             :  * On Windows, we have to interpret EACCES as possibly meaning the same as
      60             :  * ENOENT, because if a file is unlinked-but-not-yet-gone on that platform,
      61             :  * that's what you get.  Ugh.  This code is designed so that we don't
      62             :  * actually believe these cases are okay without further evidence (namely,
      63             :  * a pending fsync request getting canceled ... see mdsync).
      64             :  */
      65             : #ifndef WIN32
      66             : #define FILE_POSSIBLY_DELETED(err)  ((err) == ENOENT)
      67             : #else
      68             : #define FILE_POSSIBLY_DELETED(err)  ((err) == ENOENT || (err) == EACCES)
      69             : #endif
      70             : 
      71             : /*
      72             :  *  The magnetic disk storage manager keeps track of open file
      73             :  *  descriptors in its own descriptor pool.  This is done to make it
      74             :  *  easier to support relations that are larger than the operating
      75             :  *  system's file size limit (often 2GBytes).  In order to do that,
      76             :  *  we break relations up into "segment" files that are each shorter than
      77             :  *  the OS file size limit.  The segment size is set by the RELSEG_SIZE
      78             :  *  configuration constant in pg_config.h.
      79             :  *
      80             :  *  On disk, a relation must consist of consecutively numbered segment
      81             :  *  files in the pattern
      82             :  *      -- Zero or more full segments of exactly RELSEG_SIZE blocks each
      83             :  *      -- Exactly one partial segment of size 0 <= size < RELSEG_SIZE blocks
      84             :  *      -- Optionally, any number of inactive segments of size 0 blocks.
      85             :  *  The full and partial segments are collectively the "active" segments.
      86             :  *  Inactive segments are those that once contained data but are currently
      87             :  *  not needed because of an mdtruncate() operation.  The reason for leaving
      88             :  *  them present at size zero, rather than unlinking them, is that other
      89             :  *  backends and/or the checkpointer might be holding open file references to
      90             :  *  such segments.  If the relation expands again after mdtruncate(), such
      91             :  *  that a deactivated segment becomes active again, it is important that
      92             :  *  such file references still be valid --- else data might get written
      93             :  *  out to an unlinked old copy of a segment file that will eventually
      94             :  *  disappear.
      95             :  *
      96             :  *  File descriptors are stored in the per-fork md_seg_fds arrays inside
      97             :  *  SMgrRelation. The length of these arrays is stored in md_num_open_segs.
      98             :  *  Note that a fork's md_num_open_segs having a specific value does not
      99             :  *  necessarily mean the relation doesn't have additional segments; we may
     100             :  *  just not have opened the next segment yet.  (We could not have "all
     101             :  *  segments are in the array" as an invariant anyway, since another backend
     102             :  *  could extend the relation while we aren't looking.)  We do not have
     103             :  *  entries for inactive segments, however; as soon as we find a partial
     104             :  *  segment, we assume that any subsequent segments are inactive.
     105             :  *
     106             :  *  The entire MdfdVec array is palloc'd in the MdCxt memory context.
     107             :  */
     108             : 
     109             : typedef struct _MdfdVec
     110             : {
     111             :     File        mdfd_vfd;       /* fd number in fd.c's pool */
     112             :     BlockNumber mdfd_segno;     /* segment number, from 0 */
     113             : } MdfdVec;
     114             : 
     115             : static MemoryContext MdCxt;     /* context for all MdfdVec objects */
     116             : 
     117             : 
     118             : /*
     119             :  * In some contexts (currently, standalone backends and the checkpointer)
     120             :  * we keep track of pending fsync operations: we need to remember all relation
     121             :  * segments that have been written since the last checkpoint, so that we can
     122             :  * fsync them down to disk before completing the next checkpoint.  This hash
     123             :  * table remembers the pending operations.  We use a hash table mostly as
     124             :  * a convenient way of merging duplicate requests.
     125             :  *
     126             :  * We use a similar mechanism to remember no-longer-needed files that can
     127             :  * be deleted after the next checkpoint, but we use a linked list instead of
     128             :  * a hash table, because we don't expect there to be any duplicate requests.
     129             :  *
     130             :  * These mechanisms are only used for non-temp relations; we never fsync
     131             :  * temp rels, nor do we need to postpone their deletion (see comments in
     132             :  * mdunlink).
     133             :  *
     134             :  * (Regular backends do not track pending operations locally, but forward
     135             :  * them to the checkpointer.)
     136             :  */
     137             : typedef uint16 CycleCtr;        /* can be any convenient integer size */
     138             : 
     139             : typedef struct
     140             : {
     141             :     RelFileNode rnode;          /* hash table key (must be first!) */
     142             :     CycleCtr    cycle_ctr;      /* mdsync_cycle_ctr of oldest request */
     143             :     /* requests[f] has bit n set if we need to fsync segment n of fork f */
     144             :     Bitmapset  *requests[MAX_FORKNUM + 1];
     145             :     /* canceled[f] is true if we canceled fsyncs for fork "recently" */
     146             :     bool        canceled[MAX_FORKNUM + 1];
     147             : } PendingOperationEntry;
     148             : 
     149             : typedef struct
     150             : {
     151             :     RelFileNode rnode;          /* the dead relation to delete */
     152             :     CycleCtr    cycle_ctr;      /* mdckpt_cycle_ctr when request was made */
     153             : } PendingUnlinkEntry;
     154             : 
     155             : static HTAB *pendingOpsTable = NULL;
     156             : static List *pendingUnlinks = NIL;
     157             : static MemoryContext pendingOpsCxt; /* context for the above  */
     158             : 
     159             : static CycleCtr mdsync_cycle_ctr = 0;
     160             : static CycleCtr mdckpt_cycle_ctr = 0;
     161             : 
     162             : 
     163             : /*** behavior for mdopen & _mdfd_getseg ***/
     164             : /* ereport if segment not present */
     165             : #define EXTENSION_FAIL              (1 << 0)
     166             : /* return NULL if segment not present */
     167             : #define EXTENSION_RETURN_NULL       (1 << 1)
     168             : /* create new segments as needed */
     169             : #define EXTENSION_CREATE            (1 << 2)
     170             : /* create new segments if needed during recovery */
     171             : #define EXTENSION_CREATE_RECOVERY   (1 << 3)
     172             : /*
     173             :  * Allow opening segments which are preceded by segments smaller than
     174             :  * RELSEG_SIZE, e.g. inactive segments (see above). Note that this breaks
     175             :  * mdnblocks() and related functionality henceforth - which currently is ok,
     176             :  * because this is only required in the checkpointer which never uses
     177             :  * mdnblocks().
     178             :  */
     179             : #define EXTENSION_DONT_CHECK_SIZE   (1 << 4)
     180             : 
     181             : 
     182             : /* local routines */
     183             : static void mdunlinkfork(RelFileNodeBackend rnode, ForkNumber forkNum,
     184             :              bool isRedo);
     185             : static MdfdVec *mdopen(SMgrRelation reln, ForkNumber forknum, int behavior);
     186             : static void register_dirty_segment(SMgrRelation reln, ForkNumber forknum,
     187             :                        MdfdVec *seg);
     188             : static void register_unlink(RelFileNodeBackend rnode);
     189             : static void _fdvec_resize(SMgrRelation reln,
     190             :               ForkNumber forknum,
     191             :               int nseg);
     192             : static char *_mdfd_segpath(SMgrRelation reln, ForkNumber forknum,
     193             :               BlockNumber segno);
     194             : static MdfdVec *_mdfd_openseg(SMgrRelation reln, ForkNumber forkno,
     195             :               BlockNumber segno, int oflags);
     196             : static MdfdVec *_mdfd_getseg(SMgrRelation reln, ForkNumber forkno,
     197             :              BlockNumber blkno, bool skipFsync, int behavior);
     198             : static BlockNumber _mdnblocks(SMgrRelation reln, ForkNumber forknum,
     199             :            MdfdVec *seg);
     200             : 
     201             : 
     202             : /*
     203             :  *  mdinit() -- Initialize private state for magnetic disk storage manager.
     204             :  */
     205             : void
     206       11418 : mdinit(void)
     207             : {
     208       11418 :     MdCxt = AllocSetContextCreate(TopMemoryContext,
     209             :                                   "MdSmgr",
     210             :                                   ALLOCSET_DEFAULT_SIZES);
     211             : 
     212             :     /*
     213             :      * Create pending-operations hashtable if we need it.  Currently, we need
     214             :      * it if we are standalone (not under a postmaster) or if we are a startup
     215             :      * or checkpointer auxiliary process.
     216             :      */
     217       11418 :     if (!IsUnderPostmaster || AmStartupProcess() || AmCheckpointerProcess())
     218             :     {
     219             :         HASHCTL     hash_ctl;
     220             : 
     221             :         /*
     222             :          * XXX: The checkpointer needs to add entries to the pending ops table
     223             :          * when absorbing fsync requests.  That is done within a critical
     224             :          * section, which isn't usually allowed, but we make an exception. It
     225             :          * means that there's a theoretical possibility that you run out of
     226             :          * memory while absorbing fsync requests, which leads to a PANIC.
     227             :          * Fortunately the hash table is small so that's unlikely to happen in
     228             :          * practice.
     229             :          */
     230        1996 :         pendingOpsCxt = AllocSetContextCreate(MdCxt,
     231             :                                               "Pending ops context",
     232             :                                               ALLOCSET_DEFAULT_SIZES);
     233        1996 :         MemoryContextAllowInCriticalSection(pendingOpsCxt, true);
     234             : 
     235        1996 :         MemSet(&hash_ctl, 0, sizeof(hash_ctl));
     236        1996 :         hash_ctl.keysize = sizeof(RelFileNode);
     237        1996 :         hash_ctl.entrysize = sizeof(PendingOperationEntry);
     238        1996 :         hash_ctl.hcxt = pendingOpsCxt;
     239        1996 :         pendingOpsTable = hash_create("Pending Ops Table",
     240             :                                       100L,
     241             :                                       &hash_ctl,
     242             :                                       HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
     243        1996 :         pendingUnlinks = NIL;
     244             :     }
     245       11418 : }
     246             : 
     247             : /*
     248             :  * In archive recovery, we rely on checkpointer to do fsyncs, but we will have
     249             :  * already created the pendingOpsTable during initialization of the startup
     250             :  * process.  Calling this function drops the local pendingOpsTable so that
     251             :  * subsequent requests will be forwarded to checkpointer.
     252             :  */
     253             : void
     254          62 : SetForwardFsyncRequests(void)
     255             : {
     256             :     /* Perform any pending fsyncs we may have queued up, then drop table */
     257          62 :     if (pendingOpsTable)
     258             :     {
     259          62 :         mdsync();
     260          62 :         hash_destroy(pendingOpsTable);
     261             :     }
     262          62 :     pendingOpsTable = NULL;
     263             : 
     264             :     /*
     265             :      * We should not have any pending unlink requests, since mdunlink doesn't
     266             :      * queue unlink requests when isRedo.
     267             :      */
     268             :     Assert(pendingUnlinks == NIL);
     269          62 : }
     270             : 
     271             : /*
     272             :  *  mdexists() -- Does the physical file exist?
     273             :  *
     274             :  * Note: this will return true for lingering files, with pending deletions
     275             :  */
     276             : bool
     277      361070 : mdexists(SMgrRelation reln, ForkNumber forkNum)
     278             : {
     279             :     /*
     280             :      * Close it first, to ensure that we notice if the fork has been unlinked
     281             :      * since we opened it.
     282             :      */
     283      361070 :     mdclose(reln, forkNum);
     284             : 
     285      361070 :     return (mdopen(reln, forkNum, EXTENSION_RETURN_NULL) != NULL);
     286             : }
     287             : 
     288             : /*
     289             :  *  mdcreate() -- Create a new relation on magnetic disk.
     290             :  *
     291             :  * If isRedo is true, it's okay for the relation to exist already.
     292             :  */
     293             : void
     294      133360 : mdcreate(SMgrRelation reln, ForkNumber forkNum, bool isRedo)
     295             : {
     296             :     MdfdVec    *mdfd;
     297             :     char       *path;
     298             :     File        fd;
     299             : 
     300      133360 :     if (isRedo && reln->md_num_open_segs[forkNum] > 0)
     301           0 :         return;                 /* created and opened already... */
     302             : 
     303             :     Assert(reln->md_num_open_segs[forkNum] == 0);
     304             : 
     305      133360 :     path = relpath(reln->smgr_rnode, forkNum);
     306             : 
     307      133360 :     fd = PathNameOpenFile(path, O_RDWR | O_CREAT | O_EXCL | PG_BINARY);
     308             : 
     309      133360 :     if (fd < 0)
     310             :     {
     311         612 :         int         save_errno = errno;
     312             : 
     313             :         /*
     314             :          * During bootstrap, there are cases where a system relation will be
     315             :          * accessed (by internal backend processes) before the bootstrap
     316             :          * script nominally creates it.  Therefore, allow the file to exist
     317             :          * already, even if isRedo is not set.  (See also mdopen)
     318             :          */
     319         612 :         if (isRedo || IsBootstrapProcessingMode())
     320         612 :             fd = PathNameOpenFile(path, O_RDWR | PG_BINARY);
     321         612 :         if (fd < 0)
     322             :         {
     323             :             /* be sure to report the error reported by create, not open */
     324           0 :             errno = save_errno;
     325           0 :             ereport(ERROR,
     326             :                     (errcode_for_file_access(),
     327             :                      errmsg("could not create file \"%s\": %m", path)));
     328             :         }
     329             :     }
     330             : 
     331      133360 :     pfree(path);
     332             : 
     333      133360 :     _fdvec_resize(reln, forkNum, 1);
     334      133360 :     mdfd = &reln->md_seg_fds[forkNum][0];
     335      133360 :     mdfd->mdfd_vfd = fd;
     336      133360 :     mdfd->mdfd_segno = 0;
     337             : }
     338             : 
     339             : /*
     340             :  *  mdunlink() -- Unlink a relation.
     341             :  *
     342             :  * Note that we're passed a RelFileNodeBackend --- by the time this is called,
     343             :  * there won't be an SMgrRelation hashtable entry anymore.
     344             :  *
     345             :  * forkNum can be a fork number to delete a specific fork, or InvalidForkNumber
     346             :  * to delete all forks.
     347             :  *
     348             :  * For regular relations, we don't unlink the first segment file of the rel,
     349             :  * but just truncate it to zero length, and record a request to unlink it after
     350             :  * the next checkpoint.  Additional segments can be unlinked immediately,
     351             :  * however.  Leaving the empty file in place prevents that relfilenode
     352             :  * number from being reused.  The scenario this protects us from is:
     353             :  * 1. We delete a relation (and commit, and actually remove its file).
     354             :  * 2. We create a new relation, which by chance gets the same relfilenode as
     355             :  *    the just-deleted one (OIDs must've wrapped around for that to happen).
     356             :  * 3. We crash before another checkpoint occurs.
     357             :  * During replay, we would delete the file and then recreate it, which is fine
     358             :  * if the contents of the file were repopulated by subsequent WAL entries.
     359             :  * But if we didn't WAL-log insertions, but instead relied on fsyncing the
     360             :  * file after populating it (as for instance CLUSTER and CREATE INDEX do),
     361             :  * the contents of the file would be lost forever.  By leaving the empty file
     362             :  * until after the next checkpoint, we prevent reassignment of the relfilenode
     363             :  * number until it's safe, because relfilenode assignment skips over any
     364             :  * existing file.
     365             :  *
     366             :  * We do not need to go through this dance for temp relations, though, because
     367             :  * we never make WAL entries for temp rels, and so a temp rel poses no threat
     368             :  * to the health of a regular rel that has taken over its relfilenode number.
     369             :  * The fact that temp rels and regular rels have different file naming
     370             :  * patterns provides additional safety.
     371             :  *
     372             :  * All the above applies only to the relation's main fork; other forks can
     373             :  * just be removed immediately, since they are not needed to prevent the
     374             :  * relfilenode number from being recycled.  Also, we do not carefully
     375             :  * track whether other forks have been created or not, but just attempt to
     376             :  * unlink them unconditionally; so we should never complain about ENOENT.
     377             :  *
     378             :  * If isRedo is true, it's unsurprising for the relation to be already gone.
     379             :  * Also, we should remove the file immediately instead of queuing a request
     380             :  * for later, since during redo there's no possibility of creating a
     381             :  * conflicting relation.
     382             :  *
     383             :  * Note: any failure should be reported as WARNING not ERROR, because
     384             :  * we are usually not in a transaction anymore when this is called.
     385             :  */
     386             : void
     387      145016 : mdunlink(RelFileNodeBackend rnode, ForkNumber forkNum, bool isRedo)
     388             : {
     389             :     /*
     390             :      * We have to clean out any pending fsync requests for the doomed
     391             :      * relation, else the next mdsync() will fail.  There can't be any such
     392             :      * requests for a temp relation, though.  We can send just one request
     393             :      * even when deleting multiple forks, since the fsync queuing code accepts
     394             :      * the "InvalidForkNumber = all forks" convention.
     395             :      */
     396      145016 :     if (!RelFileNodeBackendIsTemp(rnode))
     397      126976 :         ForgetRelationFsyncRequests(rnode.node, forkNum);
     398             : 
     399             :     /* Now do the per-fork work */
     400      145016 :     if (forkNum == InvalidForkNumber)
     401             :     {
     402           0 :         for (forkNum = 0; forkNum <= MAX_FORKNUM; forkNum++)
     403           0 :             mdunlinkfork(rnode, forkNum, isRedo);
     404             :     }
     405             :     else
     406      145016 :         mdunlinkfork(rnode, forkNum, isRedo);
     407      145016 : }
     408             : 
     409             : static void
     410      145016 : mdunlinkfork(RelFileNodeBackend rnode, ForkNumber forkNum, bool isRedo)
     411             : {
     412             :     char       *path;
     413             :     int         ret;
     414             : 
     415      145016 :     path = relpath(rnode, forkNum);
     416             : 
     417             :     /*
     418             :      * Delete or truncate the first segment.
     419             :      */
     420      145016 :     if (isRedo || forkNum != MAIN_FORKNUM || RelFileNodeBackendIsTemp(rnode))
     421             :     {
     422      113286 :         ret = unlink(path);
     423      226572 :         if (ret < 0 && errno != ENOENT)
     424           0 :             ereport(WARNING,
     425             :                     (errcode_for_file_access(),
     426             :                      errmsg("could not remove file \"%s\": %m", path)));
     427             :     }
     428             :     else
     429             :     {
     430             :         /* truncate(2) would be easier here, but Windows hasn't got it */
     431             :         int         fd;
     432             : 
     433       31730 :         fd = OpenTransientFile(path, O_RDWR | PG_BINARY);
     434       31730 :         if (fd >= 0)
     435             :         {
     436             :             int         save_errno;
     437             : 
     438       31730 :             ret = ftruncate(fd, 0);
     439       31730 :             save_errno = errno;
     440       31730 :             CloseTransientFile(fd);
     441       31730 :             errno = save_errno;
     442             :         }
     443             :         else
     444           0 :             ret = -1;
     445       31730 :         if (ret < 0 && errno != ENOENT)
     446           0 :             ereport(WARNING,
     447             :                     (errcode_for_file_access(),
     448             :                      errmsg("could not truncate file \"%s\": %m", path)));
     449             : 
     450             :         /* Register request to unlink first segment later */
     451       31730 :         register_unlink(rnode);
     452             :     }
     453             : 
     454             :     /*
     455             :      * Delete any additional segments.
     456             :      */
     457      145016 :     if (ret >= 0)
     458             :     {
     459       38154 :         char       *segpath = (char *) palloc(strlen(path) + 12);
     460             :         BlockNumber segno;
     461             : 
     462             :         /*
     463             :          * Note that because we loop until getting ENOENT, we will correctly
     464             :          * remove all inactive segments as well as active ones.
     465             :          */
     466       38154 :         for (segno = 1;; segno++)
     467             :         {
     468       38154 :             sprintf(segpath, "%s.%u", path, segno);
     469       38154 :             if (unlink(segpath) < 0)
     470             :             {
     471             :                 /* ENOENT is expected after the last segment... */
     472       38154 :                 if (errno != ENOENT)
     473           0 :                     ereport(WARNING,
     474             :                             (errcode_for_file_access(),
     475             :                              errmsg("could not remove file \"%s\": %m", segpath)));
     476       38154 :                 break;
     477             :             }
     478             :         }
     479       38154 :         pfree(segpath);
     480             :     }
     481             : 
     482      145016 :     pfree(path);
     483      145016 : }
     484             : 
     485             : /*
     486             :  *  mdextend() -- Add a block to the specified relation.
     487             :  *
     488             :  *      The semantics are nearly the same as mdwrite(): write at the
     489             :  *      specified position.  However, this is to be used for the case of
     490             :  *      extending a relation (i.e., blocknum is at or beyond the current
     491             :  *      EOF).  Note that we assume writing a block beyond current EOF
     492             :  *      causes intervening file space to become filled with zeroes.
     493             :  */
     494             : void
     495      513208 : mdextend(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum,
     496             :          char *buffer, bool skipFsync)
     497             : {
     498             :     off_t       seekpos;
     499             :     int         nbytes;
     500             :     MdfdVec    *v;
     501             : 
     502             :     /* This assert is too expensive to have on normally ... */
     503             : #ifdef CHECK_WRITE_VS_EXTEND
     504             :     Assert(blocknum >= mdnblocks(reln, forknum));
     505             : #endif
     506             : 
     507             :     /*
     508             :      * If a relation manages to grow to 2^32-1 blocks, refuse to extend it any
     509             :      * more --- we mustn't create a block whose number actually is
     510             :      * InvalidBlockNumber.
     511             :      */
     512      513208 :     if (blocknum == InvalidBlockNumber)
     513           0 :         ereport(ERROR,
     514             :                 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
     515             :                  errmsg("cannot extend file \"%s\" beyond %u blocks",
     516             :                         relpath(reln->smgr_rnode, forknum),
     517             :                         InvalidBlockNumber)));
     518             : 
     519      513208 :     v = _mdfd_getseg(reln, forknum, blocknum, skipFsync, EXTENSION_CREATE);
     520             : 
     521      513208 :     seekpos = (off_t) BLCKSZ * (blocknum % ((BlockNumber) RELSEG_SIZE));
     522             : 
     523             :     Assert(seekpos < (off_t) BLCKSZ * RELSEG_SIZE);
     524             : 
     525      513208 :     if ((nbytes = FileWrite(v->mdfd_vfd, buffer, BLCKSZ, seekpos, WAIT_EVENT_DATA_FILE_EXTEND)) != BLCKSZ)
     526             :     {
     527           0 :         if (nbytes < 0)
     528           0 :             ereport(ERROR,
     529             :                     (errcode_for_file_access(),
     530             :                      errmsg("could not extend file \"%s\": %m",
     531             :                             FilePathName(v->mdfd_vfd)),
     532             :                      errhint("Check free disk space.")));
     533             :         /* short write: complain appropriately */
     534           0 :         ereport(ERROR,
     535             :                 (errcode(ERRCODE_DISK_FULL),
     536             :                  errmsg("could not extend file \"%s\": wrote only %d of %d bytes at block %u",
     537             :                         FilePathName(v->mdfd_vfd),
     538             :                         nbytes, BLCKSZ, blocknum),
     539             :                  errhint("Check free disk space.")));
     540             :     }
     541             : 
     542      513208 :     if (!skipFsync && !SmgrIsTemp(reln))
     543      359438 :         register_dirty_segment(reln, forknum, v);
     544             : 
     545             :     Assert(_mdnblocks(reln, forknum, v) <= ((BlockNumber) RELSEG_SIZE));
     546      513208 : }
     547             : 
     548             : /*
     549             :  *  mdopen() -- Open the specified relation.
     550             :  *
     551             :  * Note we only open the first segment, when there are multiple segments.
     552             :  *
     553             :  * If first segment is not present, either ereport or return NULL according
     554             :  * to "behavior".  We treat EXTENSION_CREATE the same as EXTENSION_FAIL;
     555             :  * EXTENSION_CREATE means it's OK to extend an existing relation, not to
     556             :  * invent one out of whole cloth.
     557             :  */
     558             : static MdfdVec *
     559     3890684 : mdopen(SMgrRelation reln, ForkNumber forknum, int behavior)
     560             : {
     561             :     MdfdVec    *mdfd;
     562             :     char       *path;
     563             :     File        fd;
     564             : 
     565             :     /* No work if already open */
     566     3890684 :     if (reln->md_num_open_segs[forknum] > 0)
     567     2831602 :         return &reln->md_seg_fds[forknum][0];
     568             : 
     569     1059082 :     path = relpath(reln->smgr_rnode, forknum);
     570             : 
     571     1059082 :     fd = PathNameOpenFile(path, O_RDWR | PG_BINARY);
     572             : 
     573     1059082 :     if (fd < 0)
     574             :     {
     575             :         /*
     576             :          * During bootstrap, there are cases where a system relation will be
     577             :          * accessed (by internal backend processes) before the bootstrap
     578             :          * script nominally creates it.  Therefore, accept mdopen() as a
     579             :          * substitute for mdcreate() in bootstrap mode only. (See mdcreate)
     580             :          */
     581      173522 :         if (IsBootstrapProcessingMode())
     582       36162 :             fd = PathNameOpenFile(path, O_RDWR | O_CREAT | O_EXCL | PG_BINARY);
     583      173522 :         if (fd < 0)
     584             :         {
     585      274720 :             if ((behavior & EXTENSION_RETURN_NULL) &&
     586      137360 :                 FILE_POSSIBLY_DELETED(errno))
     587             :             {
     588      137360 :                 pfree(path);
     589      137360 :                 return NULL;
     590             :             }
     591           0 :             ereport(ERROR,
     592             :                     (errcode_for_file_access(),
     593             :                      errmsg("could not open file \"%s\": %m", path)));
     594             :         }
     595             :     }
     596             : 
     597      921722 :     pfree(path);
     598             : 
     599      921722 :     _fdvec_resize(reln, forknum, 1);
     600      921722 :     mdfd = &reln->md_seg_fds[forknum][0];
     601      921722 :     mdfd->mdfd_vfd = fd;
     602      921722 :     mdfd->mdfd_segno = 0;
     603             : 
     604             :     Assert(_mdnblocks(reln, forknum, mdfd) <= ((BlockNumber) RELSEG_SIZE));
     605             : 
     606      921722 :     return mdfd;
     607             : }
     608             : 
     609             : /*
     610             :  *  mdclose() -- Close the specified relation, if it isn't closed already.
     611             :  */
     612             : void
     613     3286006 : mdclose(SMgrRelation reln, ForkNumber forknum)
     614             : {
     615     3286006 :     int         nopensegs = reln->md_num_open_segs[forknum];
     616             : 
     617             :     /* No work if already closed */
     618     3286006 :     if (nopensegs == 0)
     619     2473410 :         return;
     620             : 
     621             :     /* close segments starting from the end */
     622     2437788 :     while (nopensegs > 0)
     623             :     {
     624      812596 :         MdfdVec    *v = &reln->md_seg_fds[forknum][nopensegs - 1];
     625             : 
     626             :         /* if not closed already */
     627      812596 :         if (v->mdfd_vfd >= 0)
     628             :         {
     629      812596 :             FileClose(v->mdfd_vfd);
     630      812596 :             v->mdfd_vfd = -1;
     631             :         }
     632             : 
     633      812596 :         nopensegs--;
     634             :     }
     635             : 
     636             :     /* resize just once, avoids pointless reallocations */
     637      812596 :     _fdvec_resize(reln, forknum, 0);
     638             : }
     639             : 
     640             : /*
     641             :  *  mdprefetch() -- Initiate asynchronous read of the specified block of a relation
     642             :  */
     643             : void
     644          84 : mdprefetch(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum)
     645             : {
     646             : #ifdef USE_PREFETCH
     647             :     off_t       seekpos;
     648             :     MdfdVec    *v;
     649             : 
     650          84 :     v = _mdfd_getseg(reln, forknum, blocknum, false, EXTENSION_FAIL);
     651             : 
     652          84 :     seekpos = (off_t) BLCKSZ * (blocknum % ((BlockNumber) RELSEG_SIZE));
     653             : 
     654             :     Assert(seekpos < (off_t) BLCKSZ * RELSEG_SIZE);
     655             : 
     656          84 :     (void) FilePrefetch(v->mdfd_vfd, seekpos, BLCKSZ, WAIT_EVENT_DATA_FILE_PREFETCH);
     657             : #endif                          /* USE_PREFETCH */
     658          84 : }
     659             : 
     660             : /*
     661             :  * mdwriteback() -- Tell the kernel to write pages back to storage.
     662             :  *
     663             :  * This accepts a range of blocks because flushing several pages at once is
     664             :  * considerably more efficient than doing so individually.
     665             :  */
     666             : void
     667      138704 : mdwriteback(SMgrRelation reln, ForkNumber forknum,
     668             :             BlockNumber blocknum, BlockNumber nblocks)
     669             : {
     670             :     /*
     671             :      * Issue flush requests in as few requests as possible; have to split at
     672             :      * segment boundaries though, since those are actually separate files.
     673             :      */
     674      416112 :     while (nblocks > 0)
     675             :     {
     676      138704 :         BlockNumber nflush = nblocks;
     677             :         off_t       seekpos;
     678             :         MdfdVec    *v;
     679             :         int         segnum_start,
     680             :                     segnum_end;
     681             : 
     682      138704 :         v = _mdfd_getseg(reln, forknum, blocknum, true /* not used */ ,
     683             :                          EXTENSION_RETURN_NULL);
     684             : 
     685             :         /*
     686             :          * We might be flushing buffers of already removed relations, that's
     687             :          * ok, just ignore that case.
     688             :          */
     689      138704 :         if (!v)
     690           0 :             return;
     691             : 
     692             :         /* compute offset inside the current segment */
     693      138704 :         segnum_start = blocknum / RELSEG_SIZE;
     694             : 
     695             :         /* compute number of desired writes within the current segment */
     696      138704 :         segnum_end = (blocknum + nblocks - 1) / RELSEG_SIZE;
     697      138704 :         if (segnum_start != segnum_end)
     698           0 :             nflush = RELSEG_SIZE - (blocknum % ((BlockNumber) RELSEG_SIZE));
     699             : 
     700             :         Assert(nflush >= 1);
     701             :         Assert(nflush <= nblocks);
     702             : 
     703      138704 :         seekpos = (off_t) BLCKSZ * (blocknum % ((BlockNumber) RELSEG_SIZE));
     704             : 
     705      138704 :         FileWriteback(v->mdfd_vfd, seekpos, (off_t) BLCKSZ * nflush, WAIT_EVENT_DATA_FILE_FLUSH);
     706             : 
     707      138704 :         nblocks -= nflush;
     708      138704 :         blocknum += nflush;
     709             :     }
     710             : }
     711             : 
     712             : /*
     713             :  *  mdread() -- Read the specified block from a relation.
     714             :  */
     715             : void
     716      448204 : mdread(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum,
     717             :        char *buffer)
     718             : {
     719             :     off_t       seekpos;
     720             :     int         nbytes;
     721             :     MdfdVec    *v;
     722             : 
     723             :     TRACE_POSTGRESQL_SMGR_MD_READ_START(forknum, blocknum,
     724             :                                         reln->smgr_rnode.node.spcNode,
     725             :                                         reln->smgr_rnode.node.dbNode,
     726             :                                         reln->smgr_rnode.node.relNode,
     727             :                                         reln->smgr_rnode.backend);
     728             : 
     729      448204 :     v = _mdfd_getseg(reln, forknum, blocknum, false,
     730             :                      EXTENSION_FAIL | EXTENSION_CREATE_RECOVERY);
     731             : 
     732      448204 :     seekpos = (off_t) BLCKSZ * (blocknum % ((BlockNumber) RELSEG_SIZE));
     733             : 
     734             :     Assert(seekpos < (off_t) BLCKSZ * RELSEG_SIZE);
     735             : 
     736      448204 :     nbytes = FileRead(v->mdfd_vfd, buffer, BLCKSZ, seekpos, WAIT_EVENT_DATA_FILE_READ);
     737             : 
     738             :     TRACE_POSTGRESQL_SMGR_MD_READ_DONE(forknum, blocknum,
     739             :                                        reln->smgr_rnode.node.spcNode,
     740             :                                        reln->smgr_rnode.node.dbNode,
     741             :                                        reln->smgr_rnode.node.relNode,
     742             :                                        reln->smgr_rnode.backend,
     743             :                                        nbytes,
     744             :                                        BLCKSZ);
     745             : 
     746      448204 :     if (nbytes != BLCKSZ)
     747             :     {
     748           0 :         if (nbytes < 0)
     749           0 :             ereport(ERROR,
     750             :                     (errcode_for_file_access(),
     751             :                      errmsg("could not read block %u in file \"%s\": %m",
     752             :                             blocknum, FilePathName(v->mdfd_vfd))));
     753             : 
     754             :         /*
     755             :          * Short read: we are at or past EOF, or we read a partial block at
     756             :          * EOF.  Normally this is an error; upper levels should never try to
     757             :          * read a nonexistent block.  However, if zero_damaged_pages is ON or
     758             :          * we are InRecovery, we should instead return zeroes without
     759             :          * complaining.  This allows, for example, the case of trying to
     760             :          * update a block that was later truncated away.
     761             :          */
     762           0 :         if (zero_damaged_pages || InRecovery)
     763           0 :             MemSet(buffer, 0, BLCKSZ);
     764             :         else
     765           0 :             ereport(ERROR,
     766             :                     (errcode(ERRCODE_DATA_CORRUPTED),
     767             :                      errmsg("could not read block %u in file \"%s\": read only %d of %d bytes",
     768             :                             blocknum, FilePathName(v->mdfd_vfd),
     769             :                             nbytes, BLCKSZ)));
     770             :     }
     771      448204 : }
     772             : 
     773             : /*
     774             :  *  mdwrite() -- Write the supplied block at the appropriate location.
     775             :  *
     776             :  *      This is to be used only for updating already-existing blocks of a
     777             :  *      relation (ie, those before the current EOF).  To extend a relation,
     778             :  *      use mdextend().
     779             :  */
     780             : void
     781      450354 : mdwrite(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum,
     782             :         char *buffer, bool skipFsync)
     783             : {
     784             :     off_t       seekpos;
     785             :     int         nbytes;
     786             :     MdfdVec    *v;
     787             : 
     788             :     /* This assert is too expensive to have on normally ... */
     789             : #ifdef CHECK_WRITE_VS_EXTEND
     790             :     Assert(blocknum < mdnblocks(reln, forknum));
     791             : #endif
     792             : 
     793             :     TRACE_POSTGRESQL_SMGR_MD_WRITE_START(forknum, blocknum,
     794             :                                          reln->smgr_rnode.node.spcNode,
     795             :                                          reln->smgr_rnode.node.dbNode,
     796             :                                          reln->smgr_rnode.node.relNode,
     797             :                                          reln->smgr_rnode.backend);
     798             : 
     799      450354 :     v = _mdfd_getseg(reln, forknum, blocknum, skipFsync,
     800             :                      EXTENSION_FAIL | EXTENSION_CREATE_RECOVERY);
     801             : 
     802      450354 :     seekpos = (off_t) BLCKSZ * (blocknum % ((BlockNumber) RELSEG_SIZE));
     803             : 
     804             :     Assert(seekpos < (off_t) BLCKSZ * RELSEG_SIZE);
     805             : 
     806      450354 :     nbytes = FileWrite(v->mdfd_vfd, buffer, BLCKSZ, seekpos, WAIT_EVENT_DATA_FILE_WRITE);
     807             : 
     808             :     TRACE_POSTGRESQL_SMGR_MD_WRITE_DONE(forknum, blocknum,
     809             :                                         reln->smgr_rnode.node.spcNode,
     810             :                                         reln->smgr_rnode.node.dbNode,
     811             :                                         reln->smgr_rnode.node.relNode,
     812             :                                         reln->smgr_rnode.backend,
     813             :                                         nbytes,
     814             :                                         BLCKSZ);
     815             : 
     816      450354 :     if (nbytes != BLCKSZ)
     817             :     {
     818           0 :         if (nbytes < 0)
     819           0 :             ereport(ERROR,
     820             :                     (errcode_for_file_access(),
     821             :                      errmsg("could not write block %u in file \"%s\": %m",
     822             :                             blocknum, FilePathName(v->mdfd_vfd))));
     823             :         /* short write: complain appropriately */
     824           0 :         ereport(ERROR,
     825             :                 (errcode(ERRCODE_DISK_FULL),
     826             :                  errmsg("could not write block %u in file \"%s\": wrote only %d of %d bytes",
     827             :                         blocknum,
     828             :                         FilePathName(v->mdfd_vfd),
     829             :                         nbytes, BLCKSZ),
     830             :                  errhint("Check free disk space.")));
     831             :     }
     832             : 
     833      450354 :     if (!skipFsync && !SmgrIsTemp(reln))
     834      428322 :         register_dirty_segment(reln, forknum, v);
     835      450354 : }
     836             : 
     837             : /*
     838             :  *  mdnblocks() -- Get the number of blocks stored in a relation.
     839             :  *
     840             :  *      Important side effect: all active segments of the relation are opened
     841             :  *      and added to the mdfd_seg_fds array.  If this routine has not been
     842             :  *      called, then only segments up to the last one actually touched
     843             :  *      are present in the array.
     844             :  */
     845             : BlockNumber
     846     3393996 : mdnblocks(SMgrRelation reln, ForkNumber forknum)
     847             : {
     848     3393996 :     MdfdVec    *v = mdopen(reln, forknum, EXTENSION_FAIL);
     849             :     BlockNumber nblocks;
     850     3393996 :     BlockNumber segno = 0;
     851             : 
     852             :     /* mdopen has opened the first segment */
     853             :     Assert(reln->md_num_open_segs[forknum] > 0);
     854             : 
     855             :     /*
     856             :      * Start from the last open segments, to avoid redundant seeks.  We have
     857             :      * previously verified that these segments are exactly RELSEG_SIZE long,
     858             :      * and it's useless to recheck that each time.
     859             :      *
     860             :      * NOTE: this assumption could only be wrong if another backend has
     861             :      * truncated the relation.  We rely on higher code levels to handle that
     862             :      * scenario by closing and re-opening the md fd, which is handled via
     863             :      * relcache flush.  (Since the checkpointer doesn't participate in
     864             :      * relcache flush, it could have segment entries for inactive segments;
     865             :      * that's OK because the checkpointer never needs to compute relation
     866             :      * size.)
     867             :      */
     868     3393996 :     segno = reln->md_num_open_segs[forknum] - 1;
     869     3393996 :     v = &reln->md_seg_fds[forknum][segno];
     870             : 
     871             :     for (;;)
     872             :     {
     873     3393996 :         nblocks = _mdnblocks(reln, forknum, v);
     874     3393996 :         if (nblocks > ((BlockNumber) RELSEG_SIZE))
     875           0 :             elog(FATAL, "segment too big");
     876     3393996 :         if (nblocks < ((BlockNumber) RELSEG_SIZE))
     877     3393996 :             return (segno * ((BlockNumber) RELSEG_SIZE)) + nblocks;
     878             : 
     879             :         /*
     880             :          * If segment is exactly RELSEG_SIZE, advance to next one.
     881             :          */
     882           0 :         segno++;
     883             : 
     884             :         /*
     885             :          * We used to pass O_CREAT here, but that has the disadvantage that it
     886             :          * might create a segment which has vanished through some operating
     887             :          * system misadventure.  In such a case, creating the segment here
     888             :          * undermines _mdfd_getseg's attempts to notice and report an error
     889             :          * upon access to a missing segment.
     890             :          */
     891           0 :         v = _mdfd_openseg(reln, forknum, segno, 0);
     892           0 :         if (v == NULL)
     893           0 :             return segno * ((BlockNumber) RELSEG_SIZE);
     894             :     }
     895             : }
     896             : 
     897             : /*
     898             :  *  mdtruncate() -- Truncate relation to specified number of blocks.
     899             :  */
     900             : void
     901         490 : mdtruncate(SMgrRelation reln, ForkNumber forknum, BlockNumber nblocks)
     902             : {
     903             :     BlockNumber curnblk;
     904             :     BlockNumber priorblocks;
     905             :     int         curopensegs;
     906             : 
     907             :     /*
     908             :      * NOTE: mdnblocks makes sure we have opened all active segments, so that
     909             :      * truncation loop will get them all!
     910             :      */
     911         490 :     curnblk = mdnblocks(reln, forknum);
     912         490 :     if (nblocks > curnblk)
     913             :     {
     914             :         /* Bogus request ... but no complaint if InRecovery */
     915           0 :         if (InRecovery)
     916           0 :             return;
     917           0 :         ereport(ERROR,
     918             :                 (errmsg("could not truncate file \"%s\" to %u blocks: it's only %u blocks now",
     919             :                         relpath(reln->smgr_rnode, forknum),
     920             :                         nblocks, curnblk)));
     921             :     }
     922         490 :     if (nblocks == curnblk)
     923         228 :         return;                 /* no work */
     924             : 
     925             :     /*
     926             :      * Truncate segments, starting at the last one. Starting at the end makes
     927             :      * managing the memory for the fd array easier, should there be errors.
     928             :      */
     929         262 :     curopensegs = reln->md_num_open_segs[forknum];
     930         786 :     while (curopensegs > 0)
     931             :     {
     932             :         MdfdVec    *v;
     933             : 
     934         262 :         priorblocks = (curopensegs - 1) * RELSEG_SIZE;
     935             : 
     936         262 :         v = &reln->md_seg_fds[forknum][curopensegs - 1];
     937             : 
     938         262 :         if (priorblocks > nblocks)
     939             :         {
     940             :             /*
     941             :              * This segment is no longer active. We truncate the file, but do
     942             :              * not delete it, for reasons explained in the header comments.
     943             :              */
     944           0 :             if (FileTruncate(v->mdfd_vfd, 0, WAIT_EVENT_DATA_FILE_TRUNCATE) < 0)
     945           0 :                 ereport(ERROR,
     946             :                         (errcode_for_file_access(),
     947             :                          errmsg("could not truncate file \"%s\": %m",
     948             :                                 FilePathName(v->mdfd_vfd))));
     949             : 
     950           0 :             if (!SmgrIsTemp(reln))
     951           0 :                 register_dirty_segment(reln, forknum, v);
     952             : 
     953             :             /* we never drop the 1st segment */
     954             :             Assert(v != &reln->md_seg_fds[forknum][0]);
     955             : 
     956           0 :             FileClose(v->mdfd_vfd);
     957           0 :             _fdvec_resize(reln, forknum, curopensegs - 1);
     958             :         }
     959         262 :         else if (priorblocks + ((BlockNumber) RELSEG_SIZE) > nblocks)
     960             :         {
     961             :             /*
     962             :              * This is the last segment we want to keep. Truncate the file to
     963             :              * the right length. NOTE: if nblocks is exactly a multiple K of
     964             :              * RELSEG_SIZE, we will truncate the K+1st segment to 0 length but
     965             :              * keep it. This adheres to the invariant given in the header
     966             :              * comments.
     967             :              */
     968         262 :             BlockNumber lastsegblocks = nblocks - priorblocks;
     969             : 
     970         262 :             if (FileTruncate(v->mdfd_vfd, (off_t) lastsegblocks * BLCKSZ, WAIT_EVENT_DATA_FILE_TRUNCATE) < 0)
     971           0 :                 ereport(ERROR,
     972             :                         (errcode_for_file_access(),
     973             :                          errmsg("could not truncate file \"%s\" to %u blocks: %m",
     974             :                                 FilePathName(v->mdfd_vfd),
     975             :                                 nblocks)));
     976         262 :             if (!SmgrIsTemp(reln))
     977         222 :                 register_dirty_segment(reln, forknum, v);
     978             :         }
     979             :         else
     980             :         {
     981             :             /*
     982             :              * We still need this segment, so nothing to do for this and any
     983             :              * earlier segment.
     984             :              */
     985           0 :             break;
     986             :         }
     987         262 :         curopensegs--;
     988             :     }
     989             : }
     990             : 
     991             : /*
     992             :  *  mdimmedsync() -- Immediately sync a relation to stable storage.
     993             :  *
     994             :  * Note that only writes already issued are synced; this routine knows
     995             :  * nothing of dirty buffers that may exist inside the buffer manager.
     996             :  */
     997             : void
     998       63502 : mdimmedsync(SMgrRelation reln, ForkNumber forknum)
     999             : {
    1000             :     int         segno;
    1001             : 
    1002             :     /*
    1003             :      * NOTE: mdnblocks makes sure we have opened all active segments, so that
    1004             :      * fsync loop will get them all!
    1005             :      */
    1006       63502 :     mdnblocks(reln, forknum);
    1007             : 
    1008       63502 :     segno = reln->md_num_open_segs[forknum];
    1009             : 
    1010      190506 :     while (segno > 0)
    1011             :     {
    1012       63502 :         MdfdVec    *v = &reln->md_seg_fds[forknum][segno - 1];
    1013             : 
    1014       63502 :         if (FileSync(v->mdfd_vfd, WAIT_EVENT_DATA_FILE_IMMEDIATE_SYNC) < 0)
    1015           0 :             ereport(data_sync_elevel(ERROR),
    1016             :                     (errcode_for_file_access(),
    1017             :                      errmsg("could not fsync file \"%s\": %m",
    1018             :                             FilePathName(v->mdfd_vfd))));
    1019       63502 :         segno--;
    1020             :     }
    1021       63502 : }
    1022             : 
    1023             : /*
    1024             :  *  mdsync() -- Sync previous writes to stable storage.
    1025             :  */
    1026             : void
    1027        2674 : mdsync(void)
    1028             : {
    1029             :     static bool mdsync_in_progress = false;
    1030             : 
    1031             :     HASH_SEQ_STATUS hstat;
    1032             :     PendingOperationEntry *entry;
    1033             :     int         absorb_counter;
    1034             : 
    1035             :     /* Statistics on sync times */
    1036        2674 :     int         processed = 0;
    1037             :     instr_time  sync_start,
    1038             :                 sync_end,
    1039             :                 sync_diff;
    1040             :     uint64      elapsed;
    1041        2674 :     uint64      longest = 0;
    1042        2674 :     uint64      total_elapsed = 0;
    1043             : 
    1044             :     /*
    1045             :      * This is only called during checkpoints, and checkpoints should only
    1046             :      * occur in processes that have created a pendingOpsTable.
    1047             :      */
    1048        2674 :     if (!pendingOpsTable)
    1049           0 :         elog(ERROR, "cannot sync without a pendingOpsTable");
    1050             : 
    1051             :     /*
    1052             :      * If we are in the checkpointer, the sync had better include all fsync
    1053             :      * requests that were queued by backends up to this point.  The tightest
    1054             :      * race condition that could occur is that a buffer that must be written
    1055             :      * and fsync'd for the checkpoint could have been dumped by a backend just
    1056             :      * before it was visited by BufferSync().  We know the backend will have
    1057             :      * queued an fsync request before clearing the buffer's dirtybit, so we
    1058             :      * are safe as long as we do an Absorb after completing BufferSync().
    1059             :      */
    1060        2674 :     AbsorbFsyncRequests();
    1061             : 
    1062             :     /*
    1063             :      * To avoid excess fsync'ing (in the worst case, maybe a never-terminating
    1064             :      * checkpoint), we want to ignore fsync requests that are entered into the
    1065             :      * hashtable after this point --- they should be processed next time,
    1066             :      * instead.  We use mdsync_cycle_ctr to tell old entries apart from new
    1067             :      * ones: new ones will have cycle_ctr equal to the incremented value of
    1068             :      * mdsync_cycle_ctr.
    1069             :      *
    1070             :      * In normal circumstances, all entries present in the table at this point
    1071             :      * will have cycle_ctr exactly equal to the current (about to be old)
    1072             :      * value of mdsync_cycle_ctr.  However, if we fail partway through the
    1073             :      * fsync'ing loop, then older values of cycle_ctr might remain when we
    1074             :      * come back here to try again.  Repeated checkpoint failures would
    1075             :      * eventually wrap the counter around to the point where an old entry
    1076             :      * might appear new, causing us to skip it, possibly allowing a checkpoint
    1077             :      * to succeed that should not have.  To forestall wraparound, any time the
    1078             :      * previous mdsync() failed to complete, run through the table and
    1079             :      * forcibly set cycle_ctr = mdsync_cycle_ctr.
    1080             :      *
    1081             :      * Think not to merge this loop with the main loop, as the problem is
    1082             :      * exactly that that loop may fail before having visited all the entries.
    1083             :      * From a performance point of view it doesn't matter anyway, as this path
    1084             :      * will never be taken in a system that's functioning normally.
    1085             :      */
    1086        2674 :     if (mdsync_in_progress)
    1087             :     {
    1088             :         /* prior try failed, so update any stale cycle_ctr values */
    1089           0 :         hash_seq_init(&hstat, pendingOpsTable);
    1090           0 :         while ((entry = (PendingOperationEntry *) hash_seq_search(&hstat)) != NULL)
    1091             :         {
    1092           0 :             entry->cycle_ctr = mdsync_cycle_ctr;
    1093             :         }
    1094             :     }
    1095             : 
    1096             :     /* Advance counter so that new hashtable entries are distinguishable */
    1097        2674 :     mdsync_cycle_ctr++;
    1098             : 
    1099             :     /* Set flag to detect failure if we don't reach the end of the loop */
    1100        2674 :     mdsync_in_progress = true;
    1101             : 
    1102             :     /* Now scan the hashtable for fsync requests to process */
    1103        2674 :     absorb_counter = FSYNCS_PER_ABSORB;
    1104        2674 :     hash_seq_init(&hstat, pendingOpsTable);
    1105        2674 :     while ((entry = (PendingOperationEntry *) hash_seq_search(&hstat)) != NULL)
    1106             :     {
    1107             :         ForkNumber  forknum;
    1108             : 
    1109             :         /*
    1110             :          * If the entry is new then don't process it this time; it might
    1111             :          * contain multiple fsync-request bits, but they are all new.  Note
    1112             :          * "continue" bypasses the hash-remove call at the bottom of the loop.
    1113             :          */
    1114       96584 :         if (entry->cycle_ctr == mdsync_cycle_ctr)
    1115           0 :             continue;
    1116             : 
    1117             :         /* Else assert we haven't missed it */
    1118             :         Assert((CycleCtr) (entry->cycle_ctr + 1) == mdsync_cycle_ctr);
    1119             : 
    1120             :         /*
    1121             :          * Scan over the forks and segments represented by the entry.
    1122             :          *
    1123             :          * The bitmap manipulations are slightly tricky, because we can call
    1124             :          * AbsorbFsyncRequests() inside the loop and that could result in
    1125             :          * bms_add_member() modifying and even re-palloc'ing the bitmapsets.
    1126             :          * So we detach it, but if we fail we'll merge it with any new
    1127             :          * requests that have arrived in the meantime.
    1128             :          */
    1129      482920 :         for (forknum = 0; forknum <= MAX_FORKNUM; forknum++)
    1130             :         {
    1131      386336 :             Bitmapset  *requests = entry->requests[forknum];
    1132             :             int         segno;
    1133             : 
    1134      386336 :             entry->requests[forknum] = NULL;
    1135      386336 :             entry->canceled[forknum] = false;
    1136             : 
    1137      386336 :             segno = -1;
    1138      892974 :             while ((segno = bms_next_member(requests, segno)) >= 0)
    1139             :             {
    1140             :                 int         failures;
    1141             : 
    1142             :                 /*
    1143             :                  * If fsync is off then we don't have to bother opening the
    1144             :                  * file at all.  (We delay checking until this point so that
    1145             :                  * changing fsync on the fly behaves sensibly.)
    1146             :                  */
    1147      120302 :                 if (!enableFsync)
    1148      120242 :                     continue;
    1149             : 
    1150             :                 /*
    1151             :                  * If in checkpointer, we want to absorb pending requests
    1152             :                  * every so often to prevent overflow of the fsync request
    1153             :                  * queue.  It is unspecified whether newly-added entries will
    1154             :                  * be visited by hash_seq_search, but we don't care since we
    1155             :                  * don't need to process them anyway.
    1156             :                  */
    1157          60 :                 if (--absorb_counter <= 0)
    1158             :                 {
    1159           4 :                     AbsorbFsyncRequests();
    1160           4 :                     absorb_counter = FSYNCS_PER_ABSORB;
    1161             :                 }
    1162             : 
    1163             :                 /*
    1164             :                  * The fsync table could contain requests to fsync segments
    1165             :                  * that have been deleted (unlinked) by the time we get to
    1166             :                  * them. Rather than just hoping an ENOENT (or EACCES on
    1167             :                  * Windows) error can be ignored, what we do on error is
    1168             :                  * absorb pending requests and then retry.  Since mdunlink()
    1169             :                  * queues a "cancel" message before actually unlinking, the
    1170             :                  * fsync request is guaranteed to be marked canceled after the
    1171             :                  * absorb if it really was this case. DROP DATABASE likewise
    1172             :                  * has to tell us to forget fsync requests before it starts
    1173             :                  * deletions.
    1174             :                  */
    1175          60 :                 for (failures = 0;; failures++) /* loop exits at "break" */
    1176           0 :                 {
    1177             :                     SMgrRelation reln;
    1178             :                     MdfdVec    *seg;
    1179             :                     char       *path;
    1180             :                     int         save_errno;
    1181             : 
    1182             :                     /*
    1183             :                      * Find or create an smgr hash entry for this relation.
    1184             :                      * This may seem a bit unclean -- md calling smgr?  But
    1185             :                      * it's really the best solution.  It ensures that the
    1186             :                      * open file reference isn't permanently leaked if we get
    1187             :                      * an error here. (You may say "but an unreferenced
    1188             :                      * SMgrRelation is still a leak!" Not really, because the
    1189             :                      * only case in which a checkpoint is done by a process
    1190             :                      * that isn't about to shut down is in the checkpointer,
    1191             :                      * and it will periodically do smgrcloseall(). This fact
    1192             :                      * justifies our not closing the reln in the success path
    1193             :                      * either, which is a good thing since in non-checkpointer
    1194             :                      * cases we couldn't safely do that.)
    1195             :                      */
    1196          60 :                     reln = smgropen(entry->rnode, InvalidBackendId);
    1197             : 
    1198             :                     /* Attempt to open and fsync the target segment */
    1199          60 :                     seg = _mdfd_getseg(reln, forknum,
    1200          60 :                                        (BlockNumber) segno * (BlockNumber) RELSEG_SIZE,
    1201             :                                        false,
    1202             :                                        EXTENSION_RETURN_NULL
    1203             :                                        | EXTENSION_DONT_CHECK_SIZE);
    1204             : 
    1205          60 :                     INSTR_TIME_SET_CURRENT(sync_start);
    1206             : 
    1207         120 :                     if (seg != NULL &&
    1208          60 :                         FileSync(seg->mdfd_vfd, WAIT_EVENT_DATA_FILE_SYNC) >= 0)
    1209             :                     {
    1210             :                         /* Success; update statistics about sync timing */
    1211          60 :                         INSTR_TIME_SET_CURRENT(sync_end);
    1212          60 :                         sync_diff = sync_end;
    1213          60 :                         INSTR_TIME_SUBTRACT(sync_diff, sync_start);
    1214          60 :                         elapsed = INSTR_TIME_GET_MICROSEC(sync_diff);
    1215          60 :                         if (elapsed > longest)
    1216          10 :                             longest = elapsed;
    1217          60 :                         total_elapsed += elapsed;
    1218          60 :                         processed++;
    1219          60 :                         requests = bms_del_member(requests, segno);
    1220          60 :                         if (log_checkpoints)
    1221           0 :                             elog(DEBUG1, "checkpoint sync: number=%d file=%s time=%.3f msec",
    1222             :                                  processed,
    1223             :                                  FilePathName(seg->mdfd_vfd),
    1224             :                                  (double) elapsed / 1000);
    1225             : 
    1226          60 :                         break;  /* out of retry loop */
    1227             :                     }
    1228             : 
    1229             :                     /* Compute file name for use in message */
    1230           0 :                     save_errno = errno;
    1231           0 :                     path = _mdfd_segpath(reln, forknum, (BlockNumber) segno);
    1232           0 :                     errno = save_errno;
    1233             : 
    1234             :                     /*
    1235             :                      * It is possible that the relation has been dropped or
    1236             :                      * truncated since the fsync request was entered.
    1237             :                      * Therefore, allow ENOENT, but only if we didn't fail
    1238             :                      * already on this file.  This applies both for
    1239             :                      * _mdfd_getseg() and for FileSync, since fd.c might have
    1240             :                      * closed the file behind our back.
    1241             :                      *
    1242             :                      * XXX is there any point in allowing more than one retry?
    1243             :                      * Don't see one at the moment, but easy to change the
    1244             :                      * test here if so.
    1245             :                      */
    1246           0 :                     if (!FILE_POSSIBLY_DELETED(errno) ||
    1247             :                         failures > 0)
    1248           0 :                     {
    1249             :                         Bitmapset  *new_requests;
    1250             : 
    1251             :                         /*
    1252             :                          * We need to merge these unsatisfied requests with
    1253             :                          * any others that have arrived since we started.
    1254             :                          */
    1255           0 :                         new_requests = entry->requests[forknum];
    1256           0 :                         entry->requests[forknum] =
    1257           0 :                             bms_join(new_requests, requests);
    1258             : 
    1259           0 :                         errno = save_errno;
    1260           0 :                         ereport(data_sync_elevel(ERROR),
    1261             :                                 (errcode_for_file_access(),
    1262             :                                  errmsg("could not fsync file \"%s\": %m",
    1263             :                                         path)));
    1264             :                     }
    1265             :                     else
    1266           0 :                         ereport(DEBUG1,
    1267             :                                 (errcode_for_file_access(),
    1268             :                                  errmsg("could not fsync file \"%s\" but retrying: %m",
    1269             :                                         path)));
    1270           0 :                     pfree(path);
    1271             : 
    1272             :                     /*
    1273             :                      * Absorb incoming requests and check to see if a cancel
    1274             :                      * arrived for this relation fork.
    1275             :                      */
    1276           0 :                     AbsorbFsyncRequests();
    1277           0 :                     absorb_counter = FSYNCS_PER_ABSORB; /* might as well... */
    1278             : 
    1279           0 :                     if (entry->canceled[forknum])
    1280           0 :                         break;
    1281             :                 }               /* end retry loop */
    1282             :             }
    1283      386336 :             bms_free(requests);
    1284             :         }
    1285             : 
    1286             :         /*
    1287             :          * We've finished everything that was requested before we started to
    1288             :          * scan the entry.  If no new requests have been inserted meanwhile,
    1289             :          * remove the entry.  Otherwise, update its cycle counter, as all the
    1290             :          * requests now in it must have arrived during this cycle.
    1291             :          */
    1292      482920 :         for (forknum = 0; forknum <= MAX_FORKNUM; forknum++)
    1293             :         {
    1294      386336 :             if (entry->requests[forknum] != NULL)
    1295           0 :                 break;
    1296             :         }
    1297       96584 :         if (forknum <= MAX_FORKNUM)
    1298           0 :             entry->cycle_ctr = mdsync_cycle_ctr;
    1299             :         else
    1300             :         {
    1301             :             /* Okay to remove it */
    1302       96584 :             if (hash_search(pendingOpsTable, &entry->rnode,
    1303             :                             HASH_REMOVE, NULL) == NULL)
    1304           0 :                 elog(ERROR, "pendingOpsTable corrupted");
    1305             :         }
    1306             :     }                           /* end loop over hashtable entries */
    1307             : 
    1308             :     /* Return sync performance metrics for report at checkpoint end */
    1309        2674 :     CheckpointStats.ckpt_sync_rels = processed;
    1310        2674 :     CheckpointStats.ckpt_longest_sync = longest;
    1311        2674 :     CheckpointStats.ckpt_agg_sync_time = total_elapsed;
    1312             : 
    1313             :     /* Flag successful completion of mdsync */
    1314        2674 :     mdsync_in_progress = false;
    1315        2674 : }
    1316             : 
    1317             : /*
    1318             :  * mdpreckpt() -- Do pre-checkpoint work
    1319             :  *
    1320             :  * To distinguish unlink requests that arrived before this checkpoint
    1321             :  * started from those that arrived during the checkpoint, we use a cycle
    1322             :  * counter similar to the one we use for fsync requests. That cycle
    1323             :  * counter is incremented here.
    1324             :  *
    1325             :  * This must be called *before* the checkpoint REDO point is determined.
    1326             :  * That ensures that we won't delete files too soon.
    1327             :  *
    1328             :  * Note that we can't do anything here that depends on the assumption
    1329             :  * that the checkpoint will be completed.
    1330             :  */
    1331             : void
    1332        2598 : mdpreckpt(void)
    1333             : {
    1334             :     /*
    1335             :      * Any unlink requests arriving after this point will be assigned the next
    1336             :      * cycle counter, and won't be unlinked until next checkpoint.
    1337             :      */
    1338        2598 :     mdckpt_cycle_ctr++;
    1339        2598 : }
    1340             : 
    1341             : /*
    1342             :  * mdpostckpt() -- Do post-checkpoint work
    1343             :  *
    1344             :  * Remove any lingering files that can now be safely removed.
    1345             :  */
    1346             : void
    1347        2598 : mdpostckpt(void)
    1348             : {
    1349             :     int         absorb_counter;
    1350             : 
    1351        2598 :     absorb_counter = UNLINKS_PER_ABSORB;
    1352       31946 :     while (pendingUnlinks != NIL)
    1353             :     {
    1354       26760 :         PendingUnlinkEntry *entry = (PendingUnlinkEntry *) linitial(pendingUnlinks);
    1355             :         char       *path;
    1356             : 
    1357             :         /*
    1358             :          * New entries are appended to the end, so if the entry is new we've
    1359             :          * reached the end of old entries.
    1360             :          *
    1361             :          * Note: if just the right number of consecutive checkpoints fail, we
    1362             :          * could be fooled here by cycle_ctr wraparound.  However, the only
    1363             :          * consequence is that we'd delay unlinking for one more checkpoint,
    1364             :          * which is perfectly tolerable.
    1365             :          */
    1366       26760 :         if (entry->cycle_ctr == mdckpt_cycle_ctr)
    1367          10 :             break;
    1368             : 
    1369             :         /* Unlink the file */
    1370       26750 :         path = relpathperm(entry->rnode, MAIN_FORKNUM);
    1371       26750 :         if (unlink(path) < 0)
    1372             :         {
    1373             :             /*
    1374             :              * There's a race condition, when the database is dropped at the
    1375             :              * same time that we process the pending unlink requests. If the
    1376             :              * DROP DATABASE deletes the file before we do, we will get ENOENT
    1377             :              * here. rmtree() also has to ignore ENOENT errors, to deal with
    1378             :              * the possibility that we delete the file first.
    1379             :              */
    1380           0 :             if (errno != ENOENT)
    1381           0 :                 ereport(WARNING,
    1382             :                         (errcode_for_file_access(),
    1383             :                          errmsg("could not remove file \"%s\": %m", path)));
    1384             :         }
    1385       26750 :         pfree(path);
    1386             : 
    1387             :         /* And remove the list entry */
    1388       26750 :         pendingUnlinks = list_delete_first(pendingUnlinks);
    1389       26750 :         pfree(entry);
    1390             : 
    1391             :         /*
    1392             :          * As in mdsync, we don't want to stop absorbing fsync requests for a
    1393             :          * long time when there are many deletions to be done.  We can safely
    1394             :          * call AbsorbFsyncRequests() at this point in the loop (note it might
    1395             :          * try to delete list entries).
    1396             :          */
    1397       26750 :         if (--absorb_counter <= 0)
    1398             :         {
    1399        2634 :             AbsorbFsyncRequests();
    1400        2634 :             absorb_counter = UNLINKS_PER_ABSORB;
    1401             :         }
    1402             :     }
    1403        2598 : }
    1404             : 
    1405             : /*
    1406             :  * register_dirty_segment() -- Mark a relation segment as needing fsync
    1407             :  *
    1408             :  * If there is a local pending-ops table, just make an entry in it for
    1409             :  * mdsync to process later.  Otherwise, try to pass off the fsync request
    1410             :  * to the checkpointer process.  If that fails, just do the fsync
    1411             :  * locally before returning (we hope this will not happen often enough
    1412             :  * to be a performance problem).
    1413             :  */
    1414             : static void
    1415      787982 : register_dirty_segment(SMgrRelation reln, ForkNumber forknum, MdfdVec *seg)
    1416             : {
    1417             :     /* Temp relations should never be fsync'd */
    1418             :     Assert(!SmgrIsTemp(reln));
    1419             : 
    1420      787982 :     if (pendingOpsTable)
    1421             :     {
    1422             :         /* push it into local pending-ops table */
    1423      632724 :         RememberFsyncRequest(reln->smgr_rnode.node, forknum, seg->mdfd_segno);
    1424             :     }
    1425             :     else
    1426             :     {
    1427      155258 :         if (ForwardFsyncRequest(reln->smgr_rnode.node, forknum, seg->mdfd_segno))
    1428      155258 :             return;             /* passed it off successfully */
    1429             : 
    1430           0 :         ereport(DEBUG1,
    1431             :                 (errmsg("could not forward fsync request because request queue is full")));
    1432             : 
    1433           0 :         if (FileSync(seg->mdfd_vfd, WAIT_EVENT_DATA_FILE_SYNC) < 0)
    1434           0 :             ereport(data_sync_elevel(ERROR),
    1435             :                     (errcode_for_file_access(),
    1436             :                      errmsg("could not fsync file \"%s\": %m",
    1437             :                             FilePathName(seg->mdfd_vfd))));
    1438             :     }
    1439             : }
    1440             : 
    1441             : /*
    1442             :  * register_unlink() -- Schedule a file to be deleted after next checkpoint
    1443             :  *
    1444             :  * We don't bother passing in the fork number, because this is only used
    1445             :  * with main forks.
    1446             :  *
    1447             :  * As with register_dirty_segment, this could involve either a local or
    1448             :  * a remote pending-ops table.
    1449             :  */
    1450             : static void
    1451       31730 : register_unlink(RelFileNodeBackend rnode)
    1452             : {
    1453             :     /* Should never be used with temp relations */
    1454             :     Assert(!RelFileNodeBackendIsTemp(rnode));
    1455             : 
    1456       31730 :     if (pendingOpsTable)
    1457             :     {
    1458             :         /* push it into local pending-ops table */
    1459           0 :         RememberFsyncRequest(rnode.node, MAIN_FORKNUM,
    1460             :                              UNLINK_RELATION_REQUEST);
    1461             :     }
    1462             :     else
    1463             :     {
    1464             :         /*
    1465             :          * Notify the checkpointer about it.  If we fail to queue the request
    1466             :          * message, we have to sleep and try again, because we can't simply
    1467             :          * delete the file now.  Ugly, but hopefully won't happen often.
    1468             :          *
    1469             :          * XXX should we just leave the file orphaned instead?
    1470             :          */
    1471             :         Assert(IsUnderPostmaster);
    1472       63460 :         while (!ForwardFsyncRequest(rnode.node, MAIN_FORKNUM,
    1473             :                                     UNLINK_RELATION_REQUEST))
    1474           0 :             pg_usleep(10000L);  /* 10 msec seems a good number */
    1475             :     }
    1476       31730 : }
    1477             : 
    1478             : /*
    1479             :  * RememberFsyncRequest() -- callback from checkpointer side of fsync request
    1480             :  *
    1481             :  * We stuff fsync requests into the local hash table for execution
    1482             :  * during the checkpointer's next checkpoint.  UNLINK requests go into a
    1483             :  * separate linked list, however, because they get processed separately.
    1484             :  *
    1485             :  * The range of possible segment numbers is way less than the range of
    1486             :  * BlockNumber, so we can reserve high values of segno for special purposes.
    1487             :  * We define three:
    1488             :  * - FORGET_RELATION_FSYNC means to cancel pending fsyncs for a relation,
    1489             :  *   either for one fork, or all forks if forknum is InvalidForkNumber
    1490             :  * - FORGET_DATABASE_FSYNC means to cancel pending fsyncs for a whole database
    1491             :  * - UNLINK_RELATION_REQUEST is a request to delete the file after the next
    1492             :  *   checkpoint.
    1493             :  * Note also that we're assuming real segment numbers don't exceed INT_MAX.
    1494             :  *
    1495             :  * (Handling FORGET_DATABASE_FSYNC requests is a tad slow because the hash
    1496             :  * table has to be searched linearly, but dropping a database is a pretty
    1497             :  * heavyweight operation anyhow, so we'll live with it.)
    1498             :  */
    1499             : void
    1500      918610 : RememberFsyncRequest(RelFileNode rnode, ForkNumber forknum, BlockNumber segno)
    1501             : {
    1502             :     Assert(pendingOpsTable);
    1503             : 
    1504      918610 :     if (segno == FORGET_RELATION_FSYNC)
    1505             :     {
    1506             :         /* Remove any pending requests for the relation (one or all forks) */
    1507             :         PendingOperationEntry *entry;
    1508             : 
    1509      107032 :         entry = (PendingOperationEntry *) hash_search(pendingOpsTable,
    1510             :                                                       &rnode,
    1511             :                                                       HASH_FIND,
    1512             :                                                       NULL);
    1513      107032 :         if (entry)
    1514             :         {
    1515             :             /*
    1516             :              * We can't just delete the entry since mdsync could have an
    1517             :              * active hashtable scan.  Instead we delete the bitmapsets; this
    1518             :              * is safe because of the way mdsync is coded.  We also set the
    1519             :              * "canceled" flags so that mdsync can tell that a cancel arrived
    1520             :              * for the fork(s).
    1521             :              */
    1522       48576 :             if (forknum == InvalidForkNumber)
    1523             :             {
    1524             :                 /* remove requests for all forks */
    1525           0 :                 for (forknum = 0; forknum <= MAX_FORKNUM; forknum++)
    1526             :                 {
    1527           0 :                     bms_free(entry->requests[forknum]);
    1528           0 :                     entry->requests[forknum] = NULL;
    1529           0 :                     entry->canceled[forknum] = true;
    1530             :                 }
    1531             :             }
    1532             :             else
    1533             :             {
    1534             :                 /* remove requests for single fork */
    1535       48576 :                 bms_free(entry->requests[forknum]);
    1536       48576 :                 entry->requests[forknum] = NULL;
    1537       48576 :                 entry->canceled[forknum] = true;
    1538             :             }
    1539             :         }
    1540             :     }
    1541      811578 :     else if (segno == FORGET_DATABASE_FSYNC)
    1542             :     {
    1543             :         /* Remove any pending requests for the entire database */
    1544             :         HASH_SEQ_STATUS hstat;
    1545             :         PendingOperationEntry *entry;
    1546             :         ListCell   *cell,
    1547             :                    *prev,
    1548             :                    *next;
    1549             : 
    1550             :         /* Remove fsync requests */
    1551           6 :         hash_seq_init(&hstat, pendingOpsTable);
    1552          24 :         while ((entry = (PendingOperationEntry *) hash_seq_search(&hstat)) != NULL)
    1553             :         {
    1554          12 :             if (entry->rnode.dbNode == rnode.dbNode)
    1555             :             {
    1556             :                 /* remove requests for all forks */
    1557          20 :                 for (forknum = 0; forknum <= MAX_FORKNUM; forknum++)
    1558             :                 {
    1559          16 :                     bms_free(entry->requests[forknum]);
    1560          16 :                     entry->requests[forknum] = NULL;
    1561          16 :                     entry->canceled[forknum] = true;
    1562             :                 }
    1563             :             }
    1564             :         }
    1565             : 
    1566             :         /* Remove unlink requests */
    1567           6 :         prev = NULL;
    1568           6 :         for (cell = list_head(pendingUnlinks); cell; cell = next)
    1569             :         {
    1570           0 :             PendingUnlinkEntry *entry = (PendingUnlinkEntry *) lfirst(cell);
    1571             : 
    1572           0 :             next = lnext(cell);
    1573           0 :             if (entry->rnode.dbNode == rnode.dbNode)
    1574             :             {
    1575           0 :                 pendingUnlinks = list_delete_cell(pendingUnlinks, cell, prev);
    1576           0 :                 pfree(entry);
    1577             :             }
    1578             :             else
    1579           0 :                 prev = cell;
    1580             :         }
    1581             :     }
    1582      811572 :     else if (segno == UNLINK_RELATION_REQUEST)
    1583             :     {
    1584             :         /* Unlink request: put it in the linked list */
    1585       26750 :         MemoryContext oldcxt = MemoryContextSwitchTo(pendingOpsCxt);
    1586             :         PendingUnlinkEntry *entry;
    1587             : 
    1588             :         /* PendingUnlinkEntry doesn't store forknum, since it's always MAIN */
    1589             :         Assert(forknum == MAIN_FORKNUM);
    1590             : 
    1591       26750 :         entry = palloc(sizeof(PendingUnlinkEntry));
    1592       26750 :         entry->rnode = rnode;
    1593       26750 :         entry->cycle_ctr = mdckpt_cycle_ctr;
    1594             : 
    1595       26750 :         pendingUnlinks = lappend(pendingUnlinks, entry);
    1596             : 
    1597       26750 :         MemoryContextSwitchTo(oldcxt);
    1598             :     }
    1599             :     else
    1600             :     {
    1601             :         /* Normal case: enter a request to fsync this segment */
    1602      784822 :         MemoryContext oldcxt = MemoryContextSwitchTo(pendingOpsCxt);
    1603             :         PendingOperationEntry *entry;
    1604             :         bool        found;
    1605             : 
    1606      784822 :         entry = (PendingOperationEntry *) hash_search(pendingOpsTable,
    1607             :                                                       &rnode,
    1608             :                                                       HASH_ENTER,
    1609             :                                                       &found);
    1610             :         /* if new entry, initialize it */
    1611      784822 :         if (!found)
    1612             :         {
    1613       96586 :             entry->cycle_ctr = mdsync_cycle_ctr;
    1614       96586 :             MemSet(entry->requests, 0, sizeof(entry->requests));
    1615       96586 :             MemSet(entry->canceled, 0, sizeof(entry->canceled));
    1616             :         }
    1617             : 
    1618             :         /*
    1619             :          * NB: it's intentional that we don't change cycle_ctr if the entry
    1620             :          * already exists.  The cycle_ctr must represent the oldest fsync
    1621             :          * request that could be in the entry.
    1622             :          */
    1623             : 
    1624      784822 :         entry->requests[forknum] = bms_add_member(entry->requests[forknum],
    1625             :                                                   (int) segno);
    1626             : 
    1627      784822 :         MemoryContextSwitchTo(oldcxt);
    1628             :     }
    1629      918610 : }
    1630             : 
    1631             : /*
    1632             :  * ForgetRelationFsyncRequests -- forget any fsyncs for a relation fork
    1633             :  *
    1634             :  * forknum == InvalidForkNumber means all forks, although this code doesn't
    1635             :  * actually know that, since it's just forwarding the request elsewhere.
    1636             :  */
    1637             : void
    1638      126976 : ForgetRelationFsyncRequests(RelFileNode rnode, ForkNumber forknum)
    1639             : {
    1640      126976 :     if (pendingOpsTable)
    1641             :     {
    1642             :         /* standalone backend or startup process: fsync state is local */
    1643          32 :         RememberFsyncRequest(rnode, forknum, FORGET_RELATION_FSYNC);
    1644             :     }
    1645      126944 :     else if (IsUnderPostmaster)
    1646             :     {
    1647             :         /*
    1648             :          * Notify the checkpointer about it.  If we fail to queue the cancel
    1649             :          * message, we have to sleep and try again ... ugly, but hopefully
    1650             :          * won't happen often.
    1651             :          *
    1652             :          * XXX should we CHECK_FOR_INTERRUPTS in this loop?  Escaping with an
    1653             :          * error would leave the no-longer-used file still present on disk,
    1654             :          * which would be bad, so I'm inclined to assume that the checkpointer
    1655             :          * will always empty the queue soon.
    1656             :          */
    1657      253888 :         while (!ForwardFsyncRequest(rnode, forknum, FORGET_RELATION_FSYNC))
    1658           0 :             pg_usleep(10000L);  /* 10 msec seems a good number */
    1659             : 
    1660             :         /*
    1661             :          * Note we don't wait for the checkpointer to actually absorb the
    1662             :          * cancel message; see mdsync() for the implications.
    1663             :          */
    1664             :     }
    1665      126976 : }
    1666             : 
    1667             : /*
    1668             :  * ForgetDatabaseFsyncRequests -- forget any fsyncs and unlinks for a DB
    1669             :  */
    1670             : void
    1671          18 : ForgetDatabaseFsyncRequests(Oid dbid)
    1672             : {
    1673             :     RelFileNode rnode;
    1674             : 
    1675          18 :     rnode.dbNode = dbid;
    1676          18 :     rnode.spcNode = 0;
    1677          18 :     rnode.relNode = 0;
    1678             : 
    1679          18 :     if (pendingOpsTable)
    1680             :     {
    1681             :         /* standalone backend or startup process: fsync state is local */
    1682           0 :         RememberFsyncRequest(rnode, InvalidForkNumber, FORGET_DATABASE_FSYNC);
    1683             :     }
    1684          18 :     else if (IsUnderPostmaster)
    1685             :     {
    1686             :         /* see notes in ForgetRelationFsyncRequests */
    1687          36 :         while (!ForwardFsyncRequest(rnode, InvalidForkNumber,
    1688             :                                     FORGET_DATABASE_FSYNC))
    1689           0 :             pg_usleep(10000L);  /* 10 msec seems a good number */
    1690             :     }
    1691          18 : }
    1692             : 
    1693             : /*
    1694             :  * DropRelationFiles -- drop files of all given relations
    1695             :  */
    1696             : void
    1697          70 : DropRelationFiles(RelFileNode *delrels, int ndelrels, bool isRedo)
    1698             : {
    1699             :     SMgrRelation *srels;
    1700             :     int         i;
    1701             : 
    1702          70 :     srels = palloc(sizeof(SMgrRelation) * ndelrels);
    1703          86 :     for (i = 0; i < ndelrels; i++)
    1704             :     {
    1705          16 :         SMgrRelation srel = smgropen(delrels[i], InvalidBackendId);
    1706             : 
    1707          16 :         if (isRedo)
    1708             :         {
    1709             :             ForkNumber  fork;
    1710             : 
    1711          70 :             for (fork = 0; fork <= MAX_FORKNUM; fork++)
    1712          56 :                 XLogDropRelation(delrels[i], fork);
    1713             :         }
    1714          16 :         srels[i] = srel;
    1715             :     }
    1716             : 
    1717          70 :     smgrdounlinkall(srels, ndelrels, isRedo);
    1718             : 
    1719             :     /*
    1720             :      * Call smgrclose() in reverse order as when smgropen() is called.
    1721             :      * This trick enables remove_from_unowned_list() in smgrclose()
    1722             :      * to search the SMgrRelation from the unowned list,
    1723             :      * with O(1) performance.
    1724             :      */
    1725          86 :     for (i = ndelrels - 1; i >= 0; i--)
    1726          16 :         smgrclose(srels[i]);
    1727          70 :     pfree(srels);
    1728          70 : }
    1729             : 
    1730             : 
    1731             : /*
    1732             :  *  _fdvec_resize() -- Resize the fork's open segments array
    1733             :  */
    1734             : static void
    1735     1867678 : _fdvec_resize(SMgrRelation reln,
    1736             :               ForkNumber forknum,
    1737             :               int nseg)
    1738             : {
    1739     1867678 :     if (nseg == 0)
    1740             :     {
    1741      812596 :         if (reln->md_num_open_segs[forknum] > 0)
    1742             :         {
    1743      812596 :             pfree(reln->md_seg_fds[forknum]);
    1744      812596 :             reln->md_seg_fds[forknum] = NULL;
    1745             :         }
    1746             :     }
    1747     1055082 :     else if (reln->md_num_open_segs[forknum] == 0)
    1748             :     {
    1749     1055082 :         reln->md_seg_fds[forknum] =
    1750     1055082 :             MemoryContextAlloc(MdCxt, sizeof(MdfdVec) * nseg);
    1751             :     }
    1752             :     else
    1753             :     {
    1754             :         /*
    1755             :          * It doesn't seem worthwhile complicating the code by having a more
    1756             :          * aggressive growth strategy here; the number of segments doesn't
    1757             :          * grow that fast, and the memory context internally will sometimes
    1758             :          * avoid doing an actual reallocation.
    1759             :          */
    1760           0 :         reln->md_seg_fds[forknum] =
    1761           0 :             repalloc(reln->md_seg_fds[forknum],
    1762             :                      sizeof(MdfdVec) * nseg);
    1763             :     }
    1764             : 
    1765     1867678 :     reln->md_num_open_segs[forknum] = nseg;
    1766     1867678 : }
    1767             : 
    1768             : /*
    1769             :  * Return the filename for the specified segment of the relation. The
    1770             :  * returned string is palloc'd.
    1771             :  */
    1772             : static char *
    1773           0 : _mdfd_segpath(SMgrRelation reln, ForkNumber forknum, BlockNumber segno)
    1774             : {
    1775             :     char       *path,
    1776             :                *fullpath;
    1777             : 
    1778           0 :     path = relpath(reln->smgr_rnode, forknum);
    1779             : 
    1780           0 :     if (segno > 0)
    1781             :     {
    1782           0 :         fullpath = psprintf("%s.%u", path, segno);
    1783           0 :         pfree(path);
    1784             :     }
    1785             :     else
    1786           0 :         fullpath = path;
    1787             : 
    1788           0 :     return fullpath;
    1789             : }
    1790             : 
    1791             : /*
    1792             :  * Open the specified segment of the relation,
    1793             :  * and make a MdfdVec object for it.  Returns NULL on failure.
    1794             :  */
    1795             : static MdfdVec *
    1796           0 : _mdfd_openseg(SMgrRelation reln, ForkNumber forknum, BlockNumber segno,
    1797             :               int oflags)
    1798             : {
    1799             :     MdfdVec    *v;
    1800             :     int         fd;
    1801             :     char       *fullpath;
    1802             : 
    1803           0 :     fullpath = _mdfd_segpath(reln, forknum, segno);
    1804             : 
    1805             :     /* open the file */
    1806           0 :     fd = PathNameOpenFile(fullpath, O_RDWR | PG_BINARY | oflags);
    1807             : 
    1808           0 :     pfree(fullpath);
    1809             : 
    1810           0 :     if (fd < 0)
    1811           0 :         return NULL;
    1812             : 
    1813           0 :     if (segno <= reln->md_num_open_segs[forknum])
    1814           0 :         _fdvec_resize(reln, forknum, segno + 1);
    1815             : 
    1816             :     /* fill the entry */
    1817           0 :     v = &reln->md_seg_fds[forknum][segno];
    1818           0 :     v->mdfd_vfd = fd;
    1819           0 :     v->mdfd_segno = segno;
    1820             : 
    1821             :     Assert(_mdnblocks(reln, forknum, v) <= ((BlockNumber) RELSEG_SIZE));
    1822             : 
    1823             :     /* all done */
    1824           0 :     return v;
    1825             : }
    1826             : 
    1827             : /*
    1828             :  *  _mdfd_getseg() -- Find the segment of the relation holding the
    1829             :  *      specified block.
    1830             :  *
    1831             :  * If the segment doesn't exist, we ereport, return NULL, or create the
    1832             :  * segment, according to "behavior".  Note: skipFsync is only used in the
    1833             :  * EXTENSION_CREATE case.
    1834             :  */
    1835             : static MdfdVec *
    1836     1550614 : _mdfd_getseg(SMgrRelation reln, ForkNumber forknum, BlockNumber blkno,
    1837             :              bool skipFsync, int behavior)
    1838             : {
    1839             :     MdfdVec    *v;
    1840             :     BlockNumber targetseg;
    1841             :     BlockNumber nextsegno;
    1842             : 
    1843             :     /* some way to handle non-existent segments needs to be specified */
    1844             :     Assert(behavior &
    1845             :            (EXTENSION_FAIL | EXTENSION_CREATE | EXTENSION_RETURN_NULL));
    1846             : 
    1847     1550614 :     targetseg = blkno / ((BlockNumber) RELSEG_SIZE);
    1848             : 
    1849             :     /* if an existing and opened segment, we're done */
    1850     1550614 :     if (targetseg < reln->md_num_open_segs[forknum])
    1851             :     {
    1852     1414996 :         v = &reln->md_seg_fds[forknum][targetseg];
    1853     1414996 :         return v;
    1854             :     }
    1855             : 
    1856             :     /*
    1857             :      * The target segment is not yet open. Iterate over all the segments
    1858             :      * between the last opened and the target segment. This way missing
    1859             :      * segments either raise an error, or get created (according to
    1860             :      * 'behavior'). Start with either the last opened, or the first segment if
    1861             :      * none was opened before.
    1862             :      */
    1863      135618 :     if (reln->md_num_open_segs[forknum] > 0)
    1864           0 :         v = &reln->md_seg_fds[forknum][reln->md_num_open_segs[forknum] - 1];
    1865             :     else
    1866             :     {
    1867      135618 :         v = mdopen(reln, forknum, behavior);
    1868      135618 :         if (!v)
    1869           0 :             return NULL;        /* if behavior & EXTENSION_RETURN_NULL */
    1870             :     }
    1871             : 
    1872      271236 :     for (nextsegno = reln->md_num_open_segs[forknum];
    1873           0 :          nextsegno <= targetseg; nextsegno++)
    1874             :     {
    1875           0 :         BlockNumber nblocks = _mdnblocks(reln, forknum, v);
    1876           0 :         int         flags = 0;
    1877             : 
    1878             :         Assert(nextsegno == v->mdfd_segno + 1);
    1879             : 
    1880           0 :         if (nblocks > ((BlockNumber) RELSEG_SIZE))
    1881           0 :             elog(FATAL, "segment too big");
    1882             : 
    1883           0 :         if ((behavior & EXTENSION_CREATE) ||
    1884           0 :             (InRecovery && (behavior & EXTENSION_CREATE_RECOVERY)))
    1885             :         {
    1886             :             /*
    1887             :              * Normally we will create new segments only if authorized by the
    1888             :              * caller (i.e., we are doing mdextend()).  But when doing WAL
    1889             :              * recovery, create segments anyway; this allows cases such as
    1890             :              * replaying WAL data that has a write into a high-numbered
    1891             :              * segment of a relation that was later deleted. We want to go
    1892             :              * ahead and create the segments so we can finish out the replay.
    1893             :              * However if the caller has specified
    1894             :              * EXTENSION_REALLY_RETURN_NULL, then extension is not desired
    1895             :              * even in recovery; we won't reach this point in that case.
    1896             :              *
    1897             :              * We have to maintain the invariant that segments before the last
    1898             :              * active segment are of size RELSEG_SIZE; therefore, if
    1899             :              * extending, pad them out with zeroes if needed.  (This only
    1900             :              * matters if in recovery, or if the caller is extending the
    1901             :              * relation discontiguously, but that can happen in hash indexes.)
    1902             :              */
    1903           0 :             if (nblocks < ((BlockNumber) RELSEG_SIZE))
    1904             :             {
    1905           0 :                 char       *zerobuf = palloc0(BLCKSZ);
    1906             : 
    1907           0 :                 mdextend(reln, forknum,
    1908           0 :                          nextsegno * ((BlockNumber) RELSEG_SIZE) - 1,
    1909             :                          zerobuf, skipFsync);
    1910           0 :                 pfree(zerobuf);
    1911             :             }
    1912           0 :             flags = O_CREAT;
    1913             :         }
    1914           0 :         else if (!(behavior & EXTENSION_DONT_CHECK_SIZE) &&
    1915             :                  nblocks < ((BlockNumber) RELSEG_SIZE))
    1916             :         {
    1917             :             /*
    1918             :              * When not extending (or explicitly including truncated
    1919             :              * segments), only open the next segment if the current one is
    1920             :              * exactly RELSEG_SIZE.  If not (this branch), either return NULL
    1921             :              * or fail.
    1922             :              */
    1923           0 :             if (behavior & EXTENSION_RETURN_NULL)
    1924             :             {
    1925             :                 /*
    1926             :                  * Some callers discern between reasons for _mdfd_getseg()
    1927             :                  * returning NULL based on errno. As there's no failing
    1928             :                  * syscall involved in this case, explicitly set errno to
    1929             :                  * ENOENT, as that seems the closest interpretation.
    1930             :                  */
    1931           0 :                 errno = ENOENT;
    1932           0 :                 return NULL;
    1933             :             }
    1934             : 
    1935           0 :             ereport(ERROR,
    1936             :                     (errcode_for_file_access(),
    1937             :                      errmsg("could not open file \"%s\" (target block %u): previous segment is only %u blocks",
    1938             :                             _mdfd_segpath(reln, forknum, nextsegno),
    1939             :                             blkno, nblocks)));
    1940             :         }
    1941             : 
    1942           0 :         v = _mdfd_openseg(reln, forknum, nextsegno, flags);
    1943             : 
    1944           0 :         if (v == NULL)
    1945             :         {
    1946           0 :             if ((behavior & EXTENSION_RETURN_NULL) &&
    1947           0 :                 FILE_POSSIBLY_DELETED(errno))
    1948           0 :                 return NULL;
    1949           0 :             ereport(ERROR,
    1950             :                     (errcode_for_file_access(),
    1951             :                      errmsg("could not open file \"%s\" (target block %u): %m",
    1952             :                             _mdfd_segpath(reln, forknum, nextsegno),
    1953             :                             blkno)));
    1954             :         }
    1955             :     }
    1956             : 
    1957      135618 :     return v;
    1958             : }
    1959             : 
    1960             : /*
    1961             :  * Get number of blocks present in a single disk file
    1962             :  */
    1963             : static BlockNumber
    1964     3393996 : _mdnblocks(SMgrRelation reln, ForkNumber forknum, MdfdVec *seg)
    1965             : {
    1966             :     off_t       len;
    1967             : 
    1968     3393996 :     len = FileSize(seg->mdfd_vfd);
    1969     3393996 :     if (len < 0)
    1970           0 :         ereport(ERROR,
    1971             :                 (errcode_for_file_access(),
    1972             :                  errmsg("could not seek to end of file \"%s\": %m",
    1973             :                         FilePathName(seg->mdfd_vfd))));
    1974             :     /* note that this calculation will ignore any partial block at EOF */
    1975     3393996 :     return (BlockNumber) (len / BLCKSZ);
    1976             : }

Generated by: LCOV version 1.13