LCOV - code coverage report
Current view: top level - src/backend/storage/smgr - md.c (source / functions) Hit Total Coverage
Test: PostgreSQL 18devel Lines: 333 456 73.0 %
Date: 2024-12-12 15:15:20 Functions: 33 35 94.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-2024, 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 "access/xlogutils.h"
      29             : #include "commands/tablespace.h"
      30             : #include "common/file_utils.h"
      31             : #include "miscadmin.h"
      32             : #include "pg_trace.h"
      33             : #include "pgstat.h"
      34             : #include "storage/bufmgr.h"
      35             : #include "storage/fd.h"
      36             : #include "storage/md.h"
      37             : #include "storage/relfilelocator.h"
      38             : #include "storage/smgr.h"
      39             : #include "storage/sync.h"
      40             : #include "utils/memutils.h"
      41             : 
      42             : /*
      43             :  * The magnetic disk storage manager keeps track of open file
      44             :  * descriptors in its own descriptor pool.  This is done to make it
      45             :  * easier to support relations that are larger than the operating
      46             :  * system's file size limit (often 2GBytes).  In order to do that,
      47             :  * we break relations up into "segment" files that are each shorter than
      48             :  * the OS file size limit.  The segment size is set by the RELSEG_SIZE
      49             :  * configuration constant in pg_config.h.
      50             :  *
      51             :  * On disk, a relation must consist of consecutively numbered segment
      52             :  * files in the pattern
      53             :  *  -- Zero or more full segments of exactly RELSEG_SIZE blocks each
      54             :  *  -- Exactly one partial segment of size 0 <= size < RELSEG_SIZE blocks
      55             :  *  -- Optionally, any number of inactive segments of size 0 blocks.
      56             :  * The full and partial segments are collectively the "active" segments.
      57             :  * Inactive segments are those that once contained data but are currently
      58             :  * not needed because of an mdtruncate() operation.  The reason for leaving
      59             :  * them present at size zero, rather than unlinking them, is that other
      60             :  * backends and/or the checkpointer might be holding open file references to
      61             :  * such segments.  If the relation expands again after mdtruncate(), such
      62             :  * that a deactivated segment becomes active again, it is important that
      63             :  * such file references still be valid --- else data might get written
      64             :  * out to an unlinked old copy of a segment file that will eventually
      65             :  * disappear.
      66             :  *
      67             :  * File descriptors are stored in the per-fork md_seg_fds arrays inside
      68             :  * SMgrRelation. The length of these arrays is stored in md_num_open_segs.
      69             :  * Note that a fork's md_num_open_segs having a specific value does not
      70             :  * necessarily mean the relation doesn't have additional segments; we may
      71             :  * just not have opened the next segment yet.  (We could not have "all
      72             :  * segments are in the array" as an invariant anyway, since another backend
      73             :  * could extend the relation while we aren't looking.)  We do not have
      74             :  * entries for inactive segments, however; as soon as we find a partial
      75             :  * segment, we assume that any subsequent segments are inactive.
      76             :  *
      77             :  * The entire MdfdVec array is palloc'd in the MdCxt memory context.
      78             :  */
      79             : 
      80             : typedef struct _MdfdVec
      81             : {
      82             :     File        mdfd_vfd;       /* fd number in fd.c's pool */
      83             :     BlockNumber mdfd_segno;     /* segment number, from 0 */
      84             : } MdfdVec;
      85             : 
      86             : static MemoryContext MdCxt;     /* context for all MdfdVec objects */
      87             : 
      88             : 
      89             : /* Populate a file tag describing an md.c segment file. */
      90             : #define INIT_MD_FILETAG(a,xx_rlocator,xx_forknum,xx_segno) \
      91             : ( \
      92             :     memset(&(a), 0, sizeof(FileTag)), \
      93             :     (a).handler = SYNC_HANDLER_MD, \
      94             :     (a).rlocator = (xx_rlocator), \
      95             :     (a).forknum = (xx_forknum), \
      96             :     (a).segno = (xx_segno) \
      97             : )
      98             : 
      99             : 
     100             : /*** behavior for mdopen & _mdfd_getseg ***/
     101             : /* ereport if segment not present */
     102             : #define EXTENSION_FAIL              (1 << 0)
     103             : /* return NULL if segment not present */
     104             : #define EXTENSION_RETURN_NULL       (1 << 1)
     105             : /* create new segments as needed */
     106             : #define EXTENSION_CREATE            (1 << 2)
     107             : /* create new segments if needed during recovery */
     108             : #define EXTENSION_CREATE_RECOVERY   (1 << 3)
     109             : /*
     110             :  * Allow opening segments which are preceded by segments smaller than
     111             :  * RELSEG_SIZE, e.g. inactive segments (see above). Note that this breaks
     112             :  * mdnblocks() and related functionality henceforth - which currently is ok,
     113             :  * because this is only required in the checkpointer which never uses
     114             :  * mdnblocks().
     115             :  */
     116             : #define EXTENSION_DONT_CHECK_SIZE   (1 << 4)
     117             : /* don't try to open a segment, if not already open */
     118             : #define EXTENSION_DONT_OPEN         (1 << 5)
     119             : 
     120             : 
     121             : /* local routines */
     122             : static void mdunlinkfork(RelFileLocatorBackend rlocator, ForkNumber forknum,
     123             :                          bool isRedo);
     124             : static MdfdVec *mdopenfork(SMgrRelation reln, ForkNumber forknum, int behavior);
     125             : static void register_dirty_segment(SMgrRelation reln, ForkNumber forknum,
     126             :                                    MdfdVec *seg);
     127             : static void register_unlink_segment(RelFileLocatorBackend rlocator, ForkNumber forknum,
     128             :                                     BlockNumber segno);
     129             : static void register_forget_request(RelFileLocatorBackend rlocator, ForkNumber forknum,
     130             :                                     BlockNumber segno);
     131             : static void _fdvec_resize(SMgrRelation reln,
     132             :                           ForkNumber forknum,
     133             :                           int nseg);
     134             : static char *_mdfd_segpath(SMgrRelation reln, ForkNumber forknum,
     135             :                            BlockNumber segno);
     136             : static MdfdVec *_mdfd_openseg(SMgrRelation reln, ForkNumber forknum,
     137             :                               BlockNumber segno, int oflags);
     138             : static MdfdVec *_mdfd_getseg(SMgrRelation reln, ForkNumber forknum,
     139             :                              BlockNumber blkno, bool skipFsync, int behavior);
     140             : static BlockNumber _mdnblocks(SMgrRelation reln, ForkNumber forknum,
     141             :                               MdfdVec *seg);
     142             : 
     143             : static inline int
     144     2347038 : _mdfd_open_flags(void)
     145             : {
     146     2347038 :     int         flags = O_RDWR | PG_BINARY;
     147             : 
     148     2347038 :     if (io_direct_flags & IO_DIRECT_DATA)
     149         662 :         flags |= PG_O_DIRECT;
     150             : 
     151     2347038 :     return flags;
     152             : }
     153             : 
     154             : /*
     155             :  * mdinit() -- Initialize private state for magnetic disk storage manager.
     156             :  */
     157             : void
     158       36042 : mdinit(void)
     159             : {
     160       36042 :     MdCxt = AllocSetContextCreate(TopMemoryContext,
     161             :                                   "MdSmgr",
     162             :                                   ALLOCSET_DEFAULT_SIZES);
     163       36042 : }
     164             : 
     165             : /*
     166             :  * mdexists() -- Does the physical file exist?
     167             :  *
     168             :  * Note: this will return true for lingering files, with pending deletions
     169             :  */
     170             : bool
     171      998320 : mdexists(SMgrRelation reln, ForkNumber forknum)
     172             : {
     173             :     /*
     174             :      * Close it first, to ensure that we notice if the fork has been unlinked
     175             :      * since we opened it.  As an optimization, we can skip that in recovery,
     176             :      * which already closes relations when dropping them.
     177             :      */
     178      998320 :     if (!InRecovery)
     179      957512 :         mdclose(reln, forknum);
     180             : 
     181      998320 :     return (mdopenfork(reln, forknum, EXTENSION_RETURN_NULL) != NULL);
     182             : }
     183             : 
     184             : /*
     185             :  * mdcreate() -- Create a new relation on magnetic disk.
     186             :  *
     187             :  * If isRedo is true, it's okay for the relation to exist already.
     188             :  */
     189             : void
     190    10912520 : mdcreate(SMgrRelation reln, ForkNumber forknum, bool isRedo)
     191             : {
     192             :     MdfdVec    *mdfd;
     193             :     char       *path;
     194             :     File        fd;
     195             : 
     196    10912520 :     if (isRedo && reln->md_num_open_segs[forknum] > 0)
     197    10621086 :         return;                 /* created and opened already... */
     198             : 
     199             :     Assert(reln->md_num_open_segs[forknum] == 0);
     200             : 
     201             :     /*
     202             :      * We may be using the target table space for the first time in this
     203             :      * database, so create a per-database subdirectory if needed.
     204             :      *
     205             :      * XXX this is a fairly ugly violation of module layering, but this seems
     206             :      * to be the best place to put the check.  Maybe TablespaceCreateDbspace
     207             :      * should be here and not in commands/tablespace.c?  But that would imply
     208             :      * importing a lot of stuff that smgr.c oughtn't know, either.
     209             :      */
     210      291434 :     TablespaceCreateDbspace(reln->smgr_rlocator.locator.spcOid,
     211             :                             reln->smgr_rlocator.locator.dbOid,
     212             :                             isRedo);
     213             : 
     214      291434 :     path = relpath(reln->smgr_rlocator, forknum);
     215             : 
     216      291434 :     fd = PathNameOpenFile(path, _mdfd_open_flags() | O_CREAT | O_EXCL);
     217             : 
     218      291434 :     if (fd < 0)
     219             :     {
     220        8922 :         int         save_errno = errno;
     221             : 
     222        8922 :         if (isRedo)
     223        8922 :             fd = PathNameOpenFile(path, _mdfd_open_flags());
     224        8922 :         if (fd < 0)
     225             :         {
     226             :             /* be sure to report the error reported by create, not open */
     227           0 :             errno = save_errno;
     228           0 :             ereport(ERROR,
     229             :                     (errcode_for_file_access(),
     230             :                      errmsg("could not create file \"%s\": %m", path)));
     231             :         }
     232             :     }
     233             : 
     234      291434 :     pfree(path);
     235             : 
     236      291434 :     _fdvec_resize(reln, forknum, 1);
     237      291434 :     mdfd = &reln->md_seg_fds[forknum][0];
     238      291434 :     mdfd->mdfd_vfd = fd;
     239      291434 :     mdfd->mdfd_segno = 0;
     240             : 
     241      291434 :     if (!SmgrIsTemp(reln))
     242      285124 :         register_dirty_segment(reln, forknum, mdfd);
     243             : }
     244             : 
     245             : /*
     246             :  * mdunlink() -- Unlink a relation.
     247             :  *
     248             :  * Note that we're passed a RelFileLocatorBackend --- by the time this is called,
     249             :  * there won't be an SMgrRelation hashtable entry anymore.
     250             :  *
     251             :  * forknum can be a fork number to delete a specific fork, or InvalidForkNumber
     252             :  * to delete all forks.
     253             :  *
     254             :  * For regular relations, we don't unlink the first segment file of the rel,
     255             :  * but just truncate it to zero length, and record a request to unlink it after
     256             :  * the next checkpoint.  Additional segments can be unlinked immediately,
     257             :  * however.  Leaving the empty file in place prevents that relfilenumber
     258             :  * from being reused.  The scenario this protects us from is:
     259             :  * 1. We delete a relation (and commit, and actually remove its file).
     260             :  * 2. We create a new relation, which by chance gets the same relfilenumber as
     261             :  *    the just-deleted one (OIDs must've wrapped around for that to happen).
     262             :  * 3. We crash before another checkpoint occurs.
     263             :  * During replay, we would delete the file and then recreate it, which is fine
     264             :  * if the contents of the file were repopulated by subsequent WAL entries.
     265             :  * But if we didn't WAL-log insertions, but instead relied on fsyncing the
     266             :  * file after populating it (as we do at wal_level=minimal), the contents of
     267             :  * the file would be lost forever.  By leaving the empty file until after the
     268             :  * next checkpoint, we prevent reassignment of the relfilenumber until it's
     269             :  * safe, because relfilenumber assignment skips over any existing file.
     270             :  *
     271             :  * Additional segments, if any, are truncated and then unlinked.  The reason
     272             :  * for truncating is that other backends may still hold open FDs for these at
     273             :  * the smgr level, so that the kernel can't remove the file yet.  We want to
     274             :  * reclaim the disk space right away despite that.
     275             :  *
     276             :  * We do not need to go through this dance for temp relations, though, because
     277             :  * we never make WAL entries for temp rels, and so a temp rel poses no threat
     278             :  * to the health of a regular rel that has taken over its relfilenumber.
     279             :  * The fact that temp rels and regular rels have different file naming
     280             :  * patterns provides additional safety.  Other backends shouldn't have open
     281             :  * FDs for them, either.
     282             :  *
     283             :  * We also don't do it while performing a binary upgrade.  There is no reuse
     284             :  * hazard in that case, since after a crash or even a simple ERROR, the
     285             :  * upgrade fails and the whole cluster must be recreated from scratch.
     286             :  * Furthermore, it is important to remove the files from disk immediately,
     287             :  * because we may be about to reuse the same relfilenumber.
     288             :  *
     289             :  * All the above applies only to the relation's main fork; other forks can
     290             :  * just be removed immediately, since they are not needed to prevent the
     291             :  * relfilenumber from being recycled.  Also, we do not carefully
     292             :  * track whether other forks have been created or not, but just attempt to
     293             :  * unlink them unconditionally; so we should never complain about ENOENT.
     294             :  *
     295             :  * If isRedo is true, it's unsurprising for the relation to be already gone.
     296             :  * Also, we should remove the file immediately instead of queuing a request
     297             :  * for later, since during redo there's no possibility of creating a
     298             :  * conflicting relation.
     299             :  *
     300             :  * Note: we currently just never warn about ENOENT at all.  We could warn in
     301             :  * the main-fork, non-isRedo case, but it doesn't seem worth the trouble.
     302             :  *
     303             :  * Note: any failure should be reported as WARNING not ERROR, because
     304             :  * we are usually not in a transaction anymore when this is called.
     305             :  */
     306             : void
     307      349760 : mdunlink(RelFileLocatorBackend rlocator, ForkNumber forknum, bool isRedo)
     308             : {
     309             :     /* Now do the per-fork work */
     310      349760 :     if (forknum == InvalidForkNumber)
     311             :     {
     312           0 :         for (forknum = 0; forknum <= MAX_FORKNUM; forknum++)
     313           0 :             mdunlinkfork(rlocator, forknum, isRedo);
     314             :     }
     315             :     else
     316      349760 :         mdunlinkfork(rlocator, forknum, isRedo);
     317      349760 : }
     318             : 
     319             : /*
     320             :  * Truncate a file to release disk space.
     321             :  */
     322             : static int
     323      410578 : do_truncate(const char *path)
     324             : {
     325             :     int         save_errno;
     326             :     int         ret;
     327             : 
     328      410578 :     ret = pg_truncate(path, 0);
     329             : 
     330             :     /* Log a warning here to avoid repetition in callers. */
     331      410578 :     if (ret < 0 && errno != ENOENT)
     332             :     {
     333           0 :         save_errno = errno;
     334           0 :         ereport(WARNING,
     335             :                 (errcode_for_file_access(),
     336             :                  errmsg("could not truncate file \"%s\": %m", path)));
     337           0 :         errno = save_errno;
     338             :     }
     339             : 
     340      410578 :     return ret;
     341             : }
     342             : 
     343             : static void
     344      349760 : mdunlinkfork(RelFileLocatorBackend rlocator, ForkNumber forknum, bool isRedo)
     345             : {
     346             :     char       *path;
     347             :     int         ret;
     348             :     int         save_errno;
     349             : 
     350      349760 :     path = relpath(rlocator, forknum);
     351             : 
     352             :     /*
     353             :      * Truncate and then unlink the first segment, or just register a request
     354             :      * to unlink it later, as described in the comments for mdunlink().
     355             :      */
     356      349760 :     if (isRedo || IsBinaryUpgrade || forknum != MAIN_FORKNUM ||
     357       72936 :         RelFileLocatorBackendIsTemp(rlocator))
     358             :     {
     359      282846 :         if (!RelFileLocatorBackendIsTemp(rlocator))
     360             :         {
     361             :             /* Prevent other backends' fds from holding on to the disk space */
     362      258758 :             ret = do_truncate(path);
     363             : 
     364             :             /* Forget any pending sync requests for the first segment */
     365      258758 :             save_errno = errno;
     366      258758 :             register_forget_request(rlocator, forknum, 0 /* first seg */ );
     367      258758 :             errno = save_errno;
     368             :         }
     369             :         else
     370       24088 :             ret = 0;
     371             : 
     372             :         /* Next unlink the file, unless it was already found to be missing */
     373      282846 :         if (ret >= 0 || errno != ENOENT)
     374             :         {
     375       42088 :             ret = unlink(path);
     376       42088 :             if (ret < 0 && errno != ENOENT)
     377             :             {
     378           0 :                 save_errno = errno;
     379           0 :                 ereport(WARNING,
     380             :                         (errcode_for_file_access(),
     381             :                          errmsg("could not remove file \"%s\": %m", path)));
     382           0 :                 errno = save_errno;
     383             :             }
     384             :         }
     385             :     }
     386             :     else
     387             :     {
     388             :         /* Prevent other backends' fds from holding on to the disk space */
     389       66914 :         ret = do_truncate(path);
     390             : 
     391             :         /* Register request to unlink first segment later */
     392       66914 :         save_errno = errno;
     393       66914 :         register_unlink_segment(rlocator, forknum, 0 /* first seg */ );
     394       66914 :         errno = save_errno;
     395             :     }
     396             : 
     397             :     /*
     398             :      * Delete any additional segments.
     399             :      *
     400             :      * Note that because we loop until getting ENOENT, we will correctly
     401             :      * remove all inactive segments as well as active ones.  Ideally we'd
     402             :      * continue the loop until getting exactly that errno, but that risks an
     403             :      * infinite loop if the problem is directory-wide (for instance, if we
     404             :      * suddenly can't read the data directory itself).  We compromise by
     405             :      * continuing after a non-ENOENT truncate error, but stopping after any
     406             :      * unlink error.  If there is indeed a directory-wide problem, additional
     407             :      * unlink attempts wouldn't work anyway.
     408             :      */
     409      349760 :     if (ret >= 0 || errno != ENOENT)
     410             :     {
     411       91216 :         char       *segpath = (char *) palloc(strlen(path) + 12);
     412             :         BlockNumber segno;
     413             : 
     414       91216 :         for (segno = 1;; segno++)
     415             :         {
     416       91216 :             sprintf(segpath, "%s.%u", path, segno);
     417             : 
     418       91216 :             if (!RelFileLocatorBackendIsTemp(rlocator))
     419             :             {
     420             :                 /*
     421             :                  * Prevent other backends' fds from holding on to the disk
     422             :                  * space.  We're done if we see ENOENT, though.
     423             :                  */
     424       84906 :                 if (do_truncate(segpath) < 0 && errno == ENOENT)
     425       84906 :                     break;
     426             : 
     427             :                 /*
     428             :                  * Forget any pending sync requests for this segment before we
     429             :                  * try to unlink.
     430             :                  */
     431           0 :                 register_forget_request(rlocator, forknum, segno);
     432             :             }
     433             : 
     434        6310 :             if (unlink(segpath) < 0)
     435             :             {
     436             :                 /* ENOENT is expected after the last segment... */
     437        6310 :                 if (errno != ENOENT)
     438           0 :                     ereport(WARNING,
     439             :                             (errcode_for_file_access(),
     440             :                              errmsg("could not remove file \"%s\": %m", segpath)));
     441        6310 :                 break;
     442             :             }
     443             :         }
     444       91216 :         pfree(segpath);
     445             :     }
     446             : 
     447      349760 :     pfree(path);
     448      349760 : }
     449             : 
     450             : /*
     451             :  * mdextend() -- Add a block to the specified relation.
     452             :  *
     453             :  * The semantics are nearly the same as mdwrite(): write at the
     454             :  * specified position.  However, this is to be used for the case of
     455             :  * extending a relation (i.e., blocknum is at or beyond the current
     456             :  * EOF).  Note that we assume writing a block beyond current EOF
     457             :  * causes intervening file space to become filled with zeroes.
     458             :  */
     459             : void
     460      218522 : mdextend(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum,
     461             :          const void *buffer, bool skipFsync)
     462             : {
     463             :     off_t       seekpos;
     464             :     int         nbytes;
     465             :     MdfdVec    *v;
     466             : 
     467             :     /* If this build supports direct I/O, the buffer must be I/O aligned. */
     468             :     if (PG_O_DIRECT != 0 && PG_IO_ALIGN_SIZE <= BLCKSZ)
     469             :         Assert((uintptr_t) buffer == TYPEALIGN(PG_IO_ALIGN_SIZE, buffer));
     470             : 
     471             :     /* This assert is too expensive to have on normally ... */
     472             : #ifdef CHECK_WRITE_VS_EXTEND
     473             :     Assert(blocknum >= mdnblocks(reln, forknum));
     474             : #endif
     475             : 
     476             :     /*
     477             :      * If a relation manages to grow to 2^32-1 blocks, refuse to extend it any
     478             :      * more --- we mustn't create a block whose number actually is
     479             :      * InvalidBlockNumber.  (Note that this failure should be unreachable
     480             :      * because of upstream checks in bufmgr.c.)
     481             :      */
     482      218522 :     if (blocknum == InvalidBlockNumber)
     483           0 :         ereport(ERROR,
     484             :                 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
     485             :                  errmsg("cannot extend file \"%s\" beyond %u blocks",
     486             :                         relpath(reln->smgr_rlocator, forknum),
     487             :                         InvalidBlockNumber)));
     488             : 
     489      218522 :     v = _mdfd_getseg(reln, forknum, blocknum, skipFsync, EXTENSION_CREATE);
     490             : 
     491      218522 :     seekpos = (off_t) BLCKSZ * (blocknum % ((BlockNumber) RELSEG_SIZE));
     492             : 
     493             :     Assert(seekpos < (off_t) BLCKSZ * RELSEG_SIZE);
     494             : 
     495      218522 :     if ((nbytes = FileWrite(v->mdfd_vfd, buffer, BLCKSZ, seekpos, WAIT_EVENT_DATA_FILE_EXTEND)) != BLCKSZ)
     496             :     {
     497           0 :         if (nbytes < 0)
     498           0 :             ereport(ERROR,
     499             :                     (errcode_for_file_access(),
     500             :                      errmsg("could not extend file \"%s\": %m",
     501             :                             FilePathName(v->mdfd_vfd)),
     502             :                      errhint("Check free disk space.")));
     503             :         /* short write: complain appropriately */
     504           0 :         ereport(ERROR,
     505             :                 (errcode(ERRCODE_DISK_FULL),
     506             :                  errmsg("could not extend file \"%s\": wrote only %d of %d bytes at block %u",
     507             :                         FilePathName(v->mdfd_vfd),
     508             :                         nbytes, BLCKSZ, blocknum),
     509             :                  errhint("Check free disk space.")));
     510             :     }
     511             : 
     512      218522 :     if (!skipFsync && !SmgrIsTemp(reln))
     513          58 :         register_dirty_segment(reln, forknum, v);
     514             : 
     515             :     Assert(_mdnblocks(reln, forknum, v) <= ((BlockNumber) RELSEG_SIZE));
     516      218522 : }
     517             : 
     518             : /*
     519             :  * mdzeroextend() -- Add new zeroed out blocks to the specified relation.
     520             :  *
     521             :  * Similar to mdextend(), except the relation can be extended by multiple
     522             :  * blocks at once and the added blocks will be filled with zeroes.
     523             :  */
     524             : void
     525      390550 : mdzeroextend(SMgrRelation reln, ForkNumber forknum,
     526             :              BlockNumber blocknum, int nblocks, bool skipFsync)
     527             : {
     528             :     MdfdVec    *v;
     529      390550 :     BlockNumber curblocknum = blocknum;
     530      390550 :     int         remblocks = nblocks;
     531             : 
     532             :     Assert(nblocks > 0);
     533             : 
     534             :     /* This assert is too expensive to have on normally ... */
     535             : #ifdef CHECK_WRITE_VS_EXTEND
     536             :     Assert(blocknum >= mdnblocks(reln, forknum));
     537             : #endif
     538             : 
     539             :     /*
     540             :      * If a relation manages to grow to 2^32-1 blocks, refuse to extend it any
     541             :      * more --- we mustn't create a block whose number actually is
     542             :      * InvalidBlockNumber or larger.
     543             :      */
     544      390550 :     if ((uint64) blocknum + nblocks >= (uint64) InvalidBlockNumber)
     545           0 :         ereport(ERROR,
     546             :                 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
     547             :                  errmsg("cannot extend file \"%s\" beyond %u blocks",
     548             :                         relpath(reln->smgr_rlocator, forknum),
     549             :                         InvalidBlockNumber)));
     550             : 
     551      781100 :     while (remblocks > 0)
     552             :     {
     553      390550 :         BlockNumber segstartblock = curblocknum % ((BlockNumber) RELSEG_SIZE);
     554      390550 :         off_t       seekpos = (off_t) BLCKSZ * segstartblock;
     555             :         int         numblocks;
     556             : 
     557      390550 :         if (segstartblock + remblocks > RELSEG_SIZE)
     558           0 :             numblocks = RELSEG_SIZE - segstartblock;
     559             :         else
     560      390550 :             numblocks = remblocks;
     561             : 
     562      390550 :         v = _mdfd_getseg(reln, forknum, curblocknum, skipFsync, EXTENSION_CREATE);
     563             : 
     564             :         Assert(segstartblock < RELSEG_SIZE);
     565             :         Assert(segstartblock + numblocks <= RELSEG_SIZE);
     566             : 
     567             :         /*
     568             :          * If available and useful, use posix_fallocate() (via
     569             :          * FileFallocate()) to extend the relation. That's often more
     570             :          * efficient than using write(), as it commonly won't cause the kernel
     571             :          * to allocate page cache space for the extended pages.
     572             :          *
     573             :          * However, we don't use FileFallocate() for small extensions, as it
     574             :          * defeats delayed allocation on some filesystems. Not clear where
     575             :          * that decision should be made though? For now just use a cutoff of
     576             :          * 8, anything between 4 and 8 worked OK in some local testing.
     577             :          */
     578      390550 :         if (numblocks > 8)
     579             :         {
     580             :             int         ret;
     581             : 
     582         992 :             ret = FileFallocate(v->mdfd_vfd,
     583             :                                 seekpos, (off_t) BLCKSZ * numblocks,
     584             :                                 WAIT_EVENT_DATA_FILE_EXTEND);
     585         992 :             if (ret != 0)
     586             :             {
     587           0 :                 ereport(ERROR,
     588             :                         errcode_for_file_access(),
     589             :                         errmsg("could not extend file \"%s\" with FileFallocate(): %m",
     590             :                                FilePathName(v->mdfd_vfd)),
     591             :                         errhint("Check free disk space."));
     592             :             }
     593             :         }
     594             :         else
     595             :         {
     596             :             int         ret;
     597             : 
     598             :             /*
     599             :              * Even if we don't want to use fallocate, we can still extend a
     600             :              * bit more efficiently than writing each 8kB block individually.
     601             :              * pg_pwrite_zeros() (via FileZero()) uses pg_pwritev_with_retry()
     602             :              * to avoid multiple writes or needing a zeroed buffer for the
     603             :              * whole length of the extension.
     604             :              */
     605      389558 :             ret = FileZero(v->mdfd_vfd,
     606             :                            seekpos, (off_t) BLCKSZ * numblocks,
     607             :                            WAIT_EVENT_DATA_FILE_EXTEND);
     608      389558 :             if (ret < 0)
     609           0 :                 ereport(ERROR,
     610             :                         errcode_for_file_access(),
     611             :                         errmsg("could not extend file \"%s\": %m",
     612             :                                FilePathName(v->mdfd_vfd)),
     613             :                         errhint("Check free disk space."));
     614             :         }
     615             : 
     616      390550 :         if (!skipFsync && !SmgrIsTemp(reln))
     617      372868 :             register_dirty_segment(reln, forknum, v);
     618             : 
     619             :         Assert(_mdnblocks(reln, forknum, v) <= ((BlockNumber) RELSEG_SIZE));
     620             : 
     621      390550 :         remblocks -= numblocks;
     622      390550 :         curblocknum += numblocks;
     623             :     }
     624      390550 : }
     625             : 
     626             : /*
     627             :  * mdopenfork() -- Open one fork of the specified relation.
     628             :  *
     629             :  * Note we only open the first segment, when there are multiple segments.
     630             :  *
     631             :  * If first segment is not present, either ereport or return NULL according
     632             :  * to "behavior".  We treat EXTENSION_CREATE the same as EXTENSION_FAIL;
     633             :  * EXTENSION_CREATE means it's OK to extend an existing relation, not to
     634             :  * invent one out of whole cloth.
     635             :  */
     636             : static MdfdVec *
     637     5277382 : mdopenfork(SMgrRelation reln, ForkNumber forknum, int behavior)
     638             : {
     639             :     MdfdVec    *mdfd;
     640             :     char       *path;
     641             :     File        fd;
     642             : 
     643             :     /* No work if already open */
     644     5277382 :     if (reln->md_num_open_segs[forknum] > 0)
     645     3277002 :         return &reln->md_seg_fds[forknum][0];
     646             : 
     647     2000380 :     path = relpath(reln->smgr_rlocator, forknum);
     648             : 
     649     2000380 :     fd = PathNameOpenFile(path, _mdfd_open_flags());
     650             : 
     651     2000380 :     if (fd < 0)
     652             :     {
     653      678684 :         if ((behavior & EXTENSION_RETURN_NULL) &&
     654      678640 :             FILE_POSSIBLY_DELETED(errno))
     655             :         {
     656      678640 :             pfree(path);
     657      678640 :             return NULL;
     658             :         }
     659          44 :         ereport(ERROR,
     660             :                 (errcode_for_file_access(),
     661             :                  errmsg("could not open file \"%s\": %m", path)));
     662             :     }
     663             : 
     664     1321696 :     pfree(path);
     665             : 
     666     1321696 :     _fdvec_resize(reln, forknum, 1);
     667     1321696 :     mdfd = &reln->md_seg_fds[forknum][0];
     668     1321696 :     mdfd->mdfd_vfd = fd;
     669     1321696 :     mdfd->mdfd_segno = 0;
     670             : 
     671             :     Assert(_mdnblocks(reln, forknum, mdfd) <= ((BlockNumber) RELSEG_SIZE));
     672             : 
     673     1321696 :     return mdfd;
     674             : }
     675             : 
     676             : /*
     677             :  * mdopen() -- Initialize newly-opened relation.
     678             :  */
     679             : void
     680     1953264 : mdopen(SMgrRelation reln)
     681             : {
     682             :     /* mark it not open */
     683     9766320 :     for (int forknum = 0; forknum <= MAX_FORKNUM; forknum++)
     684     7813056 :         reln->md_num_open_segs[forknum] = 0;
     685     1953264 : }
     686             : 
     687             : /*
     688             :  * mdclose() -- Close the specified relation, if it isn't closed already.
     689             :  */
     690             : void
     691     6580472 : mdclose(SMgrRelation reln, ForkNumber forknum)
     692             : {
     693     6580472 :     int         nopensegs = reln->md_num_open_segs[forknum];
     694             : 
     695             :     /* No work if already closed */
     696     6580472 :     if (nopensegs == 0)
     697     5613034 :         return;
     698             : 
     699             :     /* close segments starting from the end */
     700     1934876 :     while (nopensegs > 0)
     701             :     {
     702      967438 :         MdfdVec    *v = &reln->md_seg_fds[forknum][nopensegs - 1];
     703             : 
     704      967438 :         FileClose(v->mdfd_vfd);
     705      967438 :         _fdvec_resize(reln, forknum, nopensegs - 1);
     706      967438 :         nopensegs--;
     707             :     }
     708             : }
     709             : 
     710             : /*
     711             :  * mdprefetch() -- Initiate asynchronous read of the specified blocks of a relation
     712             :  */
     713             : bool
     714      173628 : mdprefetch(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum,
     715             :            int nblocks)
     716             : {
     717             : #ifdef USE_PREFETCH
     718             : 
     719             :     Assert((io_direct_flags & IO_DIRECT_DATA) == 0);
     720             : 
     721      173628 :     if ((uint64) blocknum + nblocks > (uint64) MaxBlockNumber + 1)
     722           0 :         return false;
     723             : 
     724      347256 :     while (nblocks > 0)
     725             :     {
     726             :         off_t       seekpos;
     727             :         MdfdVec    *v;
     728             :         int         nblocks_this_segment;
     729             : 
     730      173628 :         v = _mdfd_getseg(reln, forknum, blocknum, false,
     731      173628 :                          InRecovery ? EXTENSION_RETURN_NULL : EXTENSION_FAIL);
     732      173628 :         if (v == NULL)
     733           0 :             return false;
     734             : 
     735      173628 :         seekpos = (off_t) BLCKSZ * (blocknum % ((BlockNumber) RELSEG_SIZE));
     736             : 
     737             :         Assert(seekpos < (off_t) BLCKSZ * RELSEG_SIZE);
     738             : 
     739      173628 :         nblocks_this_segment =
     740      173628 :             Min(nblocks,
     741             :                 RELSEG_SIZE - (blocknum % ((BlockNumber) RELSEG_SIZE)));
     742             : 
     743      173628 :         (void) FilePrefetch(v->mdfd_vfd, seekpos, BLCKSZ * nblocks_this_segment,
     744             :                             WAIT_EVENT_DATA_FILE_PREFETCH);
     745             : 
     746      173628 :         blocknum += nblocks_this_segment;
     747      173628 :         nblocks -= nblocks_this_segment;
     748             :     }
     749             : #endif                          /* USE_PREFETCH */
     750             : 
     751      173628 :     return true;
     752             : }
     753             : 
     754             : /*
     755             :  * Convert an array of buffer address into an array of iovec objects, and
     756             :  * return the number that were required.  'iov' must have enough space for up
     757             :  * to 'nblocks' elements, but the number used may be less depending on
     758             :  * merging.  In the case of a run of fully contiguous buffers, a single iovec
     759             :  * will be populated that can be handled as a plain non-vectored I/O.
     760             :  */
     761             : static int
     762     3211448 : buffers_to_iovec(struct iovec *iov, void **buffers, int nblocks)
     763             : {
     764             :     struct iovec *iovp;
     765             :     int         iovcnt;
     766             : 
     767             :     Assert(nblocks >= 1);
     768             : 
     769             :     /* If this build supports direct I/O, buffers must be I/O aligned. */
     770     6662086 :     for (int i = 0; i < nblocks; ++i)
     771             :     {
     772             :         if (PG_O_DIRECT != 0 && PG_IO_ALIGN_SIZE <= BLCKSZ)
     773             :             Assert((uintptr_t) buffers[i] ==
     774             :                    TYPEALIGN(PG_IO_ALIGN_SIZE, buffers[i]));
     775             :     }
     776             : 
     777             :     /* Start the first iovec off with the first buffer. */
     778     3211448 :     iovp = &iov[0];
     779     3211448 :     iovp->iov_base = buffers[0];
     780     3211448 :     iovp->iov_len = BLCKSZ;
     781     3211448 :     iovcnt = 1;
     782             : 
     783             :     /* Try to merge the rest. */
     784     3450638 :     for (int i = 1; i < nblocks; ++i)
     785             :     {
     786      239190 :         void       *buffer = buffers[i];
     787             : 
     788      239190 :         if (((char *) iovp->iov_base + iovp->iov_len) == buffer)
     789             :         {
     790             :             /* Contiguous with the last iovec. */
     791      232894 :             iovp->iov_len += BLCKSZ;
     792             :         }
     793             :         else
     794             :         {
     795             :             /* Need a new iovec. */
     796        6296 :             iovp++;
     797        6296 :             iovp->iov_base = buffer;
     798        6296 :             iovp->iov_len = BLCKSZ;
     799        6296 :             iovcnt++;
     800             :         }
     801             :     }
     802             : 
     803     3211448 :     return iovcnt;
     804             : }
     805             : 
     806             : /*
     807             :  * mdmaxcombine() -- Return the maximum number of total blocks that can be
     808             :  *               combined with an IO starting at blocknum.
     809             :  */
     810             : uint32
     811       51684 : mdmaxcombine(SMgrRelation reln, ForkNumber forknum,
     812             :              BlockNumber blocknum)
     813             : {
     814             :     BlockNumber segoff;
     815             : 
     816       51684 :     segoff = blocknum % ((BlockNumber) RELSEG_SIZE);
     817             : 
     818       51684 :     return RELSEG_SIZE - segoff;
     819             : }
     820             : 
     821             : /*
     822             :  * mdreadv() -- Read the specified blocks from a relation.
     823             :  */
     824             : void
     825     2256630 : mdreadv(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum,
     826             :         void **buffers, BlockNumber nblocks)
     827             : {
     828     4513230 :     while (nblocks > 0)
     829             :     {
     830             :         struct iovec iov[PG_IOV_MAX];
     831             :         int         iovcnt;
     832             :         off_t       seekpos;
     833             :         int         nbytes;
     834             :         MdfdVec    *v;
     835             :         BlockNumber nblocks_this_segment;
     836             :         size_t      transferred_this_segment;
     837             :         size_t      size_this_segment;
     838             : 
     839     2256630 :         v = _mdfd_getseg(reln, forknum, blocknum, false,
     840             :                          EXTENSION_FAIL | EXTENSION_CREATE_RECOVERY);
     841             : 
     842     2256600 :         seekpos = (off_t) BLCKSZ * (blocknum % ((BlockNumber) RELSEG_SIZE));
     843             : 
     844             :         Assert(seekpos < (off_t) BLCKSZ * RELSEG_SIZE);
     845             : 
     846     2256600 :         nblocks_this_segment =
     847     2256600 :             Min(nblocks,
     848             :                 RELSEG_SIZE - (blocknum % ((BlockNumber) RELSEG_SIZE)));
     849     2256600 :         nblocks_this_segment = Min(nblocks_this_segment, lengthof(iov));
     850             : 
     851     2256600 :         if (nblocks_this_segment != nblocks)
     852           0 :             elog(ERROR, "read crosses segment boundary");
     853             : 
     854     2256600 :         iovcnt = buffers_to_iovec(iov, buffers, nblocks_this_segment);
     855     2256600 :         size_this_segment = nblocks_this_segment * BLCKSZ;
     856     2256600 :         transferred_this_segment = 0;
     857             : 
     858             :         /*
     859             :          * Inner loop to continue after a short read.  We'll keep going until
     860             :          * we hit EOF rather than assuming that a short read means we hit the
     861             :          * end.
     862             :          */
     863             :         for (;;)
     864             :         {
     865             :             TRACE_POSTGRESQL_SMGR_MD_READ_START(forknum, blocknum,
     866             :                                                 reln->smgr_rlocator.locator.spcOid,
     867             :                                                 reln->smgr_rlocator.locator.dbOid,
     868             :                                                 reln->smgr_rlocator.locator.relNumber,
     869             :                                                 reln->smgr_rlocator.backend);
     870     2256600 :             nbytes = FileReadV(v->mdfd_vfd, iov, iovcnt, seekpos,
     871             :                                WAIT_EVENT_DATA_FILE_READ);
     872             :             TRACE_POSTGRESQL_SMGR_MD_READ_DONE(forknum, blocknum,
     873             :                                                reln->smgr_rlocator.locator.spcOid,
     874             :                                                reln->smgr_rlocator.locator.dbOid,
     875             :                                                reln->smgr_rlocator.locator.relNumber,
     876             :                                                reln->smgr_rlocator.backend,
     877             :                                                nbytes,
     878             :                                                size_this_segment - transferred_this_segment);
     879             : 
     880             : #ifdef SIMULATE_SHORT_READ
     881             :             nbytes = Min(nbytes, 4096);
     882             : #endif
     883             : 
     884     2256600 :             if (nbytes < 0)
     885           0 :                 ereport(ERROR,
     886             :                         (errcode_for_file_access(),
     887             :                          errmsg("could not read blocks %u..%u in file \"%s\": %m",
     888             :                                 blocknum,
     889             :                                 blocknum + nblocks_this_segment - 1,
     890             :                                 FilePathName(v->mdfd_vfd))));
     891             : 
     892     2256600 :             if (nbytes == 0)
     893             :             {
     894             :                 /*
     895             :                  * We are at or past EOF, or we read a partial block at EOF.
     896             :                  * Normally this is an error; upper levels should never try to
     897             :                  * read a nonexistent block.  However, if zero_damaged_pages
     898             :                  * is ON or we are InRecovery, we should instead return zeroes
     899             :                  * without complaining.  This allows, for example, the case of
     900             :                  * trying to update a block that was later truncated away.
     901             :                  */
     902           0 :                 if (zero_damaged_pages || InRecovery)
     903             :                 {
     904           0 :                     for (BlockNumber i = transferred_this_segment / BLCKSZ;
     905             :                          i < nblocks_this_segment;
     906           0 :                          ++i)
     907           0 :                         memset(buffers[i], 0, BLCKSZ);
     908           0 :                     break;
     909             :                 }
     910             :                 else
     911           0 :                     ereport(ERROR,
     912             :                             (errcode(ERRCODE_DATA_CORRUPTED),
     913             :                              errmsg("could not read blocks %u..%u in file \"%s\": read only %zu of %zu bytes",
     914             :                                     blocknum,
     915             :                                     blocknum + nblocks_this_segment - 1,
     916             :                                     FilePathName(v->mdfd_vfd),
     917             :                                     transferred_this_segment,
     918             :                                     size_this_segment)));
     919             :             }
     920             : 
     921             :             /* One loop should usually be enough. */
     922     2256600 :             transferred_this_segment += nbytes;
     923             :             Assert(transferred_this_segment <= size_this_segment);
     924     2256600 :             if (transferred_this_segment == size_this_segment)
     925     2256600 :                 break;
     926             : 
     927             :             /* Adjust position and vectors after a short read. */
     928           0 :             seekpos += nbytes;
     929           0 :             iovcnt = compute_remaining_iovec(iov, iov, iovcnt, nbytes);
     930             :         }
     931             : 
     932     2256600 :         nblocks -= nblocks_this_segment;
     933     2256600 :         buffers += nblocks_this_segment;
     934     2256600 :         blocknum += nblocks_this_segment;
     935             :     }
     936     2256600 : }
     937             : 
     938             : /*
     939             :  * mdwritev() -- Write the supplied blocks at the appropriate location.
     940             :  *
     941             :  * This is to be used only for updating already-existing blocks of a
     942             :  * relation (ie, those before the current EOF).  To extend a relation,
     943             :  * use mdextend().
     944             :  */
     945             : void
     946      954848 : mdwritev(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum,
     947             :          const void **buffers, BlockNumber nblocks, bool skipFsync)
     948             : {
     949             :     /* This assert is too expensive to have on normally ... */
     950             : #ifdef CHECK_WRITE_VS_EXTEND
     951             :     Assert((uint64) blocknum + (uint64) nblocks <= (uint64) mdnblocks(reln, forknum));
     952             : #endif
     953             : 
     954     1909696 :     while (nblocks > 0)
     955             :     {
     956             :         struct iovec iov[PG_IOV_MAX];
     957             :         int         iovcnt;
     958             :         off_t       seekpos;
     959             :         int         nbytes;
     960             :         MdfdVec    *v;
     961             :         BlockNumber nblocks_this_segment;
     962             :         size_t      transferred_this_segment;
     963             :         size_t      size_this_segment;
     964             : 
     965      954848 :         v = _mdfd_getseg(reln, forknum, blocknum, skipFsync,
     966             :                          EXTENSION_FAIL | EXTENSION_CREATE_RECOVERY);
     967             : 
     968      954848 :         seekpos = (off_t) BLCKSZ * (blocknum % ((BlockNumber) RELSEG_SIZE));
     969             : 
     970             :         Assert(seekpos < (off_t) BLCKSZ * RELSEG_SIZE);
     971             : 
     972      954848 :         nblocks_this_segment =
     973      954848 :             Min(nblocks,
     974             :                 RELSEG_SIZE - (blocknum % ((BlockNumber) RELSEG_SIZE)));
     975      954848 :         nblocks_this_segment = Min(nblocks_this_segment, lengthof(iov));
     976             : 
     977      954848 :         if (nblocks_this_segment != nblocks)
     978           0 :             elog(ERROR, "write crosses segment boundary");
     979             : 
     980      954848 :         iovcnt = buffers_to_iovec(iov, (void **) buffers, nblocks_this_segment);
     981      954848 :         size_this_segment = nblocks_this_segment * BLCKSZ;
     982      954848 :         transferred_this_segment = 0;
     983             : 
     984             :         /*
     985             :          * Inner loop to continue after a short write.  If the reason is that
     986             :          * we're out of disk space, a future attempt should get an ENOSPC
     987             :          * error from the kernel.
     988             :          */
     989             :         for (;;)
     990             :         {
     991             :             TRACE_POSTGRESQL_SMGR_MD_WRITE_START(forknum, blocknum,
     992             :                                                  reln->smgr_rlocator.locator.spcOid,
     993             :                                                  reln->smgr_rlocator.locator.dbOid,
     994             :                                                  reln->smgr_rlocator.locator.relNumber,
     995             :                                                  reln->smgr_rlocator.backend);
     996      954848 :             nbytes = FileWriteV(v->mdfd_vfd, iov, iovcnt, seekpos,
     997             :                                 WAIT_EVENT_DATA_FILE_WRITE);
     998             :             TRACE_POSTGRESQL_SMGR_MD_WRITE_DONE(forknum, blocknum,
     999             :                                                 reln->smgr_rlocator.locator.spcOid,
    1000             :                                                 reln->smgr_rlocator.locator.dbOid,
    1001             :                                                 reln->smgr_rlocator.locator.relNumber,
    1002             :                                                 reln->smgr_rlocator.backend,
    1003             :                                                 nbytes,
    1004             :                                                 size_this_segment - transferred_this_segment);
    1005             : 
    1006             : #ifdef SIMULATE_SHORT_WRITE
    1007             :             nbytes = Min(nbytes, 4096);
    1008             : #endif
    1009             : 
    1010      954848 :             if (nbytes < 0)
    1011             :             {
    1012           0 :                 bool        enospc = errno == ENOSPC;
    1013             : 
    1014           0 :                 ereport(ERROR,
    1015             :                         (errcode_for_file_access(),
    1016             :                          errmsg("could not write blocks %u..%u in file \"%s\": %m",
    1017             :                                 blocknum,
    1018             :                                 blocknum + nblocks_this_segment - 1,
    1019             :                                 FilePathName(v->mdfd_vfd)),
    1020             :                          enospc ? errhint("Check free disk space.") : 0));
    1021             :             }
    1022             : 
    1023             :             /* One loop should usually be enough. */
    1024      954848 :             transferred_this_segment += nbytes;
    1025             :             Assert(transferred_this_segment <= size_this_segment);
    1026      954848 :             if (transferred_this_segment == size_this_segment)
    1027      954848 :                 break;
    1028             : 
    1029             :             /* Adjust position and iovecs after a short write. */
    1030           0 :             seekpos += nbytes;
    1031           0 :             iovcnt = compute_remaining_iovec(iov, iov, iovcnt, nbytes);
    1032             :         }
    1033             : 
    1034      954848 :         if (!skipFsync && !SmgrIsTemp(reln))
    1035      952822 :             register_dirty_segment(reln, forknum, v);
    1036             : 
    1037      954848 :         nblocks -= nblocks_this_segment;
    1038      954848 :         buffers += nblocks_this_segment;
    1039      954848 :         blocknum += nblocks_this_segment;
    1040             :     }
    1041      954848 : }
    1042             : 
    1043             : 
    1044             : /*
    1045             :  * mdwriteback() -- Tell the kernel to write pages back to storage.
    1046             :  *
    1047             :  * This accepts a range of blocks because flushing several pages at once is
    1048             :  * considerably more efficient than doing so individually.
    1049             :  */
    1050             : void
    1051           0 : mdwriteback(SMgrRelation reln, ForkNumber forknum,
    1052             :             BlockNumber blocknum, BlockNumber nblocks)
    1053             : {
    1054             :     Assert((io_direct_flags & IO_DIRECT_DATA) == 0);
    1055             : 
    1056             :     /*
    1057             :      * Issue flush requests in as few requests as possible; have to split at
    1058             :      * segment boundaries though, since those are actually separate files.
    1059             :      */
    1060           0 :     while (nblocks > 0)
    1061             :     {
    1062           0 :         BlockNumber nflush = nblocks;
    1063             :         off_t       seekpos;
    1064             :         MdfdVec    *v;
    1065             :         int         segnum_start,
    1066             :                     segnum_end;
    1067             : 
    1068           0 :         v = _mdfd_getseg(reln, forknum, blocknum, true /* not used */ ,
    1069             :                          EXTENSION_DONT_OPEN);
    1070             : 
    1071             :         /*
    1072             :          * We might be flushing buffers of already removed relations, that's
    1073             :          * ok, just ignore that case.  If the segment file wasn't open already
    1074             :          * (ie from a recent mdwrite()), then we don't want to re-open it, to
    1075             :          * avoid a race with PROCSIGNAL_BARRIER_SMGRRELEASE that might leave
    1076             :          * us with a descriptor to a file that is about to be unlinked.
    1077             :          */
    1078           0 :         if (!v)
    1079           0 :             return;
    1080             : 
    1081             :         /* compute offset inside the current segment */
    1082           0 :         segnum_start = blocknum / RELSEG_SIZE;
    1083             : 
    1084             :         /* compute number of desired writes within the current segment */
    1085           0 :         segnum_end = (blocknum + nblocks - 1) / RELSEG_SIZE;
    1086           0 :         if (segnum_start != segnum_end)
    1087           0 :             nflush = RELSEG_SIZE - (blocknum % ((BlockNumber) RELSEG_SIZE));
    1088             : 
    1089             :         Assert(nflush >= 1);
    1090             :         Assert(nflush <= nblocks);
    1091             : 
    1092           0 :         seekpos = (off_t) BLCKSZ * (blocknum % ((BlockNumber) RELSEG_SIZE));
    1093             : 
    1094           0 :         FileWriteback(v->mdfd_vfd, seekpos, (off_t) BLCKSZ * nflush, WAIT_EVENT_DATA_FILE_FLUSH);
    1095             : 
    1096           0 :         nblocks -= nflush;
    1097           0 :         blocknum += nflush;
    1098             :     }
    1099             : }
    1100             : 
    1101             : /*
    1102             :  * mdnblocks() -- Get the number of blocks stored in a relation.
    1103             :  *
    1104             :  * Important side effect: all active segments of the relation are opened
    1105             :  * and added to the md_seg_fds array.  If this routine has not been
    1106             :  * called, then only segments up to the last one actually touched
    1107             :  * are present in the array.
    1108             :  */
    1109             : BlockNumber
    1110     3897178 : mdnblocks(SMgrRelation reln, ForkNumber forknum)
    1111             : {
    1112             :     MdfdVec    *v;
    1113             :     BlockNumber nblocks;
    1114             :     BlockNumber segno;
    1115             : 
    1116     3897178 :     mdopenfork(reln, forknum, EXTENSION_FAIL);
    1117             : 
    1118             :     /* mdopen has opened the first segment */
    1119             :     Assert(reln->md_num_open_segs[forknum] > 0);
    1120             : 
    1121             :     /*
    1122             :      * Start from the last open segments, to avoid redundant seeks.  We have
    1123             :      * previously verified that these segments are exactly RELSEG_SIZE long,
    1124             :      * and it's useless to recheck that each time.
    1125             :      *
    1126             :      * NOTE: this assumption could only be wrong if another backend has
    1127             :      * truncated the relation.  We rely on higher code levels to handle that
    1128             :      * scenario by closing and re-opening the md fd, which is handled via
    1129             :      * relcache flush.  (Since the checkpointer doesn't participate in
    1130             :      * relcache flush, it could have segment entries for inactive segments;
    1131             :      * that's OK because the checkpointer never needs to compute relation
    1132             :      * size.)
    1133             :      */
    1134     3897140 :     segno = reln->md_num_open_segs[forknum] - 1;
    1135     3897140 :     v = &reln->md_seg_fds[forknum][segno];
    1136             : 
    1137             :     for (;;)
    1138             :     {
    1139     3897140 :         nblocks = _mdnblocks(reln, forknum, v);
    1140     3897140 :         if (nblocks > ((BlockNumber) RELSEG_SIZE))
    1141           0 :             elog(FATAL, "segment too big");
    1142     3897140 :         if (nblocks < ((BlockNumber) RELSEG_SIZE))
    1143     3897140 :             return (segno * ((BlockNumber) RELSEG_SIZE)) + nblocks;
    1144             : 
    1145             :         /*
    1146             :          * If segment is exactly RELSEG_SIZE, advance to next one.
    1147             :          */
    1148           0 :         segno++;
    1149             : 
    1150             :         /*
    1151             :          * We used to pass O_CREAT here, but that has the disadvantage that it
    1152             :          * might create a segment which has vanished through some operating
    1153             :          * system misadventure.  In such a case, creating the segment here
    1154             :          * undermines _mdfd_getseg's attempts to notice and report an error
    1155             :          * upon access to a missing segment.
    1156             :          */
    1157           0 :         v = _mdfd_openseg(reln, forknum, segno, 0);
    1158           0 :         if (v == NULL)
    1159           0 :             return segno * ((BlockNumber) RELSEG_SIZE);
    1160             :     }
    1161             : }
    1162             : 
    1163             : /*
    1164             :  * mdtruncate() -- Truncate relation to specified number of blocks.
    1165             :  */
    1166             : void
    1167        1690 : mdtruncate(SMgrRelation reln, ForkNumber forknum, BlockNumber nblocks)
    1168             : {
    1169             :     BlockNumber curnblk;
    1170             :     BlockNumber priorblocks;
    1171             :     int         curopensegs;
    1172             : 
    1173             :     /*
    1174             :      * NOTE: mdnblocks makes sure we have opened all active segments, so that
    1175             :      * truncation loop will get them all!
    1176             :      */
    1177        1690 :     curnblk = mdnblocks(reln, forknum);
    1178        1690 :     if (nblocks > curnblk)
    1179             :     {
    1180             :         /* Bogus request ... but no complaint if InRecovery */
    1181           0 :         if (InRecovery)
    1182           0 :             return;
    1183           0 :         ereport(ERROR,
    1184             :                 (errmsg("could not truncate file \"%s\" to %u blocks: it's only %u blocks now",
    1185             :                         relpath(reln->smgr_rlocator, forknum),
    1186             :                         nblocks, curnblk)));
    1187             :     }
    1188        1690 :     if (nblocks == curnblk)
    1189         670 :         return;                 /* no work */
    1190             : 
    1191             :     /*
    1192             :      * Truncate segments, starting at the last one. Starting at the end makes
    1193             :      * managing the memory for the fd array easier, should there be errors.
    1194             :      */
    1195        1020 :     curopensegs = reln->md_num_open_segs[forknum];
    1196        2040 :     while (curopensegs > 0)
    1197             :     {
    1198             :         MdfdVec    *v;
    1199             : 
    1200        1020 :         priorblocks = (curopensegs - 1) * RELSEG_SIZE;
    1201             : 
    1202        1020 :         v = &reln->md_seg_fds[forknum][curopensegs - 1];
    1203             : 
    1204        1020 :         if (priorblocks > nblocks)
    1205             :         {
    1206             :             /*
    1207             :              * This segment is no longer active. We truncate the file, but do
    1208             :              * not delete it, for reasons explained in the header comments.
    1209             :              */
    1210           0 :             if (FileTruncate(v->mdfd_vfd, 0, WAIT_EVENT_DATA_FILE_TRUNCATE) < 0)
    1211           0 :                 ereport(ERROR,
    1212             :                         (errcode_for_file_access(),
    1213             :                          errmsg("could not truncate file \"%s\": %m",
    1214             :                                 FilePathName(v->mdfd_vfd))));
    1215             : 
    1216           0 :             if (!SmgrIsTemp(reln))
    1217           0 :                 register_dirty_segment(reln, forknum, v);
    1218             : 
    1219             :             /* we never drop the 1st segment */
    1220             :             Assert(v != &reln->md_seg_fds[forknum][0]);
    1221             : 
    1222           0 :             FileClose(v->mdfd_vfd);
    1223           0 :             _fdvec_resize(reln, forknum, curopensegs - 1);
    1224             :         }
    1225        1020 :         else if (priorblocks + ((BlockNumber) RELSEG_SIZE) > nblocks)
    1226             :         {
    1227             :             /*
    1228             :              * This is the last segment we want to keep. Truncate the file to
    1229             :              * the right length. NOTE: if nblocks is exactly a multiple K of
    1230             :              * RELSEG_SIZE, we will truncate the K+1st segment to 0 length but
    1231             :              * keep it. This adheres to the invariant given in the header
    1232             :              * comments.
    1233             :              */
    1234        1020 :             BlockNumber lastsegblocks = nblocks - priorblocks;
    1235             : 
    1236        1020 :             if (FileTruncate(v->mdfd_vfd, (off_t) lastsegblocks * BLCKSZ, WAIT_EVENT_DATA_FILE_TRUNCATE) < 0)
    1237           0 :                 ereport(ERROR,
    1238             :                         (errcode_for_file_access(),
    1239             :                          errmsg("could not truncate file \"%s\" to %u blocks: %m",
    1240             :                                 FilePathName(v->mdfd_vfd),
    1241             :                                 nblocks)));
    1242        1020 :             if (!SmgrIsTemp(reln))
    1243         746 :                 register_dirty_segment(reln, forknum, v);
    1244             :         }
    1245             :         else
    1246             :         {
    1247             :             /*
    1248             :              * We still need this segment, so nothing to do for this and any
    1249             :              * earlier segment.
    1250             :              */
    1251           0 :             break;
    1252             :         }
    1253        1020 :         curopensegs--;
    1254             :     }
    1255             : }
    1256             : 
    1257             : /*
    1258             :  * mdregistersync() -- Mark whole relation as needing fsync
    1259             :  */
    1260             : void
    1261       46276 : mdregistersync(SMgrRelation reln, ForkNumber forknum)
    1262             : {
    1263             :     int         segno;
    1264             :     int         min_inactive_seg;
    1265             : 
    1266             :     /*
    1267             :      * NOTE: mdnblocks makes sure we have opened all active segments, so that
    1268             :      * the loop below will get them all!
    1269             :      */
    1270       46276 :     mdnblocks(reln, forknum);
    1271             : 
    1272       46276 :     min_inactive_seg = segno = reln->md_num_open_segs[forknum];
    1273             : 
    1274             :     /*
    1275             :      * Temporarily open inactive segments, then close them after sync.  There
    1276             :      * may be some inactive segments left opened after error, but that is
    1277             :      * harmless.  We don't bother to clean them up and take a risk of further
    1278             :      * trouble.  The next mdclose() will soon close them.
    1279             :      */
    1280       46276 :     while (_mdfd_openseg(reln, forknum, segno, 0) != NULL)
    1281           0 :         segno++;
    1282             : 
    1283       92552 :     while (segno > 0)
    1284             :     {
    1285       46276 :         MdfdVec    *v = &reln->md_seg_fds[forknum][segno - 1];
    1286             : 
    1287       46276 :         register_dirty_segment(reln, forknum, v);
    1288             : 
    1289             :         /* Close inactive segments immediately */
    1290       46276 :         if (segno > min_inactive_seg)
    1291             :         {
    1292           0 :             FileClose(v->mdfd_vfd);
    1293           0 :             _fdvec_resize(reln, forknum, segno - 1);
    1294             :         }
    1295             : 
    1296       46276 :         segno--;
    1297             :     }
    1298       46276 : }
    1299             : 
    1300             : /*
    1301             :  * mdimmedsync() -- Immediately sync a relation to stable storage.
    1302             :  *
    1303             :  * Note that only writes already issued are synced; this routine knows
    1304             :  * nothing of dirty buffers that may exist inside the buffer manager.  We
    1305             :  * sync active and inactive segments; smgrDoPendingSyncs() relies on this.
    1306             :  * Consider a relation skipping WAL.  Suppose a checkpoint syncs blocks of
    1307             :  * some segment, then mdtruncate() renders that segment inactive.  If we
    1308             :  * crash before the next checkpoint syncs the newly-inactive segment, that
    1309             :  * segment may survive recovery, reintroducing unwanted data into the table.
    1310             :  */
    1311             : void
    1312          26 : mdimmedsync(SMgrRelation reln, ForkNumber forknum)
    1313             : {
    1314             :     int         segno;
    1315             :     int         min_inactive_seg;
    1316             : 
    1317             :     /*
    1318             :      * NOTE: mdnblocks makes sure we have opened all active segments, so that
    1319             :      * the loop below will get them all!
    1320             :      */
    1321          26 :     mdnblocks(reln, forknum);
    1322             : 
    1323          26 :     min_inactive_seg = segno = reln->md_num_open_segs[forknum];
    1324             : 
    1325             :     /*
    1326             :      * Temporarily open inactive segments, then close them after sync.  There
    1327             :      * may be some inactive segments left opened after fsync() error, but that
    1328             :      * is harmless.  We don't bother to clean them up and take a risk of
    1329             :      * further trouble.  The next mdclose() will soon close them.
    1330             :      */
    1331          26 :     while (_mdfd_openseg(reln, forknum, segno, 0) != NULL)
    1332           0 :         segno++;
    1333             : 
    1334          52 :     while (segno > 0)
    1335             :     {
    1336          26 :         MdfdVec    *v = &reln->md_seg_fds[forknum][segno - 1];
    1337             : 
    1338             :         /*
    1339             :          * fsyncs done through mdimmedsync() should be tracked in a separate
    1340             :          * IOContext than those done through mdsyncfiletag() to differentiate
    1341             :          * between unavoidable client backend fsyncs (e.g. those done during
    1342             :          * index build) and those which ideally would have been done by the
    1343             :          * checkpointer. Since other IO operations bypassing the buffer
    1344             :          * manager could also be tracked in such an IOContext, wait until
    1345             :          * these are also tracked to track immediate fsyncs.
    1346             :          */
    1347          26 :         if (FileSync(v->mdfd_vfd, WAIT_EVENT_DATA_FILE_IMMEDIATE_SYNC) < 0)
    1348           0 :             ereport(data_sync_elevel(ERROR),
    1349             :                     (errcode_for_file_access(),
    1350             :                      errmsg("could not fsync file \"%s\": %m",
    1351             :                             FilePathName(v->mdfd_vfd))));
    1352             : 
    1353             :         /* Close inactive segments immediately */
    1354          26 :         if (segno > min_inactive_seg)
    1355             :         {
    1356           0 :             FileClose(v->mdfd_vfd);
    1357           0 :             _fdvec_resize(reln, forknum, segno - 1);
    1358             :         }
    1359             : 
    1360          26 :         segno--;
    1361             :     }
    1362          26 : }
    1363             : 
    1364             : /*
    1365             :  * register_dirty_segment() -- Mark a relation segment as needing fsync
    1366             :  *
    1367             :  * If there is a local pending-ops table, just make an entry in it for
    1368             :  * ProcessSyncRequests to process later.  Otherwise, try to pass off the
    1369             :  * fsync request to the checkpointer process.  If that fails, just do the
    1370             :  * fsync locally before returning (we hope this will not happen often
    1371             :  * enough to be a performance problem).
    1372             :  */
    1373             : static void
    1374     1657894 : register_dirty_segment(SMgrRelation reln, ForkNumber forknum, MdfdVec *seg)
    1375             : {
    1376             :     FileTag     tag;
    1377             : 
    1378     1657894 :     INIT_MD_FILETAG(tag, reln->smgr_rlocator.locator, forknum, seg->mdfd_segno);
    1379             : 
    1380             :     /* Temp relations should never be fsync'd */
    1381             :     Assert(!SmgrIsTemp(reln));
    1382             : 
    1383     1657894 :     if (!RegisterSyncRequest(&tag, SYNC_REQUEST, false /* retryOnError */ ))
    1384             :     {
    1385             :         instr_time  io_start;
    1386             : 
    1387        1832 :         ereport(DEBUG1,
    1388             :                 (errmsg_internal("could not forward fsync request because request queue is full")));
    1389             : 
    1390        1832 :         io_start = pgstat_prepare_io_time(track_io_timing);
    1391             : 
    1392        1832 :         if (FileSync(seg->mdfd_vfd, WAIT_EVENT_DATA_FILE_SYNC) < 0)
    1393           0 :             ereport(data_sync_elevel(ERROR),
    1394             :                     (errcode_for_file_access(),
    1395             :                      errmsg("could not fsync file \"%s\": %m",
    1396             :                             FilePathName(seg->mdfd_vfd))));
    1397             : 
    1398             :         /*
    1399             :          * We have no way of knowing if the current IOContext is
    1400             :          * IOCONTEXT_NORMAL or IOCONTEXT_[BULKREAD, BULKWRITE, VACUUM] at this
    1401             :          * point, so count the fsync as being in the IOCONTEXT_NORMAL
    1402             :          * IOContext. This is probably okay, because the number of backend
    1403             :          * fsyncs doesn't say anything about the efficacy of the
    1404             :          * BufferAccessStrategy. And counting both fsyncs done in
    1405             :          * IOCONTEXT_NORMAL and IOCONTEXT_[BULKREAD, BULKWRITE, VACUUM] under
    1406             :          * IOCONTEXT_NORMAL is likely clearer when investigating the number of
    1407             :          * backend fsyncs.
    1408             :          */
    1409        1832 :         pgstat_count_io_op_time(IOOBJECT_RELATION, IOCONTEXT_NORMAL,
    1410             :                                 IOOP_FSYNC, io_start, 1);
    1411             :     }
    1412     1657894 : }
    1413             : 
    1414             : /*
    1415             :  * register_unlink_segment() -- Schedule a file to be deleted after next checkpoint
    1416             :  */
    1417             : static void
    1418       66914 : register_unlink_segment(RelFileLocatorBackend rlocator, ForkNumber forknum,
    1419             :                         BlockNumber segno)
    1420             : {
    1421             :     FileTag     tag;
    1422             : 
    1423       66914 :     INIT_MD_FILETAG(tag, rlocator.locator, forknum, segno);
    1424             : 
    1425             :     /* Should never be used with temp relations */
    1426             :     Assert(!RelFileLocatorBackendIsTemp(rlocator));
    1427             : 
    1428       66914 :     RegisterSyncRequest(&tag, SYNC_UNLINK_REQUEST, true /* retryOnError */ );
    1429       66914 : }
    1430             : 
    1431             : /*
    1432             :  * register_forget_request() -- forget any fsyncs for a relation fork's segment
    1433             :  */
    1434             : static void
    1435      258758 : register_forget_request(RelFileLocatorBackend rlocator, ForkNumber forknum,
    1436             :                         BlockNumber segno)
    1437             : {
    1438             :     FileTag     tag;
    1439             : 
    1440      258758 :     INIT_MD_FILETAG(tag, rlocator.locator, forknum, segno);
    1441             : 
    1442      258758 :     RegisterSyncRequest(&tag, SYNC_FORGET_REQUEST, true /* retryOnError */ );
    1443      258758 : }
    1444             : 
    1445             : /*
    1446             :  * ForgetDatabaseSyncRequests -- forget any fsyncs and unlinks for a DB
    1447             :  */
    1448             : void
    1449          98 : ForgetDatabaseSyncRequests(Oid dbid)
    1450             : {
    1451             :     FileTag     tag;
    1452             :     RelFileLocator rlocator;
    1453             : 
    1454          98 :     rlocator.dbOid = dbid;
    1455          98 :     rlocator.spcOid = 0;
    1456          98 :     rlocator.relNumber = 0;
    1457             : 
    1458          98 :     INIT_MD_FILETAG(tag, rlocator, InvalidForkNumber, InvalidBlockNumber);
    1459             : 
    1460          98 :     RegisterSyncRequest(&tag, SYNC_FILTER_REQUEST, true /* retryOnError */ );
    1461          98 : }
    1462             : 
    1463             : /*
    1464             :  * DropRelationFiles -- drop files of all given relations
    1465             :  */
    1466             : void
    1467        5126 : DropRelationFiles(RelFileLocator *delrels, int ndelrels, bool isRedo)
    1468             : {
    1469             :     SMgrRelation *srels;
    1470             :     int         i;
    1471             : 
    1472        5126 :     srels = palloc(sizeof(SMgrRelation) * ndelrels);
    1473       19638 :     for (i = 0; i < ndelrels; i++)
    1474             :     {
    1475       14512 :         SMgrRelation srel = smgropen(delrels[i], INVALID_PROC_NUMBER);
    1476             : 
    1477       14512 :         if (isRedo)
    1478             :         {
    1479             :             ForkNumber  fork;
    1480             : 
    1481       72320 :             for (fork = 0; fork <= MAX_FORKNUM; fork++)
    1482       57856 :                 XLogDropRelation(delrels[i], fork);
    1483             :         }
    1484       14512 :         srels[i] = srel;
    1485             :     }
    1486             : 
    1487        5126 :     smgrdounlinkall(srels, ndelrels, isRedo);
    1488             : 
    1489       19638 :     for (i = 0; i < ndelrels; i++)
    1490       14512 :         smgrclose(srels[i]);
    1491        5126 :     pfree(srels);
    1492        5126 : }
    1493             : 
    1494             : 
    1495             : /*
    1496             :  * _fdvec_resize() -- Resize the fork's open segments array
    1497             :  */
    1498             : static void
    1499     2580568 : _fdvec_resize(SMgrRelation reln,
    1500             :               ForkNumber forknum,
    1501             :               int nseg)
    1502             : {
    1503     2580568 :     if (nseg == 0)
    1504             :     {
    1505      967438 :         if (reln->md_num_open_segs[forknum] > 0)
    1506             :         {
    1507      967438 :             pfree(reln->md_seg_fds[forknum]);
    1508      967438 :             reln->md_seg_fds[forknum] = NULL;
    1509             :         }
    1510             :     }
    1511     1613130 :     else if (reln->md_num_open_segs[forknum] == 0)
    1512             :     {
    1513     1613130 :         reln->md_seg_fds[forknum] =
    1514     1613130 :             MemoryContextAlloc(MdCxt, sizeof(MdfdVec) * nseg);
    1515             :     }
    1516             :     else
    1517             :     {
    1518             :         /*
    1519             :          * It doesn't seem worthwhile complicating the code to amortize
    1520             :          * repalloc() calls.  Those are far faster than PathNameOpenFile() or
    1521             :          * FileClose(), and the memory context internally will sometimes avoid
    1522             :          * doing an actual reallocation.
    1523             :          */
    1524           0 :         reln->md_seg_fds[forknum] =
    1525           0 :             repalloc(reln->md_seg_fds[forknum],
    1526             :                      sizeof(MdfdVec) * nseg);
    1527             :     }
    1528             : 
    1529     2580568 :     reln->md_num_open_segs[forknum] = nseg;
    1530     2580568 : }
    1531             : 
    1532             : /*
    1533             :  * Return the filename for the specified segment of the relation. The
    1534             :  * returned string is palloc'd.
    1535             :  */
    1536             : static char *
    1537       46326 : _mdfd_segpath(SMgrRelation reln, ForkNumber forknum, BlockNumber segno)
    1538             : {
    1539             :     char       *path,
    1540             :                *fullpath;
    1541             : 
    1542       46326 :     path = relpath(reln->smgr_rlocator, forknum);
    1543             : 
    1544       46326 :     if (segno > 0)
    1545             :     {
    1546       46326 :         fullpath = psprintf("%s.%u", path, segno);
    1547       46326 :         pfree(path);
    1548             :     }
    1549             :     else
    1550           0 :         fullpath = path;
    1551             : 
    1552       46326 :     return fullpath;
    1553             : }
    1554             : 
    1555             : /*
    1556             :  * Open the specified segment of the relation,
    1557             :  * and make a MdfdVec object for it.  Returns NULL on failure.
    1558             :  */
    1559             : static MdfdVec *
    1560       46302 : _mdfd_openseg(SMgrRelation reln, ForkNumber forknum, BlockNumber segno,
    1561             :               int oflags)
    1562             : {
    1563             :     MdfdVec    *v;
    1564             :     File        fd;
    1565             :     char       *fullpath;
    1566             : 
    1567       46302 :     fullpath = _mdfd_segpath(reln, forknum, segno);
    1568             : 
    1569             :     /* open the file */
    1570       46302 :     fd = PathNameOpenFile(fullpath, _mdfd_open_flags() | oflags);
    1571             : 
    1572       46302 :     pfree(fullpath);
    1573             : 
    1574       46302 :     if (fd < 0)
    1575       46302 :         return NULL;
    1576             : 
    1577             :     /*
    1578             :      * Segments are always opened in order from lowest to highest, so we must
    1579             :      * be adding a new one at the end.
    1580             :      */
    1581             :     Assert(segno == reln->md_num_open_segs[forknum]);
    1582             : 
    1583           0 :     _fdvec_resize(reln, forknum, segno + 1);
    1584             : 
    1585             :     /* fill the entry */
    1586           0 :     v = &reln->md_seg_fds[forknum][segno];
    1587           0 :     v->mdfd_vfd = fd;
    1588           0 :     v->mdfd_segno = segno;
    1589             : 
    1590             :     Assert(_mdnblocks(reln, forknum, v) <= ((BlockNumber) RELSEG_SIZE));
    1591             : 
    1592             :     /* all done */
    1593           0 :     return v;
    1594             : }
    1595             : 
    1596             : /*
    1597             :  * _mdfd_getseg() -- Find the segment of the relation holding the
    1598             :  *                   specified block.
    1599             :  *
    1600             :  * If the segment doesn't exist, we ereport, return NULL, or create the
    1601             :  * segment, according to "behavior".  Note: skipFsync is only used in the
    1602             :  * EXTENSION_CREATE case.
    1603             :  */
    1604             : static MdfdVec *
    1605     3994178 : _mdfd_getseg(SMgrRelation reln, ForkNumber forknum, BlockNumber blkno,
    1606             :              bool skipFsync, int behavior)
    1607             : {
    1608             :     MdfdVec    *v;
    1609             :     BlockNumber targetseg;
    1610             :     BlockNumber nextsegno;
    1611             : 
    1612             :     /* some way to handle non-existent segments needs to be specified */
    1613             :     Assert(behavior &
    1614             :            (EXTENSION_FAIL | EXTENSION_CREATE | EXTENSION_RETURN_NULL |
    1615             :             EXTENSION_DONT_OPEN));
    1616             : 
    1617     3994178 :     targetseg = blkno / ((BlockNumber) RELSEG_SIZE);
    1618             : 
    1619             :     /* if an existing and opened segment, we're done */
    1620     3994178 :     if (targetseg < reln->md_num_open_segs[forknum])
    1621             :     {
    1622     3612270 :         v = &reln->md_seg_fds[forknum][targetseg];
    1623     3612270 :         return v;
    1624             :     }
    1625             : 
    1626             :     /* The caller only wants the segment if we already had it open. */
    1627      381908 :     if (behavior & EXTENSION_DONT_OPEN)
    1628           0 :         return NULL;
    1629             : 
    1630             :     /*
    1631             :      * The target segment is not yet open. Iterate over all the segments
    1632             :      * between the last opened and the target segment. This way missing
    1633             :      * segments either raise an error, or get created (according to
    1634             :      * 'behavior'). Start with either the last opened, or the first segment if
    1635             :      * none was opened before.
    1636             :      */
    1637      381908 :     if (reln->md_num_open_segs[forknum] > 0)
    1638          24 :         v = &reln->md_seg_fds[forknum][reln->md_num_open_segs[forknum] - 1];
    1639             :     else
    1640             :     {
    1641      381884 :         v = mdopenfork(reln, forknum, behavior);
    1642      381878 :         if (!v)
    1643           0 :             return NULL;        /* if behavior & EXTENSION_RETURN_NULL */
    1644             :     }
    1645             : 
    1646      381902 :     for (nextsegno = reln->md_num_open_segs[forknum];
    1647           0 :          nextsegno <= targetseg; nextsegno++)
    1648             :     {
    1649          24 :         BlockNumber nblocks = _mdnblocks(reln, forknum, v);
    1650          24 :         int         flags = 0;
    1651             : 
    1652             :         Assert(nextsegno == v->mdfd_segno + 1);
    1653             : 
    1654          24 :         if (nblocks > ((BlockNumber) RELSEG_SIZE))
    1655           0 :             elog(FATAL, "segment too big");
    1656             : 
    1657          24 :         if ((behavior & EXTENSION_CREATE) ||
    1658          24 :             (InRecovery && (behavior & EXTENSION_CREATE_RECOVERY)))
    1659             :         {
    1660             :             /*
    1661             :              * Normally we will create new segments only if authorized by the
    1662             :              * caller (i.e., we are doing mdextend()).  But when doing WAL
    1663             :              * recovery, create segments anyway; this allows cases such as
    1664             :              * replaying WAL data that has a write into a high-numbered
    1665             :              * segment of a relation that was later deleted. We want to go
    1666             :              * ahead and create the segments so we can finish out the replay.
    1667             :              *
    1668             :              * We have to maintain the invariant that segments before the last
    1669             :              * active segment are of size RELSEG_SIZE; therefore, if
    1670             :              * extending, pad them out with zeroes if needed.  (This only
    1671             :              * matters if in recovery, or if the caller is extending the
    1672             :              * relation discontiguously, but that can happen in hash indexes.)
    1673             :              */
    1674           0 :             if (nblocks < ((BlockNumber) RELSEG_SIZE))
    1675             :             {
    1676           0 :                 char       *zerobuf = palloc_aligned(BLCKSZ, PG_IO_ALIGN_SIZE,
    1677             :                                                      MCXT_ALLOC_ZERO);
    1678             : 
    1679           0 :                 mdextend(reln, forknum,
    1680           0 :                          nextsegno * ((BlockNumber) RELSEG_SIZE) - 1,
    1681             :                          zerobuf, skipFsync);
    1682           0 :                 pfree(zerobuf);
    1683             :             }
    1684           0 :             flags = O_CREAT;
    1685             :         }
    1686          24 :         else if (!(behavior & EXTENSION_DONT_CHECK_SIZE) &&
    1687             :                  nblocks < ((BlockNumber) RELSEG_SIZE))
    1688             :         {
    1689             :             /*
    1690             :              * When not extending (or explicitly including truncated
    1691             :              * segments), only open the next segment if the current one is
    1692             :              * exactly RELSEG_SIZE.  If not (this branch), either return NULL
    1693             :              * or fail.
    1694             :              */
    1695          24 :             if (behavior & EXTENSION_RETURN_NULL)
    1696             :             {
    1697             :                 /*
    1698             :                  * Some callers discern between reasons for _mdfd_getseg()
    1699             :                  * returning NULL based on errno. As there's no failing
    1700             :                  * syscall involved in this case, explicitly set errno to
    1701             :                  * ENOENT, as that seems the closest interpretation.
    1702             :                  */
    1703           0 :                 errno = ENOENT;
    1704           0 :                 return NULL;
    1705             :             }
    1706             : 
    1707          24 :             ereport(ERROR,
    1708             :                     (errcode_for_file_access(),
    1709             :                      errmsg("could not open file \"%s\" (target block %u): previous segment is only %u blocks",
    1710             :                             _mdfd_segpath(reln, forknum, nextsegno),
    1711             :                             blkno, nblocks)));
    1712             :         }
    1713             : 
    1714           0 :         v = _mdfd_openseg(reln, forknum, nextsegno, flags);
    1715             : 
    1716           0 :         if (v == NULL)
    1717             :         {
    1718           0 :             if ((behavior & EXTENSION_RETURN_NULL) &&
    1719           0 :                 FILE_POSSIBLY_DELETED(errno))
    1720           0 :                 return NULL;
    1721           0 :             ereport(ERROR,
    1722             :                     (errcode_for_file_access(),
    1723             :                      errmsg("could not open file \"%s\" (target block %u): %m",
    1724             :                             _mdfd_segpath(reln, forknum, nextsegno),
    1725             :                             blkno)));
    1726             :         }
    1727             :     }
    1728             : 
    1729      381878 :     return v;
    1730             : }
    1731             : 
    1732             : /*
    1733             :  * Get number of blocks present in a single disk file
    1734             :  */
    1735             : static BlockNumber
    1736     3897164 : _mdnblocks(SMgrRelation reln, ForkNumber forknum, MdfdVec *seg)
    1737             : {
    1738             :     off_t       len;
    1739             : 
    1740     3897164 :     len = FileSize(seg->mdfd_vfd);
    1741     3897164 :     if (len < 0)
    1742           0 :         ereport(ERROR,
    1743             :                 (errcode_for_file_access(),
    1744             :                  errmsg("could not seek to end of file \"%s\": %m",
    1745             :                         FilePathName(seg->mdfd_vfd))));
    1746             :     /* note that this calculation will ignore any partial block at EOF */
    1747     3897164 :     return (BlockNumber) (len / BLCKSZ);
    1748             : }
    1749             : 
    1750             : /*
    1751             :  * Sync a file to disk, given a file tag.  Write the path into an output
    1752             :  * buffer so the caller can use it in error messages.
    1753             :  *
    1754             :  * Return 0 on success, -1 on failure, with errno set.
    1755             :  */
    1756             : int
    1757           0 : mdsyncfiletag(const FileTag *ftag, char *path)
    1758             : {
    1759           0 :     SMgrRelation reln = smgropen(ftag->rlocator, INVALID_PROC_NUMBER);
    1760             :     File        file;
    1761             :     instr_time  io_start;
    1762             :     bool        need_to_close;
    1763             :     int         result,
    1764             :                 save_errno;
    1765             : 
    1766             :     /* See if we already have the file open, or need to open it. */
    1767           0 :     if (ftag->segno < reln->md_num_open_segs[ftag->forknum])
    1768             :     {
    1769           0 :         file = reln->md_seg_fds[ftag->forknum][ftag->segno].mdfd_vfd;
    1770           0 :         strlcpy(path, FilePathName(file), MAXPGPATH);
    1771           0 :         need_to_close = false;
    1772             :     }
    1773             :     else
    1774             :     {
    1775             :         char       *p;
    1776             : 
    1777           0 :         p = _mdfd_segpath(reln, ftag->forknum, ftag->segno);
    1778           0 :         strlcpy(path, p, MAXPGPATH);
    1779           0 :         pfree(p);
    1780             : 
    1781           0 :         file = PathNameOpenFile(path, _mdfd_open_flags());
    1782           0 :         if (file < 0)
    1783           0 :             return -1;
    1784           0 :         need_to_close = true;
    1785             :     }
    1786             : 
    1787           0 :     io_start = pgstat_prepare_io_time(track_io_timing);
    1788             : 
    1789             :     /* Sync the file. */
    1790           0 :     result = FileSync(file, WAIT_EVENT_DATA_FILE_SYNC);
    1791           0 :     save_errno = errno;
    1792             : 
    1793           0 :     if (need_to_close)
    1794           0 :         FileClose(file);
    1795             : 
    1796           0 :     pgstat_count_io_op_time(IOOBJECT_RELATION, IOCONTEXT_NORMAL,
    1797             :                             IOOP_FSYNC, io_start, 1);
    1798             : 
    1799           0 :     errno = save_errno;
    1800           0 :     return result;
    1801             : }
    1802             : 
    1803             : /*
    1804             :  * Unlink a file, given a file tag.  Write the path into an output
    1805             :  * buffer so the caller can use it in error messages.
    1806             :  *
    1807             :  * Return 0 on success, -1 on failure, with errno set.
    1808             :  */
    1809             : int
    1810       63016 : mdunlinkfiletag(const FileTag *ftag, char *path)
    1811             : {
    1812             :     char       *p;
    1813             : 
    1814             :     /* Compute the path. */
    1815       63016 :     p = relpathperm(ftag->rlocator, MAIN_FORKNUM);
    1816       63016 :     strlcpy(path, p, MAXPGPATH);
    1817       63016 :     pfree(p);
    1818             : 
    1819             :     /* Try to unlink the file. */
    1820       63016 :     return unlink(path);
    1821             : }
    1822             : 
    1823             : /*
    1824             :  * Check if a given candidate request matches a given tag, when processing
    1825             :  * a SYNC_FILTER_REQUEST request.  This will be called for all pending
    1826             :  * requests to find out whether to forget them.
    1827             :  */
    1828             : bool
    1829       12536 : mdfiletagmatches(const FileTag *ftag, const FileTag *candidate)
    1830             : {
    1831             :     /*
    1832             :      * For now we only use filter requests as a way to drop all scheduled
    1833             :      * callbacks relating to a given database, when dropping the database.
    1834             :      * We'll return true for all candidates that have the same database OID as
    1835             :      * the ftag from the SYNC_FILTER_REQUEST request, so they're forgotten.
    1836             :      */
    1837       12536 :     return ftag->rlocator.dbOid == candidate->rlocator.dbOid;
    1838             : }

Generated by: LCOV version 1.14