LCOV - code coverage report
Current view: top level - src/backend/storage/smgr - md.c (source / functions) Hit Total Coverage
Test: PostgreSQL 13beta1 Lines: 254 334 76.0 %
Date: 2020-06-01 07:06:57 Functions: 29 29 100.0 %
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-2020, 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/xlog.h"
      29             : #include "access/xlogutils.h"
      30             : #include "commands/tablespace.h"
      31             : #include "miscadmin.h"
      32             : #include "pg_trace.h"
      33             : #include "pgstat.h"
      34             : #include "postmaster/bgwriter.h"
      35             : #include "storage/bufmgr.h"
      36             : #include "storage/fd.h"
      37             : #include "storage/md.h"
      38             : #include "storage/relfilenode.h"
      39             : #include "storage/smgr.h"
      40             : #include "storage/sync.h"
      41             : #include "utils/hsearch.h"
      42             : #include "utils/memutils.h"
      43             : 
      44             : /*
      45             :  *  The magnetic disk storage manager keeps track of open file
      46             :  *  descriptors in its own descriptor pool.  This is done to make it
      47             :  *  easier to support relations that are larger than the operating
      48             :  *  system's file size limit (often 2GBytes).  In order to do that,
      49             :  *  we break relations up into "segment" files that are each shorter than
      50             :  *  the OS file size limit.  The segment size is set by the RELSEG_SIZE
      51             :  *  configuration constant in pg_config.h.
      52             :  *
      53             :  *  On disk, a relation must consist of consecutively numbered segment
      54             :  *  files in the pattern
      55             :  *      -- Zero or more full segments of exactly RELSEG_SIZE blocks each
      56             :  *      -- Exactly one partial segment of size 0 <= size < RELSEG_SIZE blocks
      57             :  *      -- Optionally, any number of inactive segments of size 0 blocks.
      58             :  *  The full and partial segments are collectively the "active" segments.
      59             :  *  Inactive segments are those that once contained data but are currently
      60             :  *  not needed because of an mdtruncate() operation.  The reason for leaving
      61             :  *  them present at size zero, rather than unlinking them, is that other
      62             :  *  backends and/or the checkpointer might be holding open file references to
      63             :  *  such segments.  If the relation expands again after mdtruncate(), such
      64             :  *  that a deactivated segment becomes active again, it is important that
      65             :  *  such file references still be valid --- else data might get written
      66             :  *  out to an unlinked old copy of a segment file that will eventually
      67             :  *  disappear.
      68             :  *
      69             :  *  File descriptors are stored in the per-fork md_seg_fds arrays inside
      70             :  *  SMgrRelation. The length of these arrays is stored in md_num_open_segs.
      71             :  *  Note that a fork's md_num_open_segs having a specific value does not
      72             :  *  necessarily mean the relation doesn't have additional segments; we may
      73             :  *  just not have opened the next segment yet.  (We could not have "all
      74             :  *  segments are in the array" as an invariant anyway, since another backend
      75             :  *  could extend the relation while we aren't looking.)  We do not have
      76             :  *  entries for inactive segments, however; as soon as we find a partial
      77             :  *  segment, we assume that any subsequent segments are inactive.
      78             :  *
      79             :  *  The entire MdfdVec array is palloc'd in the MdCxt memory context.
      80             :  */
      81             : 
      82             : typedef struct _MdfdVec
      83             : {
      84             :     File        mdfd_vfd;       /* fd number in fd.c's pool */
      85             :     BlockNumber mdfd_segno;     /* segment number, from 0 */
      86             : } MdfdVec;
      87             : 
      88             : static MemoryContext MdCxt;     /* context for all MdfdVec objects */
      89             : 
      90             : 
      91             : /* Populate a file tag describing an md.c segment file. */
      92             : #define INIT_MD_FILETAG(a,xx_rnode,xx_forknum,xx_segno) \
      93             : ( \
      94             :     memset(&(a), 0, sizeof(FileTag)), \
      95             :     (a).handler = SYNC_HANDLER_MD, \
      96             :     (a).rnode = (xx_rnode), \
      97             :     (a).forknum = (xx_forknum), \
      98             :     (a).segno = (xx_segno) \
      99             : )
     100             : 
     101             : 
     102             : /*** behavior for mdopen & _mdfd_getseg ***/
     103             : /* ereport if segment not present */
     104             : #define EXTENSION_FAIL              (1 << 0)
     105             : /* return NULL if segment not present */
     106             : #define EXTENSION_RETURN_NULL       (1 << 1)
     107             : /* create new segments as needed */
     108             : #define EXTENSION_CREATE            (1 << 2)
     109             : /* create new segments if needed during recovery */
     110             : #define EXTENSION_CREATE_RECOVERY   (1 << 3)
     111             : /*
     112             :  * Allow opening segments which are preceded by segments smaller than
     113             :  * RELSEG_SIZE, e.g. inactive segments (see above). Note that this breaks
     114             :  * mdnblocks() and related functionality henceforth - which currently is ok,
     115             :  * because this is only required in the checkpointer which never uses
     116             :  * mdnblocks().
     117             :  */
     118             : #define EXTENSION_DONT_CHECK_SIZE   (1 << 4)
     119             : 
     120             : 
     121             : /* local routines */
     122             : static void mdunlinkfork(RelFileNodeBackend rnode, 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(RelFileNodeBackend rnode, ForkNumber forknum,
     128             :                                     BlockNumber segno);
     129             : static void register_forget_request(RelFileNodeBackend rnode, 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 forkno,
     137             :                               BlockNumber segno, int oflags);
     138             : static MdfdVec *_mdfd_getseg(SMgrRelation reln, ForkNumber forkno,
     139             :                              BlockNumber blkno, bool skipFsync, int behavior);
     140             : static BlockNumber _mdnblocks(SMgrRelation reln, ForkNumber forknum,
     141             :                               MdfdVec *seg);
     142             : 
     143             : 
     144             : /*
     145             :  *  mdinit() -- Initialize private state for magnetic disk storage manager.
     146             :  */
     147             : void
     148       13826 : mdinit(void)
     149             : {
     150       13826 :     MdCxt = AllocSetContextCreate(TopMemoryContext,
     151             :                                   "MdSmgr",
     152             :                                   ALLOCSET_DEFAULT_SIZES);
     153       13826 : }
     154             : 
     155             : /*
     156             :  *  mdexists() -- Does the physical file exist?
     157             :  *
     158             :  * Note: this will return true for lingering files, with pending deletions
     159             :  */
     160             : bool
     161      452538 : mdexists(SMgrRelation reln, ForkNumber forkNum)
     162             : {
     163             :     /*
     164             :      * Close it first, to ensure that we notice if the fork has been unlinked
     165             :      * since we opened it.
     166             :      */
     167      452538 :     mdclose(reln, forkNum);
     168             : 
     169      452538 :     return (mdopenfork(reln, forkNum, EXTENSION_RETURN_NULL) != NULL);
     170             : }
     171             : 
     172             : /*
     173             :  *  mdcreate() -- Create a new relation on magnetic disk.
     174             :  *
     175             :  * If isRedo is true, it's okay for the relation to exist already.
     176             :  */
     177             : void
     178      829228 : mdcreate(SMgrRelation reln, ForkNumber forkNum, bool isRedo)
     179             : {
     180             :     MdfdVec    *mdfd;
     181             :     char       *path;
     182             :     File        fd;
     183             : 
     184      829228 :     if (isRedo && reln->md_num_open_segs[forkNum] > 0)
     185      649018 :         return;                 /* created and opened already... */
     186             : 
     187             :     Assert(reln->md_num_open_segs[forkNum] == 0);
     188             : 
     189             :     /*
     190             :      * We may be using the target table space for the first time in this
     191             :      * database, so create a per-database subdirectory if needed.
     192             :      *
     193             :      * XXX this is a fairly ugly violation of module layering, but this seems
     194             :      * to be the best place to put the check.  Maybe TablespaceCreateDbspace
     195             :      * should be here and not in commands/tablespace.c?  But that would imply
     196             :      * importing a lot of stuff that smgr.c oughtn't know, either.
     197             :      */
     198      180210 :     TablespaceCreateDbspace(reln->smgr_rnode.node.spcNode,
     199             :                             reln->smgr_rnode.node.dbNode,
     200             :                             isRedo);
     201             : 
     202      180210 :     path = relpath(reln->smgr_rnode, forkNum);
     203             : 
     204      180210 :     fd = PathNameOpenFile(path, O_RDWR | O_CREAT | O_EXCL | PG_BINARY);
     205             : 
     206      180210 :     if (fd < 0)
     207             :     {
     208        3040 :         int         save_errno = errno;
     209             : 
     210        3040 :         if (isRedo)
     211        3040 :             fd = PathNameOpenFile(path, O_RDWR | PG_BINARY);
     212        3040 :         if (fd < 0)
     213             :         {
     214             :             /* be sure to report the error reported by create, not open */
     215           0 :             errno = save_errno;
     216           0 :             ereport(ERROR,
     217             :                     (errcode_for_file_access(),
     218             :                      errmsg("could not create file \"%s\": %m", path)));
     219             :         }
     220             :     }
     221             : 
     222      180210 :     pfree(path);
     223             : 
     224      180210 :     _fdvec_resize(reln, forkNum, 1);
     225      180210 :     mdfd = &reln->md_seg_fds[forkNum][0];
     226      180210 :     mdfd->mdfd_vfd = fd;
     227      180210 :     mdfd->mdfd_segno = 0;
     228             : }
     229             : 
     230             : /*
     231             :  *  mdunlink() -- Unlink a relation.
     232             :  *
     233             :  * Note that we're passed a RelFileNodeBackend --- by the time this is called,
     234             :  * there won't be an SMgrRelation hashtable entry anymore.
     235             :  *
     236             :  * forkNum can be a fork number to delete a specific fork, or InvalidForkNumber
     237             :  * to delete all forks.
     238             :  *
     239             :  * For regular relations, we don't unlink the first segment file of the rel,
     240             :  * but just truncate it to zero length, and record a request to unlink it after
     241             :  * the next checkpoint.  Additional segments can be unlinked immediately,
     242             :  * however.  Leaving the empty file in place prevents that relfilenode
     243             :  * number from being reused.  The scenario this protects us from is:
     244             :  * 1. We delete a relation (and commit, and actually remove its file).
     245             :  * 2. We create a new relation, which by chance gets the same relfilenode as
     246             :  *    the just-deleted one (OIDs must've wrapped around for that to happen).
     247             :  * 3. We crash before another checkpoint occurs.
     248             :  * During replay, we would delete the file and then recreate it, which is fine
     249             :  * if the contents of the file were repopulated by subsequent WAL entries.
     250             :  * But if we didn't WAL-log insertions, but instead relied on fsyncing the
     251             :  * file after populating it (as we do at wal_level=minimal), the contents of
     252             :  * the file would be lost forever.  By leaving the empty file until after the
     253             :  * next checkpoint, we prevent reassignment of the relfilenode number until
     254             :  * it's safe, because relfilenode assignment skips over any existing file.
     255             :  *
     256             :  * We do not need to go through this dance for temp relations, though, because
     257             :  * we never make WAL entries for temp rels, and so a temp rel poses no threat
     258             :  * to the health of a regular rel that has taken over its relfilenode number.
     259             :  * The fact that temp rels and regular rels have different file naming
     260             :  * patterns provides additional safety.
     261             :  *
     262             :  * All the above applies only to the relation's main fork; other forks can
     263             :  * just be removed immediately, since they are not needed to prevent the
     264             :  * relfilenode number from being recycled.  Also, we do not carefully
     265             :  * track whether other forks have been created or not, but just attempt to
     266             :  * unlink them unconditionally; so we should never complain about ENOENT.
     267             :  *
     268             :  * If isRedo is true, it's unsurprising for the relation to be already gone.
     269             :  * Also, we should remove the file immediately instead of queuing a request
     270             :  * for later, since during redo there's no possibility of creating a
     271             :  * conflicting relation.
     272             :  *
     273             :  * Note: any failure should be reported as WARNING not ERROR, because
     274             :  * we are usually not in a transaction anymore when this is called.
     275             :  */
     276             : void
     277      169328 : mdunlink(RelFileNodeBackend rnode, ForkNumber forkNum, bool isRedo)
     278             : {
     279             :     /* Now do the per-fork work */
     280      169328 :     if (forkNum == InvalidForkNumber)
     281             :     {
     282           0 :         for (forkNum = 0; forkNum <= MAX_FORKNUM; forkNum++)
     283           0 :             mdunlinkfork(rnode, forkNum, isRedo);
     284             :     }
     285             :     else
     286      169328 :         mdunlinkfork(rnode, forkNum, isRedo);
     287      169328 : }
     288             : 
     289             : static void
     290      169328 : mdunlinkfork(RelFileNodeBackend rnode, ForkNumber forkNum, bool isRedo)
     291             : {
     292             :     char       *path;
     293             :     int         ret;
     294             : 
     295      169328 :     path = relpath(rnode, forkNum);
     296             : 
     297             :     /*
     298             :      * Delete or truncate the first segment.
     299             :      */
     300      169328 :     if (isRedo || forkNum != MAIN_FORKNUM || RelFileNodeBackendIsTemp(rnode))
     301             :     {
     302             :         /* First, forget any pending sync requests for the first segment */
     303      130272 :         if (!RelFileNodeBackendIsTemp(rnode))
     304      117488 :             register_forget_request(rnode, forkNum, 0 /* first seg */ );
     305             : 
     306             :         /* Next unlink the file */
     307      130272 :         ret = unlink(path);
     308      130272 :         if (ret < 0 && errno != ENOENT)
     309           0 :             ereport(WARNING,
     310             :                     (errcode_for_file_access(),
     311             :                      errmsg("could not remove file \"%s\": %m", path)));
     312             :     }
     313             :     else
     314             :     {
     315             :         /* truncate(2) would be easier here, but Windows hasn't got it */
     316             :         int         fd;
     317             : 
     318       39056 :         fd = OpenTransientFile(path, O_RDWR | PG_BINARY);
     319       39056 :         if (fd >= 0)
     320             :         {
     321             :             int         save_errno;
     322             : 
     323       39056 :             ret = ftruncate(fd, 0);
     324       39056 :             save_errno = errno;
     325       39056 :             CloseTransientFile(fd);
     326       39056 :             errno = save_errno;
     327             :         }
     328             :         else
     329           0 :             ret = -1;
     330       39056 :         if (ret < 0 && errno != ENOENT)
     331           0 :             ereport(WARNING,
     332             :                     (errcode_for_file_access(),
     333             :                      errmsg("could not truncate file \"%s\": %m", path)));
     334             : 
     335             :         /* Register request to unlink first segment later */
     336       39056 :         register_unlink_segment(rnode, forkNum, 0 /* first seg */ );
     337             :     }
     338             : 
     339             :     /*
     340             :      * Delete any additional segments.
     341             :      */
     342      169328 :     if (ret >= 0)
     343             :     {
     344       43952 :         char       *segpath = (char *) palloc(strlen(path) + 12);
     345             :         BlockNumber segno;
     346             : 
     347             :         /*
     348             :          * Note that because we loop until getting ENOENT, we will correctly
     349             :          * remove all inactive segments as well as active ones.
     350             :          */
     351       43952 :         for (segno = 1;; segno++)
     352             :         {
     353             :             /*
     354             :              * Forget any pending sync requests for this segment before we try
     355             :              * to unlink.
     356             :              */
     357       43952 :             if (!RelFileNodeBackendIsTemp(rnode))
     358       40692 :                 register_forget_request(rnode, forkNum, segno);
     359             : 
     360       43952 :             sprintf(segpath, "%s.%u", path, segno);
     361       43952 :             if (unlink(segpath) < 0)
     362             :             {
     363             :                 /* ENOENT is expected after the last segment... */
     364       43952 :                 if (errno != ENOENT)
     365           0 :                     ereport(WARNING,
     366             :                             (errcode_for_file_access(),
     367             :                              errmsg("could not remove file \"%s\": %m", segpath)));
     368       43952 :                 break;
     369             :             }
     370             :         }
     371       43952 :         pfree(segpath);
     372             :     }
     373             : 
     374      169328 :     pfree(path);
     375      169328 : }
     376             : 
     377             : /*
     378             :  *  mdextend() -- Add a block to the specified relation.
     379             :  *
     380             :  *      The semantics are nearly the same as mdwrite(): write at the
     381             :  *      specified position.  However, this is to be used for the case of
     382             :  *      extending a relation (i.e., blocknum is at or beyond the current
     383             :  *      EOF).  Note that we assume writing a block beyond current EOF
     384             :  *      causes intervening file space to become filled with zeroes.
     385             :  */
     386             : void
     387      599970 : mdextend(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum,
     388             :          char *buffer, bool skipFsync)
     389             : {
     390             :     off_t       seekpos;
     391             :     int         nbytes;
     392             :     MdfdVec    *v;
     393             : 
     394             :     /* This assert is too expensive to have on normally ... */
     395             : #ifdef CHECK_WRITE_VS_EXTEND
     396             :     Assert(blocknum >= mdnblocks(reln, forknum));
     397             : #endif
     398             : 
     399             :     /*
     400             :      * If a relation manages to grow to 2^32-1 blocks, refuse to extend it any
     401             :      * more --- we mustn't create a block whose number actually is
     402             :      * InvalidBlockNumber.
     403             :      */
     404      599970 :     if (blocknum == InvalidBlockNumber)
     405           0 :         ereport(ERROR,
     406             :                 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
     407             :                  errmsg("cannot extend file \"%s\" beyond %u blocks",
     408             :                         relpath(reln->smgr_rnode, forknum),
     409             :                         InvalidBlockNumber)));
     410             : 
     411      599970 :     v = _mdfd_getseg(reln, forknum, blocknum, skipFsync, EXTENSION_CREATE);
     412             : 
     413      599970 :     seekpos = (off_t) BLCKSZ * (blocknum % ((BlockNumber) RELSEG_SIZE));
     414             : 
     415             :     Assert(seekpos < (off_t) BLCKSZ * RELSEG_SIZE);
     416             : 
     417      599970 :     if ((nbytes = FileWrite(v->mdfd_vfd, buffer, BLCKSZ, seekpos, WAIT_EVENT_DATA_FILE_EXTEND)) != BLCKSZ)
     418             :     {
     419           0 :         if (nbytes < 0)
     420           0 :             ereport(ERROR,
     421             :                     (errcode_for_file_access(),
     422             :                      errmsg("could not extend file \"%s\": %m",
     423             :                             FilePathName(v->mdfd_vfd)),
     424             :                      errhint("Check free disk space.")));
     425             :         /* short write: complain appropriately */
     426           0 :         ereport(ERROR,
     427             :                 (errcode(ERRCODE_DISK_FULL),
     428             :                  errmsg("could not extend file \"%s\": wrote only %d of %d bytes at block %u",
     429             :                         FilePathName(v->mdfd_vfd),
     430             :                         nbytes, BLCKSZ, blocknum),
     431             :                  errhint("Check free disk space.")));
     432             :     }
     433             : 
     434      599970 :     if (!skipFsync && !SmgrIsTemp(reln))
     435      425234 :         register_dirty_segment(reln, forknum, v);
     436             : 
     437             :     Assert(_mdnblocks(reln, forknum, v) <= ((BlockNumber) RELSEG_SIZE));
     438      599970 : }
     439             : 
     440             : /*
     441             :  *  mdopenfork() -- Open one fork of the specified relation.
     442             :  *
     443             :  * Note we only open the first segment, when there are multiple segments.
     444             :  *
     445             :  * If first segment is not present, either ereport or return NULL according
     446             :  * to "behavior".  We treat EXTENSION_CREATE the same as EXTENSION_FAIL;
     447             :  * EXTENSION_CREATE means it's OK to extend an existing relation, not to
     448             :  * invent one out of whole cloth.
     449             :  */
     450             : static MdfdVec *
     451     5030898 : mdopenfork(SMgrRelation reln, ForkNumber forknum, int behavior)
     452             : {
     453             :     MdfdVec    *mdfd;
     454             :     char       *path;
     455             :     File        fd;
     456             : 
     457             :     /* No work if already open */
     458     5030898 :     if (reln->md_num_open_segs[forknum] > 0)
     459     3710528 :         return &reln->md_seg_fds[forknum][0];
     460             : 
     461     1320370 :     path = relpath(reln->smgr_rnode, forknum);
     462             : 
     463     1320370 :     fd = PathNameOpenFile(path, O_RDWR | PG_BINARY);
     464             : 
     465     1320370 :     if (fd < 0)
     466             :     {
     467      308572 :         if ((behavior & EXTENSION_RETURN_NULL) &&
     468      308572 :             FILE_POSSIBLY_DELETED(errno))
     469             :         {
     470      308572 :             pfree(path);
     471      308572 :             return NULL;
     472             :         }
     473           0 :         ereport(ERROR,
     474             :                 (errcode_for_file_access(),
     475             :                  errmsg("could not open file \"%s\": %m", path)));
     476             :     }
     477             : 
     478     1011798 :     pfree(path);
     479             : 
     480     1011798 :     _fdvec_resize(reln, forknum, 1);
     481     1011798 :     mdfd = &reln->md_seg_fds[forknum][0];
     482     1011798 :     mdfd->mdfd_vfd = fd;
     483     1011798 :     mdfd->mdfd_segno = 0;
     484             : 
     485             :     Assert(_mdnblocks(reln, forknum, mdfd) <= ((BlockNumber) RELSEG_SIZE));
     486             : 
     487     1011798 :     return mdfd;
     488             : }
     489             : 
     490             : /*
     491             :  *  mdopen() -- Initialize newly-opened relation.
     492             :  */
     493             : void
     494     1331528 : mdopen(SMgrRelation reln)
     495             : {
     496             :     /* mark it not open */
     497     6657640 :     for (int forknum = 0; forknum <= MAX_FORKNUM; forknum++)
     498     5326112 :         reln->md_num_open_segs[forknum] = 0;
     499     1331528 : }
     500             : 
     501             : /*
     502             :  *  mdclose() -- Close the specified relation, if it isn't closed already.
     503             :  */
     504             : void
     505     4062810 : mdclose(SMgrRelation reln, ForkNumber forknum)
     506             : {
     507     4062810 :     int         nopensegs = reln->md_num_open_segs[forknum];
     508             : 
     509             :     /* No work if already closed */
     510     4062810 :     if (nopensegs == 0)
     511     3147376 :         return;
     512             : 
     513             :     /* close segments starting from the end */
     514     1830868 :     while (nopensegs > 0)
     515             :     {
     516      915434 :         MdfdVec    *v = &reln->md_seg_fds[forknum][nopensegs - 1];
     517             : 
     518      915434 :         FileClose(v->mdfd_vfd);
     519      915434 :         _fdvec_resize(reln, forknum, nopensegs - 1);
     520      915434 :         nopensegs--;
     521             :     }
     522             : }
     523             : 
     524             : /*
     525             :  *  mdprefetch() -- Initiate asynchronous read of the specified block of a relation
     526             :  */
     527             : bool
     528         218 : mdprefetch(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum)
     529             : {
     530             : #ifdef USE_PREFETCH
     531             :     off_t       seekpos;
     532             :     MdfdVec    *v;
     533             : 
     534         218 :     v = _mdfd_getseg(reln, forknum, blocknum, false,
     535         218 :                      InRecovery ? EXTENSION_RETURN_NULL : EXTENSION_FAIL);
     536         218 :     if (v == NULL)
     537           0 :         return false;
     538             : 
     539         218 :     seekpos = (off_t) BLCKSZ * (blocknum % ((BlockNumber) RELSEG_SIZE));
     540             : 
     541             :     Assert(seekpos < (off_t) BLCKSZ * RELSEG_SIZE);
     542             : 
     543         218 :     (void) FilePrefetch(v->mdfd_vfd, seekpos, BLCKSZ, WAIT_EVENT_DATA_FILE_PREFETCH);
     544             : #endif                          /* USE_PREFETCH */
     545             : 
     546         218 :     return true;
     547             : }
     548             : 
     549             : /*
     550             :  * mdwriteback() -- Tell the kernel to write pages back to storage.
     551             :  *
     552             :  * This accepts a range of blocks because flushing several pages at once is
     553             :  * considerably more efficient than doing so individually.
     554             :  */
     555             : void
     556      163566 : mdwriteback(SMgrRelation reln, ForkNumber forknum,
     557             :             BlockNumber blocknum, BlockNumber nblocks)
     558             : {
     559             :     /*
     560             :      * Issue flush requests in as few requests as possible; have to split at
     561             :      * segment boundaries though, since those are actually separate files.
     562             :      */
     563      327132 :     while (nblocks > 0)
     564             :     {
     565      163566 :         BlockNumber nflush = nblocks;
     566             :         off_t       seekpos;
     567             :         MdfdVec    *v;
     568             :         int         segnum_start,
     569             :                     segnum_end;
     570             : 
     571      163566 :         v = _mdfd_getseg(reln, forknum, blocknum, true /* not used */ ,
     572             :                          EXTENSION_RETURN_NULL);
     573             : 
     574             :         /*
     575             :          * We might be flushing buffers of already removed relations, that's
     576             :          * ok, just ignore that case.
     577             :          */
     578      163566 :         if (!v)
     579           0 :             return;
     580             : 
     581             :         /* compute offset inside the current segment */
     582      163566 :         segnum_start = blocknum / RELSEG_SIZE;
     583             : 
     584             :         /* compute number of desired writes within the current segment */
     585      163566 :         segnum_end = (blocknum + nblocks - 1) / RELSEG_SIZE;
     586      163566 :         if (segnum_start != segnum_end)
     587           0 :             nflush = RELSEG_SIZE - (blocknum % ((BlockNumber) RELSEG_SIZE));
     588             : 
     589             :         Assert(nflush >= 1);
     590             :         Assert(nflush <= nblocks);
     591             : 
     592      163566 :         seekpos = (off_t) BLCKSZ * (blocknum % ((BlockNumber) RELSEG_SIZE));
     593             : 
     594      163566 :         FileWriteback(v->mdfd_vfd, seekpos, (off_t) BLCKSZ * nflush, WAIT_EVENT_DATA_FILE_FLUSH);
     595             : 
     596      163566 :         nblocks -= nflush;
     597      163566 :         blocknum += nflush;
     598             :     }
     599             : }
     600             : 
     601             : /*
     602             :  *  mdread() -- Read the specified block from a relation.
     603             :  */
     604             : void
     605      547802 : mdread(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum,
     606             :        char *buffer)
     607             : {
     608             :     off_t       seekpos;
     609             :     int         nbytes;
     610             :     MdfdVec    *v;
     611             : 
     612             :     TRACE_POSTGRESQL_SMGR_MD_READ_START(forknum, blocknum,
     613             :                                         reln->smgr_rnode.node.spcNode,
     614             :                                         reln->smgr_rnode.node.dbNode,
     615             :                                         reln->smgr_rnode.node.relNode,
     616             :                                         reln->smgr_rnode.backend);
     617             : 
     618      547802 :     v = _mdfd_getseg(reln, forknum, blocknum, false,
     619             :                      EXTENSION_FAIL | EXTENSION_CREATE_RECOVERY);
     620             : 
     621      547802 :     seekpos = (off_t) BLCKSZ * (blocknum % ((BlockNumber) RELSEG_SIZE));
     622             : 
     623             :     Assert(seekpos < (off_t) BLCKSZ * RELSEG_SIZE);
     624             : 
     625      547802 :     nbytes = FileRead(v->mdfd_vfd, buffer, BLCKSZ, seekpos, WAIT_EVENT_DATA_FILE_READ);
     626             : 
     627             :     TRACE_POSTGRESQL_SMGR_MD_READ_DONE(forknum, blocknum,
     628             :                                        reln->smgr_rnode.node.spcNode,
     629             :                                        reln->smgr_rnode.node.dbNode,
     630             :                                        reln->smgr_rnode.node.relNode,
     631             :                                        reln->smgr_rnode.backend,
     632             :                                        nbytes,
     633             :                                        BLCKSZ);
     634             : 
     635      547802 :     if (nbytes != BLCKSZ)
     636             :     {
     637           0 :         if (nbytes < 0)
     638           0 :             ereport(ERROR,
     639             :                     (errcode_for_file_access(),
     640             :                      errmsg("could not read block %u in file \"%s\": %m",
     641             :                             blocknum, FilePathName(v->mdfd_vfd))));
     642             : 
     643             :         /*
     644             :          * Short read: we are at or past EOF, or we read a partial block at
     645             :          * EOF.  Normally this is an error; upper levels should never try to
     646             :          * read a nonexistent block.  However, if zero_damaged_pages is ON or
     647             :          * we are InRecovery, we should instead return zeroes without
     648             :          * complaining.  This allows, for example, the case of trying to
     649             :          * update a block that was later truncated away.
     650             :          */
     651           0 :         if (zero_damaged_pages || InRecovery)
     652           0 :             MemSet(buffer, 0, BLCKSZ);
     653             :         else
     654           0 :             ereport(ERROR,
     655             :                     (errcode(ERRCODE_DATA_CORRUPTED),
     656             :                      errmsg("could not read block %u in file \"%s\": read only %d of %d bytes",
     657             :                             blocknum, FilePathName(v->mdfd_vfd),
     658             :                             nbytes, BLCKSZ)));
     659             :     }
     660      547802 : }
     661             : 
     662             : /*
     663             :  *  mdwrite() -- Write the supplied block at the appropriate location.
     664             :  *
     665             :  *      This is to be used only for updating already-existing blocks of a
     666             :  *      relation (ie, those before the current EOF).  To extend a relation,
     667             :  *      use mdextend().
     668             :  */
     669             : void
     670      555044 : mdwrite(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum,
     671             :         char *buffer, bool skipFsync)
     672             : {
     673             :     off_t       seekpos;
     674             :     int         nbytes;
     675             :     MdfdVec    *v;
     676             : 
     677             :     /* This assert is too expensive to have on normally ... */
     678             : #ifdef CHECK_WRITE_VS_EXTEND
     679             :     Assert(blocknum < mdnblocks(reln, forknum));
     680             : #endif
     681             : 
     682             :     TRACE_POSTGRESQL_SMGR_MD_WRITE_START(forknum, blocknum,
     683             :                                          reln->smgr_rnode.node.spcNode,
     684             :                                          reln->smgr_rnode.node.dbNode,
     685             :                                          reln->smgr_rnode.node.relNode,
     686             :                                          reln->smgr_rnode.backend);
     687             : 
     688      555044 :     v = _mdfd_getseg(reln, forknum, blocknum, skipFsync,
     689             :                      EXTENSION_FAIL | EXTENSION_CREATE_RECOVERY);
     690             : 
     691      555044 :     seekpos = (off_t) BLCKSZ * (blocknum % ((BlockNumber) RELSEG_SIZE));
     692             : 
     693             :     Assert(seekpos < (off_t) BLCKSZ * RELSEG_SIZE);
     694             : 
     695      555044 :     nbytes = FileWrite(v->mdfd_vfd, buffer, BLCKSZ, seekpos, WAIT_EVENT_DATA_FILE_WRITE);
     696             : 
     697             :     TRACE_POSTGRESQL_SMGR_MD_WRITE_DONE(forknum, blocknum,
     698             :                                         reln->smgr_rnode.node.spcNode,
     699             :                                         reln->smgr_rnode.node.dbNode,
     700             :                                         reln->smgr_rnode.node.relNode,
     701             :                                         reln->smgr_rnode.backend,
     702             :                                         nbytes,
     703             :                                         BLCKSZ);
     704             : 
     705      555044 :     if (nbytes != BLCKSZ)
     706             :     {
     707           0 :         if (nbytes < 0)
     708           0 :             ereport(ERROR,
     709             :                     (errcode_for_file_access(),
     710             :                      errmsg("could not write block %u in file \"%s\": %m",
     711             :                             blocknum, FilePathName(v->mdfd_vfd))));
     712             :         /* short write: complain appropriately */
     713           0 :         ereport(ERROR,
     714             :                 (errcode(ERRCODE_DISK_FULL),
     715             :                  errmsg("could not write block %u in file \"%s\": wrote only %d of %d bytes",
     716             :                         blocknum,
     717             :                         FilePathName(v->mdfd_vfd),
     718             :                         nbytes, BLCKSZ),
     719             :                  errhint("Check free disk space.")));
     720             :     }
     721             : 
     722      555044 :     if (!skipFsync && !SmgrIsTemp(reln))
     723      527730 :         register_dirty_segment(reln, forknum, v);
     724      555044 : }
     725             : 
     726             : /*
     727             :  *  mdnblocks() -- Get the number of blocks stored in a relation.
     728             :  *
     729             :  *      Important side effect: all active segments of the relation are opened
     730             :  *      and added to the md_seg_fds array.  If this routine has not been
     731             :  *      called, then only segments up to the last one actually touched
     732             :  *      are present in the array.
     733             :  */
     734             : BlockNumber
     735     4393392 : mdnblocks(SMgrRelation reln, ForkNumber forknum)
     736             : {
     737     4393392 :     MdfdVec    *v = mdopenfork(reln, forknum, EXTENSION_FAIL);
     738             :     BlockNumber nblocks;
     739     4393392 :     BlockNumber segno = 0;
     740             : 
     741             :     /* mdopen has opened the first segment */
     742             :     Assert(reln->md_num_open_segs[forknum] > 0);
     743             : 
     744             :     /*
     745             :      * Start from the last open segments, to avoid redundant seeks.  We have
     746             :      * previously verified that these segments are exactly RELSEG_SIZE long,
     747             :      * and it's useless to recheck that each time.
     748             :      *
     749             :      * NOTE: this assumption could only be wrong if another backend has
     750             :      * truncated the relation.  We rely on higher code levels to handle that
     751             :      * scenario by closing and re-opening the md fd, which is handled via
     752             :      * relcache flush.  (Since the checkpointer doesn't participate in
     753             :      * relcache flush, it could have segment entries for inactive segments;
     754             :      * that's OK because the checkpointer never needs to compute relation
     755             :      * size.)
     756             :      */
     757     4393392 :     segno = reln->md_num_open_segs[forknum] - 1;
     758     4393392 :     v = &reln->md_seg_fds[forknum][segno];
     759             : 
     760             :     for (;;)
     761             :     {
     762     4393392 :         nblocks = _mdnblocks(reln, forknum, v);
     763     4393392 :         if (nblocks > ((BlockNumber) RELSEG_SIZE))
     764           0 :             elog(FATAL, "segment too big");
     765     4393392 :         if (nblocks < ((BlockNumber) RELSEG_SIZE))
     766     4393392 :             return (segno * ((BlockNumber) RELSEG_SIZE)) + nblocks;
     767             : 
     768             :         /*
     769             :          * If segment is exactly RELSEG_SIZE, advance to next one.
     770             :          */
     771           0 :         segno++;
     772             : 
     773             :         /*
     774             :          * We used to pass O_CREAT here, but that has the disadvantage that it
     775             :          * might create a segment which has vanished through some operating
     776             :          * system misadventure.  In such a case, creating the segment here
     777             :          * undermines _mdfd_getseg's attempts to notice and report an error
     778             :          * upon access to a missing segment.
     779             :          */
     780           0 :         v = _mdfd_openseg(reln, forknum, segno, 0);
     781           0 :         if (v == NULL)
     782           0 :             return segno * ((BlockNumber) RELSEG_SIZE);
     783             :     }
     784             : }
     785             : 
     786             : /*
     787             :  *  mdtruncate() -- Truncate relation to specified number of blocks.
     788             :  */
     789             : void
     790         852 : mdtruncate(SMgrRelation reln, ForkNumber forknum, BlockNumber nblocks)
     791             : {
     792             :     BlockNumber curnblk;
     793             :     BlockNumber priorblocks;
     794             :     int         curopensegs;
     795             : 
     796             :     /*
     797             :      * NOTE: mdnblocks makes sure we have opened all active segments, so that
     798             :      * truncation loop will get them all!
     799             :      */
     800         852 :     curnblk = mdnblocks(reln, forknum);
     801         852 :     if (nblocks > curnblk)
     802             :     {
     803             :         /* Bogus request ... but no complaint if InRecovery */
     804           0 :         if (InRecovery)
     805           0 :             return;
     806           0 :         ereport(ERROR,
     807             :                 (errmsg("could not truncate file \"%s\" to %u blocks: it's only %u blocks now",
     808             :                         relpath(reln->smgr_rnode, forknum),
     809             :                         nblocks, curnblk)));
     810             :     }
     811         852 :     if (nblocks == curnblk)
     812         352 :         return;                 /* no work */
     813             : 
     814             :     /*
     815             :      * Truncate segments, starting at the last one. Starting at the end makes
     816             :      * managing the memory for the fd array easier, should there be errors.
     817             :      */
     818         500 :     curopensegs = reln->md_num_open_segs[forknum];
     819        1000 :     while (curopensegs > 0)
     820             :     {
     821             :         MdfdVec    *v;
     822             : 
     823         500 :         priorblocks = (curopensegs - 1) * RELSEG_SIZE;
     824             : 
     825         500 :         v = &reln->md_seg_fds[forknum][curopensegs - 1];
     826             : 
     827         500 :         if (priorblocks > nblocks)
     828             :         {
     829             :             /*
     830             :              * This segment is no longer active. We truncate the file, but do
     831             :              * not delete it, for reasons explained in the header comments.
     832             :              */
     833           0 :             if (FileTruncate(v->mdfd_vfd, 0, WAIT_EVENT_DATA_FILE_TRUNCATE) < 0)
     834           0 :                 ereport(ERROR,
     835             :                         (errcode_for_file_access(),
     836             :                          errmsg("could not truncate file \"%s\": %m",
     837             :                                 FilePathName(v->mdfd_vfd))));
     838             : 
     839           0 :             if (!SmgrIsTemp(reln))
     840           0 :                 register_dirty_segment(reln, forknum, v);
     841             : 
     842             :             /* we never drop the 1st segment */
     843             :             Assert(v != &reln->md_seg_fds[forknum][0]);
     844             : 
     845           0 :             FileClose(v->mdfd_vfd);
     846           0 :             _fdvec_resize(reln, forknum, curopensegs - 1);
     847             :         }
     848         500 :         else if (priorblocks + ((BlockNumber) RELSEG_SIZE) > nblocks)
     849             :         {
     850             :             /*
     851             :              * This is the last segment we want to keep. Truncate the file to
     852             :              * the right length. NOTE: if nblocks is exactly a multiple K of
     853             :              * RELSEG_SIZE, we will truncate the K+1st segment to 0 length but
     854             :              * keep it. This adheres to the invariant given in the header
     855             :              * comments.
     856             :              */
     857         500 :             BlockNumber lastsegblocks = nblocks - priorblocks;
     858             : 
     859         500 :             if (FileTruncate(v->mdfd_vfd, (off_t) lastsegblocks * BLCKSZ, WAIT_EVENT_DATA_FILE_TRUNCATE) < 0)
     860           0 :                 ereport(ERROR,
     861             :                         (errcode_for_file_access(),
     862             :                          errmsg("could not truncate file \"%s\" to %u blocks: %m",
     863             :                                 FilePathName(v->mdfd_vfd),
     864             :                                 nblocks)));
     865         500 :             if (!SmgrIsTemp(reln))
     866         356 :                 register_dirty_segment(reln, forknum, v);
     867             :         }
     868             :         else
     869             :         {
     870             :             /*
     871             :              * We still need this segment, so nothing to do for this and any
     872             :              * earlier segment.
     873             :              */
     874           0 :             break;
     875             :         }
     876         500 :         curopensegs--;
     877             :     }
     878             : }
     879             : 
     880             : /*
     881             :  *  mdimmedsync() -- Immediately sync a relation to stable storage.
     882             :  *
     883             :  * Note that only writes already issued are synced; this routine knows
     884             :  * nothing of dirty buffers that may exist inside the buffer manager.  We
     885             :  * sync active and inactive segments; smgrDoPendingSyncs() relies on this.
     886             :  * Consider a relation skipping WAL.  Suppose a checkpoint syncs blocks of
     887             :  * some segment, then mdtruncate() renders that segment inactive.  If we
     888             :  * crash before the next checkpoint syncs the newly-inactive segment, that
     889             :  * segment may survive recovery, reintroducing unwanted data into the table.
     890             :  */
     891             : void
     892       70648 : mdimmedsync(SMgrRelation reln, ForkNumber forknum)
     893             : {
     894             :     int         segno;
     895             :     int         min_inactive_seg;
     896             : 
     897             :     /*
     898             :      * NOTE: mdnblocks makes sure we have opened all active segments, so that
     899             :      * fsync loop will get them all!
     900             :      */
     901       70648 :     mdnblocks(reln, forknum);
     902             : 
     903       70648 :     min_inactive_seg = segno = reln->md_num_open_segs[forknum];
     904             : 
     905             :     /*
     906             :      * Temporarily open inactive segments, then close them after sync.  There
     907             :      * may be some inactive segments left opened after fsync() error, but that
     908             :      * is harmless.  We don't bother to clean them up and take a risk of
     909             :      * further trouble.  The next mdclose() will soon close them.
     910             :      */
     911       70648 :     while (_mdfd_openseg(reln, forknum, segno, 0) != NULL)
     912           0 :         segno++;
     913             : 
     914      141296 :     while (segno > 0)
     915             :     {
     916       70648 :         MdfdVec    *v = &reln->md_seg_fds[forknum][segno - 1];
     917             : 
     918       70648 :         if (FileSync(v->mdfd_vfd, WAIT_EVENT_DATA_FILE_IMMEDIATE_SYNC) < 0)
     919           0 :             ereport(data_sync_elevel(ERROR),
     920             :                     (errcode_for_file_access(),
     921             :                      errmsg("could not fsync file \"%s\": %m",
     922             :                             FilePathName(v->mdfd_vfd))));
     923             : 
     924             :         /* Close inactive segments immediately */
     925       70648 :         if (segno > min_inactive_seg)
     926             :         {
     927           0 :             FileClose(v->mdfd_vfd);
     928           0 :             _fdvec_resize(reln, forknum, segno - 1);
     929             :         }
     930             : 
     931       70648 :         segno--;
     932             :     }
     933       70648 : }
     934             : 
     935             : /*
     936             :  * register_dirty_segment() -- Mark a relation segment as needing fsync
     937             :  *
     938             :  * If there is a local pending-ops table, just make an entry in it for
     939             :  * ProcessSyncRequests to process later.  Otherwise, try to pass off the
     940             :  * fsync request to the checkpointer process.  If that fails, just do the
     941             :  * fsync locally before returning (we hope this will not happen often
     942             :  * enough to be a performance problem).
     943             :  */
     944             : static void
     945      953320 : register_dirty_segment(SMgrRelation reln, ForkNumber forknum, MdfdVec *seg)
     946             : {
     947             :     FileTag     tag;
     948             : 
     949      953320 :     INIT_MD_FILETAG(tag, reln->smgr_rnode.node, forknum, seg->mdfd_segno);
     950             : 
     951             :     /* Temp relations should never be fsync'd */
     952             :     Assert(!SmgrIsTemp(reln));
     953             : 
     954      953320 :     if (!RegisterSyncRequest(&tag, SYNC_REQUEST, false /* retryOnError */ ))
     955             :     {
     956          50 :         ereport(DEBUG1,
     957             :                 (errmsg("could not forward fsync request because request queue is full")));
     958             : 
     959          50 :         if (FileSync(seg->mdfd_vfd, WAIT_EVENT_DATA_FILE_SYNC) < 0)
     960           0 :             ereport(data_sync_elevel(ERROR),
     961             :                     (errcode_for_file_access(),
     962             :                      errmsg("could not fsync file \"%s\": %m",
     963             :                             FilePathName(seg->mdfd_vfd))));
     964             :     }
     965      953320 : }
     966             : 
     967             : /*
     968             :  * register_unlink_segment() -- Schedule a file to be deleted after next checkpoint
     969             :  */
     970             : static void
     971       39056 : register_unlink_segment(RelFileNodeBackend rnode, ForkNumber forknum,
     972             :                         BlockNumber segno)
     973             : {
     974             :     FileTag     tag;
     975             : 
     976       39056 :     INIT_MD_FILETAG(tag, rnode.node, forknum, segno);
     977             : 
     978             :     /* Should never be used with temp relations */
     979             :     Assert(!RelFileNodeBackendIsTemp(rnode));
     980             : 
     981       39056 :     RegisterSyncRequest(&tag, SYNC_UNLINK_REQUEST, true /* retryOnError */ );
     982       39056 : }
     983             : 
     984             : /*
     985             :  * register_forget_request() -- forget any fsyncs for a relation fork's segment
     986             :  */
     987             : static void
     988      158180 : register_forget_request(RelFileNodeBackend rnode, ForkNumber forknum,
     989             :                         BlockNumber segno)
     990             : {
     991             :     FileTag     tag;
     992             : 
     993      158180 :     INIT_MD_FILETAG(tag, rnode.node, forknum, segno);
     994             : 
     995      158180 :     RegisterSyncRequest(&tag, SYNC_FORGET_REQUEST, true /* retryOnError */ );
     996      158180 : }
     997             : 
     998             : /*
     999             :  * ForgetDatabaseSyncRequests -- forget any fsyncs and unlinks for a DB
    1000             :  */
    1001             : void
    1002          20 : ForgetDatabaseSyncRequests(Oid dbid)
    1003             : {
    1004             :     FileTag     tag;
    1005             :     RelFileNode rnode;
    1006             : 
    1007          20 :     rnode.dbNode = dbid;
    1008          20 :     rnode.spcNode = 0;
    1009          20 :     rnode.relNode = 0;
    1010             : 
    1011          20 :     INIT_MD_FILETAG(tag, rnode, InvalidForkNumber, InvalidBlockNumber);
    1012             : 
    1013          20 :     RegisterSyncRequest(&tag, SYNC_FILTER_REQUEST, true /* retryOnError */ );
    1014          20 : }
    1015             : 
    1016             : /*
    1017             :  * DropRelationFiles -- drop files of all given relations
    1018             :  */
    1019             : void
    1020         148 : DropRelationFiles(RelFileNode *delrels, int ndelrels, bool isRedo)
    1021             : {
    1022             :     SMgrRelation *srels;
    1023             :     int         i;
    1024             : 
    1025         148 :     srels = palloc(sizeof(SMgrRelation) * ndelrels);
    1026         242 :     for (i = 0; i < ndelrels; i++)
    1027             :     {
    1028          94 :         SMgrRelation srel = smgropen(delrels[i], InvalidBackendId);
    1029             : 
    1030          94 :         if (isRedo)
    1031             :         {
    1032             :             ForkNumber  fork;
    1033             : 
    1034         400 :             for (fork = 0; fork <= MAX_FORKNUM; fork++)
    1035         320 :                 XLogDropRelation(delrels[i], fork);
    1036             :         }
    1037          94 :         srels[i] = srel;
    1038             :     }
    1039             : 
    1040         148 :     smgrdounlinkall(srels, ndelrels, isRedo);
    1041             : 
    1042         242 :     for (i = 0; i < ndelrels; i++)
    1043          94 :         smgrclose(srels[i]);
    1044         148 :     pfree(srels);
    1045         148 : }
    1046             : 
    1047             : 
    1048             : /*
    1049             :  *  _fdvec_resize() -- Resize the fork's open segments array
    1050             :  */
    1051             : static void
    1052     2107442 : _fdvec_resize(SMgrRelation reln,
    1053             :               ForkNumber forknum,
    1054             :               int nseg)
    1055             : {
    1056     2107442 :     if (nseg == 0)
    1057             :     {
    1058      915434 :         if (reln->md_num_open_segs[forknum] > 0)
    1059             :         {
    1060      915434 :             pfree(reln->md_seg_fds[forknum]);
    1061      915434 :             reln->md_seg_fds[forknum] = NULL;
    1062             :         }
    1063             :     }
    1064     1192008 :     else if (reln->md_num_open_segs[forknum] == 0)
    1065             :     {
    1066     1192008 :         reln->md_seg_fds[forknum] =
    1067     1192008 :             MemoryContextAlloc(MdCxt, sizeof(MdfdVec) * nseg);
    1068             :     }
    1069             :     else
    1070             :     {
    1071             :         /*
    1072             :          * It doesn't seem worthwhile complicating the code to amortize
    1073             :          * repalloc() calls.  Those are far faster than PathNameOpenFile() or
    1074             :          * FileClose(), and the memory context internally will sometimes avoid
    1075             :          * doing an actual reallocation.
    1076             :          */
    1077           0 :         reln->md_seg_fds[forknum] =
    1078           0 :             repalloc(reln->md_seg_fds[forknum],
    1079             :                      sizeof(MdfdVec) * nseg);
    1080             :     }
    1081             : 
    1082     2107442 :     reln->md_num_open_segs[forknum] = nseg;
    1083     2107442 : }
    1084             : 
    1085             : /*
    1086             :  * Return the filename for the specified segment of the relation. The
    1087             :  * returned string is palloc'd.
    1088             :  */
    1089             : static char *
    1090       70652 : _mdfd_segpath(SMgrRelation reln, ForkNumber forknum, BlockNumber segno)
    1091             : {
    1092             :     char       *path,
    1093             :                *fullpath;
    1094             : 
    1095       70652 :     path = relpath(reln->smgr_rnode, forknum);
    1096             : 
    1097       70652 :     if (segno > 0)
    1098             :     {
    1099       70648 :         fullpath = psprintf("%s.%u", path, segno);
    1100       70648 :         pfree(path);
    1101             :     }
    1102             :     else
    1103           4 :         fullpath = path;
    1104             : 
    1105       70652 :     return fullpath;
    1106             : }
    1107             : 
    1108             : /*
    1109             :  * Open the specified segment of the relation,
    1110             :  * and make a MdfdVec object for it.  Returns NULL on failure.
    1111             :  */
    1112             : static MdfdVec *
    1113       70648 : _mdfd_openseg(SMgrRelation reln, ForkNumber forknum, BlockNumber segno,
    1114             :               int oflags)
    1115             : {
    1116             :     MdfdVec    *v;
    1117             :     File        fd;
    1118             :     char       *fullpath;
    1119             : 
    1120       70648 :     fullpath = _mdfd_segpath(reln, forknum, segno);
    1121             : 
    1122             :     /* open the file */
    1123       70648 :     fd = PathNameOpenFile(fullpath, O_RDWR | PG_BINARY | oflags);
    1124             : 
    1125       70648 :     pfree(fullpath);
    1126             : 
    1127       70648 :     if (fd < 0)
    1128       70648 :         return NULL;
    1129             : 
    1130             :     /*
    1131             :      * Segments are always opened in order from lowest to highest, so we must
    1132             :      * be adding a new one at the end.
    1133             :      */
    1134             :     Assert(segno == reln->md_num_open_segs[forknum]);
    1135             : 
    1136           0 :     _fdvec_resize(reln, forknum, segno + 1);
    1137             : 
    1138             :     /* fill the entry */
    1139           0 :     v = &reln->md_seg_fds[forknum][segno];
    1140           0 :     v->mdfd_vfd = fd;
    1141           0 :     v->mdfd_segno = segno;
    1142             : 
    1143             :     Assert(_mdnblocks(reln, forknum, v) <= ((BlockNumber) RELSEG_SIZE));
    1144             : 
    1145             :     /* all done */
    1146           0 :     return v;
    1147             : }
    1148             : 
    1149             : /*
    1150             :  *  _mdfd_getseg() -- Find the segment of the relation holding the
    1151             :  *      specified block.
    1152             :  *
    1153             :  * If the segment doesn't exist, we ereport, return NULL, or create the
    1154             :  * segment, according to "behavior".  Note: skipFsync is only used in the
    1155             :  * EXTENSION_CREATE case.
    1156             :  */
    1157             : static MdfdVec *
    1158     1866600 : _mdfd_getseg(SMgrRelation reln, ForkNumber forknum, BlockNumber blkno,
    1159             :              bool skipFsync, int behavior)
    1160             : {
    1161             :     MdfdVec    *v;
    1162             :     BlockNumber targetseg;
    1163             :     BlockNumber nextsegno;
    1164             : 
    1165             :     /* some way to handle non-existent segments needs to be specified */
    1166             :     Assert(behavior &
    1167             :            (EXTENSION_FAIL | EXTENSION_CREATE | EXTENSION_RETURN_NULL));
    1168             : 
    1169     1866600 :     targetseg = blkno / ((BlockNumber) RELSEG_SIZE);
    1170             : 
    1171             :     /* if an existing and opened segment, we're done */
    1172     1866600 :     if (targetseg < reln->md_num_open_segs[forknum])
    1173             :     {
    1174     1681632 :         v = &reln->md_seg_fds[forknum][targetseg];
    1175     1681632 :         return v;
    1176             :     }
    1177             : 
    1178             :     /*
    1179             :      * The target segment is not yet open. Iterate over all the segments
    1180             :      * between the last opened and the target segment. This way missing
    1181             :      * segments either raise an error, or get created (according to
    1182             :      * 'behavior'). Start with either the last opened, or the first segment if
    1183             :      * none was opened before.
    1184             :      */
    1185      184968 :     if (reln->md_num_open_segs[forknum] > 0)
    1186           0 :         v = &reln->md_seg_fds[forknum][reln->md_num_open_segs[forknum] - 1];
    1187             :     else
    1188             :     {
    1189      184968 :         v = mdopenfork(reln, forknum, behavior);
    1190      184968 :         if (!v)
    1191           0 :             return NULL;        /* if behavior & EXTENSION_RETURN_NULL */
    1192             :     }
    1193             : 
    1194      184968 :     for (nextsegno = reln->md_num_open_segs[forknum];
    1195           0 :          nextsegno <= targetseg; nextsegno++)
    1196             :     {
    1197           0 :         BlockNumber nblocks = _mdnblocks(reln, forknum, v);
    1198           0 :         int         flags = 0;
    1199             : 
    1200             :         Assert(nextsegno == v->mdfd_segno + 1);
    1201             : 
    1202           0 :         if (nblocks > ((BlockNumber) RELSEG_SIZE))
    1203           0 :             elog(FATAL, "segment too big");
    1204             : 
    1205           0 :         if ((behavior & EXTENSION_CREATE) ||
    1206           0 :             (InRecovery && (behavior & EXTENSION_CREATE_RECOVERY)))
    1207             :         {
    1208             :             /*
    1209             :              * Normally we will create new segments only if authorized by the
    1210             :              * caller (i.e., we are doing mdextend()).  But when doing WAL
    1211             :              * recovery, create segments anyway; this allows cases such as
    1212             :              * replaying WAL data that has a write into a high-numbered
    1213             :              * segment of a relation that was later deleted. We want to go
    1214             :              * ahead and create the segments so we can finish out the replay.
    1215             :              *
    1216             :              * We have to maintain the invariant that segments before the last
    1217             :              * active segment are of size RELSEG_SIZE; therefore, if
    1218             :              * extending, pad them out with zeroes if needed.  (This only
    1219             :              * matters if in recovery, or if the caller is extending the
    1220             :              * relation discontiguously, but that can happen in hash indexes.)
    1221             :              */
    1222           0 :             if (nblocks < ((BlockNumber) RELSEG_SIZE))
    1223             :             {
    1224           0 :                 char       *zerobuf = palloc0(BLCKSZ);
    1225             : 
    1226           0 :                 mdextend(reln, forknum,
    1227           0 :                          nextsegno * ((BlockNumber) RELSEG_SIZE) - 1,
    1228             :                          zerobuf, skipFsync);
    1229           0 :                 pfree(zerobuf);
    1230             :             }
    1231           0 :             flags = O_CREAT;
    1232             :         }
    1233           0 :         else if (!(behavior & EXTENSION_DONT_CHECK_SIZE) &&
    1234             :                  nblocks < ((BlockNumber) RELSEG_SIZE))
    1235             :         {
    1236             :             /*
    1237             :              * When not extending (or explicitly including truncated
    1238             :              * segments), only open the next segment if the current one is
    1239             :              * exactly RELSEG_SIZE.  If not (this branch), either return NULL
    1240             :              * or fail.
    1241             :              */
    1242           0 :             if (behavior & EXTENSION_RETURN_NULL)
    1243             :             {
    1244             :                 /*
    1245             :                  * Some callers discern between reasons for _mdfd_getseg()
    1246             :                  * returning NULL based on errno. As there's no failing
    1247             :                  * syscall involved in this case, explicitly set errno to
    1248             :                  * ENOENT, as that seems the closest interpretation.
    1249             :                  */
    1250           0 :                 errno = ENOENT;
    1251           0 :                 return NULL;
    1252             :             }
    1253             : 
    1254           0 :             ereport(ERROR,
    1255             :                     (errcode_for_file_access(),
    1256             :                      errmsg("could not open file \"%s\" (target block %u): previous segment is only %u blocks",
    1257             :                             _mdfd_segpath(reln, forknum, nextsegno),
    1258             :                             blkno, nblocks)));
    1259             :         }
    1260             : 
    1261           0 :         v = _mdfd_openseg(reln, forknum, nextsegno, flags);
    1262             : 
    1263           0 :         if (v == NULL)
    1264             :         {
    1265           0 :             if ((behavior & EXTENSION_RETURN_NULL) &&
    1266           0 :                 FILE_POSSIBLY_DELETED(errno))
    1267           0 :                 return NULL;
    1268           0 :             ereport(ERROR,
    1269             :                     (errcode_for_file_access(),
    1270             :                      errmsg("could not open file \"%s\" (target block %u): %m",
    1271             :                             _mdfd_segpath(reln, forknum, nextsegno),
    1272             :                             blkno)));
    1273             :         }
    1274             :     }
    1275             : 
    1276      184968 :     return v;
    1277             : }
    1278             : 
    1279             : /*
    1280             :  * Get number of blocks present in a single disk file
    1281             :  */
    1282             : static BlockNumber
    1283     4393392 : _mdnblocks(SMgrRelation reln, ForkNumber forknum, MdfdVec *seg)
    1284             : {
    1285             :     off_t       len;
    1286             : 
    1287     4393392 :     len = FileSize(seg->mdfd_vfd);
    1288     4393392 :     if (len < 0)
    1289           0 :         ereport(ERROR,
    1290             :                 (errcode_for_file_access(),
    1291             :                  errmsg("could not seek to end of file \"%s\": %m",
    1292             :                         FilePathName(seg->mdfd_vfd))));
    1293             :     /* note that this calculation will ignore any partial block at EOF */
    1294     4393392 :     return (BlockNumber) (len / BLCKSZ);
    1295             : }
    1296             : 
    1297             : /*
    1298             :  * Sync a file to disk, given a file tag.  Write the path into an output
    1299             :  * buffer so the caller can use it in error messages.
    1300             :  *
    1301             :  * Return 0 on success, -1 on failure, with errno set.
    1302             :  */
    1303             : int
    1304          62 : mdsyncfiletag(const FileTag *ftag, char *path)
    1305             : {
    1306          62 :     SMgrRelation reln = smgropen(ftag->rnode, InvalidBackendId);
    1307             :     File        file;
    1308             :     bool        need_to_close;
    1309             :     int         result,
    1310             :                 save_errno;
    1311             : 
    1312             :     /* See if we already have the file open, or need to open it. */
    1313          62 :     if (ftag->segno < reln->md_num_open_segs[ftag->forknum])
    1314             :     {
    1315          58 :         file = reln->md_seg_fds[ftag->forknum][ftag->segno].mdfd_vfd;
    1316          58 :         strlcpy(path, FilePathName(file), MAXPGPATH);
    1317          58 :         need_to_close = false;
    1318             :     }
    1319             :     else
    1320             :     {
    1321             :         char       *p;
    1322             : 
    1323           4 :         p = _mdfd_segpath(reln, ftag->forknum, ftag->segno);
    1324           4 :         strlcpy(path, p, MAXPGPATH);
    1325           4 :         pfree(p);
    1326             : 
    1327           4 :         file = PathNameOpenFile(path, O_RDWR | PG_BINARY);
    1328           4 :         if (file < 0)
    1329           0 :             return -1;
    1330           4 :         need_to_close = true;
    1331             :     }
    1332             : 
    1333             :     /* Sync the file. */
    1334          62 :     result = FileSync(file, WAIT_EVENT_DATA_FILE_SYNC);
    1335          62 :     save_errno = errno;
    1336             : 
    1337          62 :     if (need_to_close)
    1338           4 :         FileClose(file);
    1339             : 
    1340          62 :     errno = save_errno;
    1341          62 :     return result;
    1342             : }
    1343             : 
    1344             : /*
    1345             :  * Unlink a file, given a file tag.  Write the path into an output
    1346             :  * buffer so the caller can use it in error messages.
    1347             :  *
    1348             :  * Return 0 on success, -1 on failure, with errno set.
    1349             :  */
    1350             : int
    1351       33502 : mdunlinkfiletag(const FileTag *ftag, char *path)
    1352             : {
    1353             :     char       *p;
    1354             : 
    1355             :     /* Compute the path. */
    1356       33502 :     p = relpathperm(ftag->rnode, MAIN_FORKNUM);
    1357       33502 :     strlcpy(path, p, MAXPGPATH);
    1358       33502 :     pfree(p);
    1359             : 
    1360             :     /* Try to unlink the file. */
    1361       33502 :     return unlink(path);
    1362             : }
    1363             : 
    1364             : /*
    1365             :  * Check if a given candidate request matches a given tag, when processing
    1366             :  * a SYNC_FILTER_REQUEST request.  This will be called for all pending
    1367             :  * requests to find out whether to forget them.
    1368             :  */
    1369             : bool
    1370           8 : mdfiletagmatches(const FileTag *ftag, const FileTag *candidate)
    1371             : {
    1372             :     /*
    1373             :      * For now we only use filter requests as a way to drop all scheduled
    1374             :      * callbacks relating to a given database, when dropping the database.
    1375             :      * We'll return true for all candidates that have the same database OID as
    1376             :      * the ftag from the SYNC_FILTER_REQUEST request, so they're forgotten.
    1377             :      */
    1378           8 :     return ftag->rnode.dbNode == candidate->rnode.dbNode;
    1379             : }

Generated by: LCOV version 1.13