]> granicus.if.org Git - postgresql/blobdiff - src/backend/storage/smgr/md.c
Update copyright for 2019
[postgresql] / src / backend / storage / smgr / md.c
index 53d9188e18b443bdf127fb3b01ca4ac568a4086c..e4501ff9bc909712c7316c0937537991f3e5734a 100644 (file)
@@ -10,7 +10,7 @@
  * It doesn't matter whether the bits are on spinning rust or some other
  * storage technology.
  *
- * Portions Copyright (c) 1996-2014, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1996-2019, PostgreSQL Global Development Group
  * Portions Copyright (c) 1994, Regents of the University of California
  *
  *
@@ -26,8 +26,9 @@
 #include <sys/file.h>
 
 #include "miscadmin.h"
+#include "access/xlogutils.h"
 #include "access/xlog.h"
-#include "catalog/catalog.h"
+#include "pgstat.h"
 #include "portability/instr_time.h"
 #include "postmaster/bgwriter.h"
 #include "storage/fd.h"
  *     out to an unlinked old copy of a segment file that will eventually
  *     disappear.
  *
- *     The file descriptor pointer (md_fd field) stored in the SMgrRelation
- *     cache is, therefore, just the head of a list of MdfdVec objects, one
- *     per segment.  But note the md_fd pointer can be NULL, indicating
- *     relation not open.
- *
- *     Also note that mdfd_chain == NULL does not necessarily mean the relation
- *     doesn't have another segment after this one; we may just not have
- *     opened the next segment yet.  (We could not have "all segments are
- *     in the chain" as an invariant anyway, since another backend could
- *     extend the relation when we weren't looking.)  We do not make chain
+ *     File descriptors are stored in the per-fork md_seg_fds arrays inside
+ *     SMgrRelation. The length of these arrays is stored in md_num_open_segs.
+ *     Note that a fork's md_num_open_segs having a specific value does not
+ *     necessarily mean the relation doesn't have additional segments; we may
+ *     just not have opened the next segment yet.  (We could not have "all
+ *     segments are in the array" as an invariant anyway, since another backend
+ *     could extend the relation while we aren't looking.)  We do not have
  *     entries for inactive segments, however; as soon as we find a partial
  *     segment, we assume that any subsequent segments are inactive.
  *
- *     All MdfdVec objects are palloc'd in the MdCxt memory context.
+ *     The entire MdfdVec array is palloc'd in the MdCxt memory context.
  */
 
 typedef struct _MdfdVec
 {
        File            mdfd_vfd;               /* fd number in fd.c's pool */
        BlockNumber mdfd_segno;         /* segment number, from 0 */
-       struct _MdfdVec *mdfd_chain;    /* next segment, or NULL */
 } MdfdVec;
 
 static MemoryContext MdCxt;            /* context for all MdfdVec objects */
@@ -157,34 +154,47 @@ typedef struct
 
 static HTAB *pendingOpsTable = NULL;
 static List *pendingUnlinks = NIL;
-static MemoryContext pendingOpsCxt;            /* context for the above  */
+static MemoryContext pendingOpsCxt; /* context for the above  */
 
 static CycleCtr mdsync_cycle_ctr = 0;
 static CycleCtr mdckpt_cycle_ctr = 0;
 
 
-typedef enum                                   /* behavior for mdopen & _mdfd_getseg */
-{
-       EXTENSION_FAIL,                         /* ereport if segment not present */
-       EXTENSION_RETURN_NULL,          /* return NULL if not present */
-       EXTENSION_CREATE                        /* create new segments as needed */
-} ExtensionBehavior;
+/*** behavior for mdopen & _mdfd_getseg ***/
+/* ereport if segment not present */
+#define EXTENSION_FAIL                         (1 << 0)
+/* return NULL if segment not present */
+#define EXTENSION_RETURN_NULL          (1 << 1)
+/* create new segments as needed */
+#define EXTENSION_CREATE                       (1 << 2)
+/* create new segments if needed during recovery */
+#define EXTENSION_CREATE_RECOVERY      (1 << 3)
+/*
+ * Allow opening segments which are preceded by segments smaller than
+ * RELSEG_SIZE, e.g. inactive segments (see above). Note that this is breaks
+ * mdnblocks() and related functionality henceforth - which currently is ok,
+ * because this is only required in the checkpointer which never uses
+ * mdnblocks().
+ */
+#define EXTENSION_DONT_CHECK_SIZE      (1 << 4)
+
 
 /* local routines */
 static void mdunlinkfork(RelFileNodeBackend rnode, ForkNumber forkNum,
                         bool isRedo);
-static MdfdVec *mdopen(SMgrRelation reln, ForkNumber forknum,
-          ExtensionBehavior behavior);
+static MdfdVec *mdopen(SMgrRelation reln, ForkNumber forknum, int behavior);
 static void register_dirty_segment(SMgrRelation reln, ForkNumber forknum,
                                           MdfdVec *seg);
 static void register_unlink(RelFileNodeBackend rnode);
-static MdfdVec *_fdvec_alloc(void);
+static void _fdvec_resize(SMgrRelation reln,
+                         ForkNumber forknum,
+                         int nseg);
 static char *_mdfd_segpath(SMgrRelation reln, ForkNumber forknum,
                          BlockNumber segno);
 static MdfdVec *_mdfd_openseg(SMgrRelation reln, ForkNumber forkno,
                          BlockNumber segno, int oflags);
 static MdfdVec *_mdfd_getseg(SMgrRelation reln, ForkNumber forkno,
-                        BlockNumber blkno, bool skipFsync, ExtensionBehavior behavior);
+                        BlockNumber blkno, bool skipFsync, int behavior);
 static BlockNumber _mdnblocks(SMgrRelation reln, ForkNumber forknum,
                   MdfdVec *seg);
 
@@ -197,9 +207,7 @@ mdinit(void)
 {
        MdCxt = AllocSetContextCreate(TopMemoryContext,
                                                                  "MdSmgr",
-                                                                 ALLOCSET_DEFAULT_MINSIZE,
-                                                                 ALLOCSET_DEFAULT_INITSIZE,
-                                                                 ALLOCSET_DEFAULT_MAXSIZE);
+                                                                 ALLOCSET_DEFAULT_SIZES);
 
        /*
         * Create pending-operations hashtable if we need it.  Currently, we need
@@ -213,17 +221,15 @@ mdinit(void)
                /*
                 * XXX: The checkpointer needs to add entries to the pending ops table
                 * when absorbing fsync requests.  That is done within a critical
-                * section, which isn't usually allowed, but we make an exception.
-                * It means that there's a theoretical possibility that you run out of
+                * section, which isn't usually allowed, but we make an exception. It
+                * means that there's a theoretical possibility that you run out of
                 * memory while absorbing fsync requests, which leads to a PANIC.
                 * Fortunately the hash table is small so that's unlikely to happen in
                 * practice.
                 */
                pendingOpsCxt = AllocSetContextCreate(MdCxt,
-                                                                                         "Pending Ops Context",
-                                                                                         ALLOCSET_DEFAULT_MINSIZE,
-                                                                                         ALLOCSET_DEFAULT_INITSIZE,
-                                                                                         ALLOCSET_DEFAULT_MAXSIZE);
+                                                                                         "Pending ops context",
+                                                                                         ALLOCSET_DEFAULT_SIZES);
                MemoryContextAllowInCriticalSection(pendingOpsCxt, true);
 
                MemSet(&hash_ctl, 0, sizeof(hash_ctl));
@@ -287,17 +293,18 @@ mdexists(SMgrRelation reln, ForkNumber forkNum)
 void
 mdcreate(SMgrRelation reln, ForkNumber forkNum, bool isRedo)
 {
+       MdfdVec    *mdfd;
        char       *path;
        File            fd;
 
-       if (isRedo && reln->md_fd[forkNum] != NULL)
+       if (isRedo && reln->md_num_open_segs[forkNum] > 0)
                return;                                 /* created and opened already... */
 
-       Assert(reln->md_fd[forkNum] == NULL);
+       Assert(reln->md_num_open_segs[forkNum] == 0);
 
        path = relpath(reln->smgr_rnode, forkNum);
 
-       fd = PathNameOpenFile(path, O_RDWR | O_CREAT | O_EXCL | PG_BINARY, 0600);
+       fd = PathNameOpenFile(path, O_RDWR | O_CREAT | O_EXCL | PG_BINARY);
 
        if (fd < 0)
        {
@@ -310,7 +317,7 @@ mdcreate(SMgrRelation reln, ForkNumber forkNum, bool isRedo)
                 * already, even if isRedo is not set.  (See also mdopen)
                 */
                if (isRedo || IsBootstrapProcessingMode())
-                       fd = PathNameOpenFile(path, O_RDWR | PG_BINARY, 0600);
+                       fd = PathNameOpenFile(path, O_RDWR | PG_BINARY);
                if (fd < 0)
                {
                        /* be sure to report the error reported by create, not open */
@@ -323,11 +330,10 @@ mdcreate(SMgrRelation reln, ForkNumber forkNum, bool isRedo)
 
        pfree(path);
 
-       reln->md_fd[forkNum] = _fdvec_alloc();
-
-       reln->md_fd[forkNum]->mdfd_vfd = fd;
-       reln->md_fd[forkNum]->mdfd_segno = 0;
-       reln->md_fd[forkNum]->mdfd_chain = NULL;
+       _fdvec_resize(reln, forkNum, 1);
+       mdfd = &reln->md_seg_fds[forkNum][0];
+       mdfd->mdfd_vfd = fd;
+       mdfd->mdfd_segno = 0;
 }
 
 /*
@@ -424,7 +430,7 @@ mdunlinkfork(RelFileNodeBackend rnode, ForkNumber forkNum, bool isRedo)
                /* truncate(2) would be easier here, but Windows hasn't got it */
                int                     fd;
 
-               fd = OpenTransientFile(path, O_RDWR | PG_BINARY, 0);
+               fd = OpenTransientFile(path, O_RDWR | PG_BINARY);
                if (fd >= 0)
                {
                        int                     save_errno;
@@ -466,7 +472,7 @@ mdunlinkfork(RelFileNodeBackend rnode, ForkNumber forkNum, bool isRedo)
                                if (errno != ENOENT)
                                        ereport(WARNING,
                                                        (errcode_for_file_access(),
-                                          errmsg("could not remove file \"%s\": %m", segpath)));
+                                                        errmsg("could not remove file \"%s\": %m", segpath)));
                                break;
                        }
                }
@@ -512,26 +518,11 @@ mdextend(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum,
 
        v = _mdfd_getseg(reln, forknum, blocknum, skipFsync, EXTENSION_CREATE);
 
-       seekpos = (off_t) BLCKSZ *(blocknum % ((BlockNumber) RELSEG_SIZE));
+       seekpos = (off_t) BLCKSZ * (blocknum % ((BlockNumber) RELSEG_SIZE));
 
        Assert(seekpos < (off_t) BLCKSZ * RELSEG_SIZE);
 
-       /*
-        * Note: because caller usually obtained blocknum by calling mdnblocks,
-        * which did a seek(SEEK_END), this seek is often redundant and will be
-        * optimized away by fd.c.  It's not redundant, however, if there is a
-        * partial page at the end of the file. In that case we want to try to
-        * overwrite the partial page with a full page.  It's also not redundant
-        * if bufmgr.c had to dump another buffer of the same file to make room
-        * for the new page's buffer.
-        */
-       if (FileSeek(v->mdfd_vfd, seekpos, SEEK_SET) != seekpos)
-               ereport(ERROR,
-                               (errcode_for_file_access(),
-                                errmsg("could not seek to block %u in file \"%s\": %m",
-                                               blocknum, FilePathName(v->mdfd_vfd))));
-
-       if ((nbytes = FileWrite(v->mdfd_vfd, buffer, BLCKSZ)) != BLCKSZ)
+       if ((nbytes = FileWrite(v->mdfd_vfd, buffer, BLCKSZ, seekpos, WAIT_EVENT_DATA_FILE_EXTEND)) != BLCKSZ)
        {
                if (nbytes < 0)
                        ereport(ERROR,
@@ -565,19 +556,19 @@ mdextend(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum,
  * invent one out of whole cloth.
  */
 static MdfdVec *
-mdopen(SMgrRelation reln, ForkNumber forknum, ExtensionBehavior behavior)
+mdopen(SMgrRelation reln, ForkNumber forknum, int behavior)
 {
        MdfdVec    *mdfd;
        char       *path;
        File            fd;
 
        /* No work if already open */
-       if (reln->md_fd[forknum])
-               return reln->md_fd[forknum];
+       if (reln->md_num_open_segs[forknum] > 0)
+               return &reln->md_seg_fds[forknum][0];
 
        path = relpath(reln->smgr_rnode, forknum);
 
-       fd = PathNameOpenFile(path, O_RDWR | PG_BINARY, 0600);
+       fd = PathNameOpenFile(path, O_RDWR | PG_BINARY);
 
        if (fd < 0)
        {
@@ -588,10 +579,10 @@ mdopen(SMgrRelation reln, ForkNumber forknum, ExtensionBehavior behavior)
                 * substitute for mdcreate() in bootstrap mode only. (See mdcreate)
                 */
                if (IsBootstrapProcessingMode())
-                       fd = PathNameOpenFile(path, O_RDWR | O_CREAT | O_EXCL | PG_BINARY, 0600);
+                       fd = PathNameOpenFile(path, O_RDWR | O_CREAT | O_EXCL | PG_BINARY);
                if (fd < 0)
                {
-                       if (behavior == EXTENSION_RETURN_NULL &&
+                       if ((behavior & EXTENSION_RETURN_NULL) &&
                                FILE_POSSIBLY_DELETED(errno))
                        {
                                pfree(path);
@@ -605,11 +596,11 @@ mdopen(SMgrRelation reln, ForkNumber forknum, ExtensionBehavior behavior)
 
        pfree(path);
 
-       reln->md_fd[forknum] = mdfd = _fdvec_alloc();
-
+       _fdvec_resize(reln, forknum, 1);
+       mdfd = &reln->md_seg_fds[forknum][0];
        mdfd->mdfd_vfd = fd;
        mdfd->mdfd_segno = 0;
-       mdfd->mdfd_chain = NULL;
+
        Assert(_mdnblocks(reln, forknum, mdfd) <= ((BlockNumber) RELSEG_SIZE));
 
        return mdfd;
@@ -621,25 +612,29 @@ mdopen(SMgrRelation reln, ForkNumber forknum, ExtensionBehavior behavior)
 void
 mdclose(SMgrRelation reln, ForkNumber forknum)
 {
-       MdfdVec    *v = reln->md_fd[forknum];
+       int                     nopensegs = reln->md_num_open_segs[forknum];
 
        /* No work if already closed */
-       if (v == NULL)
+       if (nopensegs == 0)
                return;
 
-       reln->md_fd[forknum] = NULL;    /* prevent dangling pointer after error */
-
-       while (v != NULL)
+       /* close segments starting from the end */
+       while (nopensegs > 0)
        {
-               MdfdVec    *ov = v;
+               MdfdVec    *v = &reln->md_seg_fds[forknum][nopensegs - 1];
 
                /* if not closed already */
                if (v->mdfd_vfd >= 0)
+               {
                        FileClose(v->mdfd_vfd);
-               /* Now free vector */
-               v = v->mdfd_chain;
-               pfree(ov);
+                       v->mdfd_vfd = -1;
+               }
+
+               nopensegs--;
        }
+
+       /* resize just once, avoids pointless reallocations */
+       _fdvec_resize(reln, forknum, 0);
 }
 
 /*
@@ -654,14 +649,65 @@ mdprefetch(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum)
 
        v = _mdfd_getseg(reln, forknum, blocknum, false, EXTENSION_FAIL);
 
-       seekpos = (off_t) BLCKSZ *(blocknum % ((BlockNumber) RELSEG_SIZE));
+       seekpos = (off_t) BLCKSZ * (blocknum % ((BlockNumber) RELSEG_SIZE));
 
        Assert(seekpos < (off_t) BLCKSZ * RELSEG_SIZE);
 
-       (void) FilePrefetch(v->mdfd_vfd, seekpos, BLCKSZ);
-#endif   /* USE_PREFETCH */
+       (void) FilePrefetch(v->mdfd_vfd, seekpos, BLCKSZ, WAIT_EVENT_DATA_FILE_PREFETCH);
+#endif                                                 /* USE_PREFETCH */
 }
 
+/*
+ * mdwriteback() -- Tell the kernel to write pages back to storage.
+ *
+ * This accepts a range of blocks because flushing several pages at once is
+ * considerably more efficient than doing so individually.
+ */
+void
+mdwriteback(SMgrRelation reln, ForkNumber forknum,
+                       BlockNumber blocknum, BlockNumber nblocks)
+{
+       /*
+        * Issue flush requests in as few requests as possible; have to split at
+        * segment boundaries though, since those are actually separate files.
+        */
+       while (nblocks > 0)
+       {
+               BlockNumber nflush = nblocks;
+               off_t           seekpos;
+               MdfdVec    *v;
+               int                     segnum_start,
+                                       segnum_end;
+
+               v = _mdfd_getseg(reln, forknum, blocknum, true /* not used */ ,
+                                                EXTENSION_RETURN_NULL);
+
+               /*
+                * We might be flushing buffers of already removed relations, that's
+                * ok, just ignore that case.
+                */
+               if (!v)
+                       return;
+
+               /* compute offset inside the current segment */
+               segnum_start = blocknum / RELSEG_SIZE;
+
+               /* compute number of desired writes within the current segment */
+               segnum_end = (blocknum + nblocks - 1) / RELSEG_SIZE;
+               if (segnum_start != segnum_end)
+                       nflush = RELSEG_SIZE - (blocknum % ((BlockNumber) RELSEG_SIZE));
+
+               Assert(nflush >= 1);
+               Assert(nflush <= nblocks);
+
+               seekpos = (off_t) BLCKSZ * (blocknum % ((BlockNumber) RELSEG_SIZE));
+
+               FileWriteback(v->mdfd_vfd, seekpos, (off_t) BLCKSZ * nflush, WAIT_EVENT_DATA_FILE_FLUSH);
+
+               nblocks -= nflush;
+               blocknum += nflush;
+       }
+}
 
 /*
  *     mdread() -- Read the specified block from a relation.
@@ -680,19 +726,14 @@ mdread(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum,
                                                                                reln->smgr_rnode.node.relNode,
                                                                                reln->smgr_rnode.backend);
 
-       v = _mdfd_getseg(reln, forknum, blocknum, false, EXTENSION_FAIL);
+       v = _mdfd_getseg(reln, forknum, blocknum, false,
+                                        EXTENSION_FAIL | EXTENSION_CREATE_RECOVERY);
 
-       seekpos = (off_t) BLCKSZ *(blocknum % ((BlockNumber) RELSEG_SIZE));
+       seekpos = (off_t) BLCKSZ * (blocknum % ((BlockNumber) RELSEG_SIZE));
 
        Assert(seekpos < (off_t) BLCKSZ * RELSEG_SIZE);
 
-       if (FileSeek(v->mdfd_vfd, seekpos, SEEK_SET) != seekpos)
-               ereport(ERROR,
-                               (errcode_for_file_access(),
-                                errmsg("could not seek to block %u in file \"%s\": %m",
-                                               blocknum, FilePathName(v->mdfd_vfd))));
-
-       nbytes = FileRead(v->mdfd_vfd, buffer, BLCKSZ);
+       nbytes = FileRead(v->mdfd_vfd, buffer, BLCKSZ, seekpos, WAIT_EVENT_DATA_FILE_READ);
 
        TRACE_POSTGRESQL_SMGR_MD_READ_DONE(forknum, blocknum,
                                                                           reln->smgr_rnode.node.spcNode,
@@ -755,19 +796,14 @@ mdwrite(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum,
                                                                                 reln->smgr_rnode.node.relNode,
                                                                                 reln->smgr_rnode.backend);
 
-       v = _mdfd_getseg(reln, forknum, blocknum, skipFsync, EXTENSION_FAIL);
+       v = _mdfd_getseg(reln, forknum, blocknum, skipFsync,
+                                        EXTENSION_FAIL | EXTENSION_CREATE_RECOVERY);
 
-       seekpos = (off_t) BLCKSZ *(blocknum % ((BlockNumber) RELSEG_SIZE));
+       seekpos = (off_t) BLCKSZ * (blocknum % ((BlockNumber) RELSEG_SIZE));
 
        Assert(seekpos < (off_t) BLCKSZ * RELSEG_SIZE);
 
-       if (FileSeek(v->mdfd_vfd, seekpos, SEEK_SET) != seekpos)
-               ereport(ERROR,
-                               (errcode_for_file_access(),
-                                errmsg("could not seek to block %u in file \"%s\": %m",
-                                               blocknum, FilePathName(v->mdfd_vfd))));
-
-       nbytes = FileWrite(v->mdfd_vfd, buffer, BLCKSZ);
+       nbytes = FileWrite(v->mdfd_vfd, buffer, BLCKSZ, seekpos, WAIT_EVENT_DATA_FILE_WRITE);
 
        TRACE_POSTGRESQL_SMGR_MD_WRITE_DONE(forknum, blocknum,
                                                                                reln->smgr_rnode.node.spcNode,
@@ -802,9 +838,9 @@ mdwrite(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum,
  *     mdnblocks() -- Get the number of blocks stored in a relation.
  *
  *             Important side effect: all active segments of the relation are opened
- *             and added to the mdfd_chain list.  If this routine has not been
+ *             and added to the mdfd_seg_fds array.  If this routine has not been
  *             called, then only segments up to the last one actually touched
- *             are present in the chain.
+ *             are present in the array.
  */
 BlockNumber
 mdnblocks(SMgrRelation reln, ForkNumber forknum)
@@ -813,24 +849,24 @@ mdnblocks(SMgrRelation reln, ForkNumber forknum)
        BlockNumber nblocks;
        BlockNumber segno = 0;
 
+       /* mdopen has opened the first segment */
+       Assert(reln->md_num_open_segs[forknum] > 0);
+
        /*
-        * Skip through any segments that aren't the last one, to avoid redundant
-        * seeks on them.  We have previously verified that these segments are
-        * exactly RELSEG_SIZE long, and it's useless to recheck that each time.
+        * Start from the last open segments, to avoid redundant seeks.  We have
+        * previously verified that these segments are exactly RELSEG_SIZE long,
+        * and it's useless to recheck that each time.
         *
         * NOTE: this assumption could only be wrong if another backend has
         * truncated the relation.  We rely on higher code levels to handle that
         * scenario by closing and re-opening the md fd, which is handled via
         * relcache flush.  (Since the checkpointer doesn't participate in
-        * relcache flush, it could have segment chain entries for inactive
-        * segments; that's OK because the checkpointer never needs to compute
-        * relation size.)
+        * relcache flush, it could have segment entries for inactive segments;
+        * that's OK because the checkpointer never needs to compute relation
+        * size.)
         */
-       while (v->mdfd_chain != NULL)
-       {
-               segno++;
-               v = v->mdfd_chain;
-       }
+       segno = reln->md_num_open_segs[forknum] - 1;
+       v = &reln->md_seg_fds[forknum][segno];
 
        for (;;)
        {
@@ -845,23 +881,16 @@ mdnblocks(SMgrRelation reln, ForkNumber forknum)
                 */
                segno++;
 
-               if (v->mdfd_chain == NULL)
-               {
-                       /*
-                        * Because we pass O_CREAT, we will create the next segment (with
-                        * zero length) immediately, if the last segment is of length
-                        * RELSEG_SIZE.  While perhaps not strictly necessary, this keeps
-                        * the logic simple.
-                        */
-                       v->mdfd_chain = _mdfd_openseg(reln, forknum, segno, O_CREAT);
-                       if (v->mdfd_chain == NULL)
-                               ereport(ERROR,
-                                               (errcode_for_file_access(),
-                                                errmsg("could not open file \"%s\": %m",
-                                                               _mdfd_segpath(reln, forknum, segno))));
-               }
-
-               v = v->mdfd_chain;
+               /*
+                * We used to pass O_CREAT here, but that's has the disadvantage that
+                * it might create a segment which has vanished through some operating
+                * system misadventure.  In such a case, creating the segment here
+                * undermines _mdfd_getseg's attempts to notice and report an error
+                * upon access to a missing segment.
+                */
+               v = _mdfd_openseg(reln, forknum, segno, 0);
+               if (v == NULL)
+                       return segno * ((BlockNumber) RELSEG_SIZE);
        }
 }
 
@@ -871,9 +900,9 @@ mdnblocks(SMgrRelation reln, ForkNumber forknum)
 void
 mdtruncate(SMgrRelation reln, ForkNumber forknum, BlockNumber nblocks)
 {
-       MdfdVec    *v;
        BlockNumber curnblk;
        BlockNumber priorblocks;
+       int                     curopensegs;
 
        /*
         * NOTE: mdnblocks makes sure we have opened all active segments, so that
@@ -893,21 +922,26 @@ mdtruncate(SMgrRelation reln, ForkNumber forknum, BlockNumber nblocks)
        if (nblocks == curnblk)
                return;                                 /* no work */
 
-       v = mdopen(reln, forknum, EXTENSION_FAIL);
-
-       priorblocks = 0;
-       while (v != NULL)
+       /*
+        * Truncate segments, starting at the last one. Starting at the end makes
+        * managing the memory for the fd array easier, should there be errors.
+        */
+       curopensegs = reln->md_num_open_segs[forknum];
+       while (curopensegs > 0)
        {
-               MdfdVec    *ov = v;
+               MdfdVec    *v;
+
+               priorblocks = (curopensegs - 1) * RELSEG_SIZE;
+
+               v = &reln->md_seg_fds[forknum][curopensegs - 1];
 
                if (priorblocks > nblocks)
                {
                        /*
-                        * This segment is no longer active (and has already been unlinked
-                        * from the mdfd_chain). We truncate the file, but do not delete
-                        * it, for reasons explained in the header comments.
+                        * This segment is no longer active. We truncate the file, but do
+                        * not delete it, for reasons explained in the header comments.
                         */
-                       if (FileTruncate(v->mdfd_vfd, 0) < 0)
+                       if (FileTruncate(v->mdfd_vfd, 0, WAIT_EVENT_DATA_FILE_TRUNCATE) < 0)
                                ereport(ERROR,
                                                (errcode_for_file_access(),
                                                 errmsg("could not truncate file \"%s\": %m",
@@ -915,43 +949,42 @@ mdtruncate(SMgrRelation reln, ForkNumber forknum, BlockNumber nblocks)
 
                        if (!SmgrIsTemp(reln))
                                register_dirty_segment(reln, forknum, v);
-                       v = v->mdfd_chain;
-                       Assert(ov != reln->md_fd[forknum]); /* we never drop the 1st
-                                                                                                * segment */
-                       pfree(ov);
+
+                       /* we never drop the 1st segment */
+                       Assert(v != &reln->md_seg_fds[forknum][0]);
+
+                       FileClose(v->mdfd_vfd);
+                       _fdvec_resize(reln, forknum, curopensegs - 1);
                }
                else if (priorblocks + ((BlockNumber) RELSEG_SIZE) > nblocks)
                {
                        /*
                         * This is the last segment we want to keep. Truncate the file to
-                        * the right length, and clear chain link that points to any
-                        * remaining segments (which we shall zap). NOTE: if nblocks is
-                        * exactly a multiple K of RELSEG_SIZE, we will truncate the K+1st
-                        * segment to 0 length but keep it. This adheres to the invariant
-                        * given in the header comments.
+                        * the right length. NOTE: if nblocks is exactly a multiple K of
+                        * RELSEG_SIZE, we will truncate the K+1st segment to 0 length but
+                        * keep it. This adheres to the invariant given in the header
+                        * comments.
                         */
                        BlockNumber lastsegblocks = nblocks - priorblocks;
 
-                       if (FileTruncate(v->mdfd_vfd, (off_t) lastsegblocks * BLCKSZ) < 0)
+                       if (FileTruncate(v->mdfd_vfd, (off_t) lastsegblocks * BLCKSZ, WAIT_EVENT_DATA_FILE_TRUNCATE) < 0)
                                ereport(ERROR,
                                                (errcode_for_file_access(),
-                                       errmsg("could not truncate file \"%s\" to %u blocks: %m",
-                                                  FilePathName(v->mdfd_vfd),
-                                                  nblocks)));
+                                                errmsg("could not truncate file \"%s\" to %u blocks: %m",
+                                                               FilePathName(v->mdfd_vfd),
+                                                               nblocks)));
                        if (!SmgrIsTemp(reln))
                                register_dirty_segment(reln, forknum, v);
-                       v = v->mdfd_chain;
-                       ov->mdfd_chain = NULL;
                }
                else
                {
                        /*
-                        * We still need this segment and 0 or more blocks beyond it, so
-                        * nothing to do here.
+                        * We still need this segment, so nothing to do for this and any
+                        * earlier segment.
                         */
-                       v = v->mdfd_chain;
+                       break;
                }
-               priorblocks += RELSEG_SIZE;
+               curopensegs--;
        }
 }
 
@@ -964,7 +997,7 @@ mdtruncate(SMgrRelation reln, ForkNumber forknum, BlockNumber nblocks)
 void
 mdimmedsync(SMgrRelation reln, ForkNumber forknum)
 {
-       MdfdVec    *v;
+       int                     segno;
 
        /*
         * NOTE: mdnblocks makes sure we have opened all active segments, so that
@@ -972,16 +1005,18 @@ mdimmedsync(SMgrRelation reln, ForkNumber forknum)
         */
        mdnblocks(reln, forknum);
 
-       v = mdopen(reln, forknum, EXTENSION_FAIL);
+       segno = reln->md_num_open_segs[forknum];
 
-       while (v != NULL)
+       while (segno > 0)
        {
-               if (FileSync(v->mdfd_vfd) < 0)
-                       ereport(ERROR,
+               MdfdVec    *v = &reln->md_seg_fds[forknum][segno - 1];
+
+               if (FileSync(v->mdfd_vfd, WAIT_EVENT_DATA_FILE_IMMEDIATE_SYNC) < 0)
+                       ereport(data_sync_elevel(ERROR),
                                        (errcode_for_file_access(),
                                         errmsg("could not fsync file \"%s\": %m",
                                                        FilePathName(v->mdfd_vfd))));
-               v = v->mdfd_chain;
+               segno--;
        }
 }
 
@@ -1088,10 +1123,8 @@ mdsync(void)
                 * The bitmap manipulations are slightly tricky, because we can call
                 * AbsorbFsyncRequests() inside the loop and that could result in
                 * bms_add_member() modifying and even re-palloc'ing the bitmapsets.
-                * This is okay because we unlink each bitmapset from the hashtable
-                * entry before scanning it.  That means that any incoming fsync
-                * requests will be processed now if they reach the table before we
-                * begin to scan their fork.
+                * So we detach it, but if we fail we'll merge it with any new
+                * requests that have arrived in the meantime.
                 */
                for (forknum = 0; forknum <= MAX_FORKNUM; forknum++)
                {
@@ -1101,7 +1134,8 @@ mdsync(void)
                        entry->requests[forknum] = NULL;
                        entry->canceled[forknum] = false;
 
-                       while ((segno = bms_first_member(requests)) >= 0)
+                       segno = -1;
+                       while ((segno = bms_next_member(requests, segno)) >= 0)
                        {
                                int                     failures;
 
@@ -1163,13 +1197,15 @@ mdsync(void)
 
                                        /* Attempt to open and fsync the target segment */
                                        seg = _mdfd_getseg(reln, forknum,
-                                                        (BlockNumber) segno * (BlockNumber) RELSEG_SIZE,
-                                                                          false, EXTENSION_RETURN_NULL);
+                                                                          (BlockNumber) segno * (BlockNumber) RELSEG_SIZE,
+                                                                          false,
+                                                                          EXTENSION_RETURN_NULL
+                                                                          | EXTENSION_DONT_CHECK_SIZE);
 
                                        INSTR_TIME_SET_CURRENT(sync_start);
 
                                        if (seg != NULL &&
-                                               FileSync(seg->mdfd_vfd) >= 0)
+                                               FileSync(seg->mdfd_vfd, WAIT_EVENT_DATA_FILE_SYNC) >= 0)
                                        {
                                                /* Success; update statistics about sync timing */
                                                INSTR_TIME_SET_CURRENT(sync_end);
@@ -1180,6 +1216,7 @@ mdsync(void)
                                                        longest = elapsed;
                                                total_elapsed += elapsed;
                                                processed++;
+                                               requests = bms_del_member(requests, segno);
                                                if (log_checkpoints)
                                                        elog(DEBUG1, "checkpoint sync: number=%d file=%s time=%.3f msec",
                                                                 processed,
@@ -1208,15 +1245,28 @@ mdsync(void)
                                         */
                                        if (!FILE_POSSIBLY_DELETED(errno) ||
                                                failures > 0)
-                                               ereport(ERROR,
+                                       {
+                                               Bitmapset  *new_requests;
+
+                                               /*
+                                                * We need to merge these unsatisfied requests with
+                                                * any others that have arrived since we started.
+                                                */
+                                               new_requests = entry->requests[forknum];
+                                               entry->requests[forknum] =
+                                                       bms_join(new_requests, requests);
+
+                                               errno = save_errno;
+                                               ereport(data_sync_elevel(ERROR),
                                                                (errcode_for_file_access(),
                                                                 errmsg("could not fsync file \"%s\": %m",
                                                                                path)));
+                                       }
                                        else
                                                ereport(DEBUG1,
                                                                (errcode_for_file_access(),
-                                               errmsg("could not fsync file \"%s\" but retrying: %m",
-                                                          path)));
+                                                                errmsg("could not fsync file \"%s\" but retrying: %m",
+                                                                               path)));
                                        pfree(path);
 
                                        /*
@@ -1380,8 +1430,8 @@ register_dirty_segment(SMgrRelation reln, ForkNumber forknum, MdfdVec *seg)
                ereport(DEBUG1,
                                (errmsg("could not forward fsync request because request queue is full")));
 
-               if (FileSync(seg->mdfd_vfd) < 0)
-                       ereport(ERROR,
+               if (FileSync(seg->mdfd_vfd, WAIT_EVENT_DATA_FILE_SYNC) < 0)
+                       ereport(data_sync_elevel(ERROR),
                                        (errcode_for_file_access(),
                                         errmsg("could not fsync file \"%s\": %m",
                                                        FilePathName(seg->mdfd_vfd))));
@@ -1640,14 +1690,79 @@ ForgetDatabaseFsyncRequests(Oid dbid)
        }
 }
 
+/*
+ * DropRelationFiles -- drop files of all given relations
+ */
+void
+DropRelationFiles(RelFileNode *delrels, int ndelrels, bool isRedo)
+{
+       SMgrRelation *srels;
+       int                     i;
+
+       srels = palloc(sizeof(SMgrRelation) * ndelrels);
+       for (i = 0; i < ndelrels; i++)
+       {
+               SMgrRelation srel = smgropen(delrels[i], InvalidBackendId);
+
+               if (isRedo)
+               {
+                       ForkNumber      fork;
+
+                       for (fork = 0; fork <= MAX_FORKNUM; fork++)
+                               XLogDropRelation(delrels[i], fork);
+               }
+               srels[i] = srel;
+       }
+
+       smgrdounlinkall(srels, ndelrels, isRedo);
+
+       /*
+        * Call smgrclose() in reverse order as when smgropen() is called.
+        * This trick enables remove_from_unowned_list() in smgrclose()
+        * to search the SMgrRelation from the unowned list,
+        * with O(1) performance.
+        */
+       for (i = ndelrels - 1; i >= 0; i--)
+               smgrclose(srels[i]);
+       pfree(srels);
+}
+
 
 /*
- *     _fdvec_alloc() -- Make a MdfdVec object.
+ *     _fdvec_resize() -- Resize the fork's open segments array
  */
-static MdfdVec *
-_fdvec_alloc(void)
+static void
+_fdvec_resize(SMgrRelation reln,
+                         ForkNumber forknum,
+                         int nseg)
 {
-       return (MdfdVec *) MemoryContextAlloc(MdCxt, sizeof(MdfdVec));
+       if (nseg == 0)
+       {
+               if (reln->md_num_open_segs[forknum] > 0)
+               {
+                       pfree(reln->md_seg_fds[forknum]);
+                       reln->md_seg_fds[forknum] = NULL;
+               }
+       }
+       else if (reln->md_num_open_segs[forknum] == 0)
+       {
+               reln->md_seg_fds[forknum] =
+                       MemoryContextAlloc(MdCxt, sizeof(MdfdVec) * nseg);
+       }
+       else
+       {
+               /*
+                * It doesn't seem worthwhile complicating the code by having a more
+                * aggressive growth strategy here; the number of segments doesn't
+                * grow that fast, and the memory context internally will sometimes
+                * avoid doing an actual reallocation.
+                */
+               reln->md_seg_fds[forknum] =
+                       repalloc(reln->md_seg_fds[forknum],
+                                        sizeof(MdfdVec) * nseg);
+       }
+
+       reln->md_num_open_segs[forknum] = nseg;
 }
 
 /*
@@ -1688,20 +1803,21 @@ _mdfd_openseg(SMgrRelation reln, ForkNumber forknum, BlockNumber segno,
        fullpath = _mdfd_segpath(reln, forknum, segno);
 
        /* open the file */
-       fd = PathNameOpenFile(fullpath, O_RDWR | PG_BINARY | oflags, 0600);
+       fd = PathNameOpenFile(fullpath, O_RDWR | PG_BINARY | oflags);
 
        pfree(fullpath);
 
        if (fd < 0)
                return NULL;
 
-       /* allocate an mdfdvec entry for it */
-       v = _fdvec_alloc();
+       if (segno <= reln->md_num_open_segs[forknum])
+               _fdvec_resize(reln, forknum, segno + 1);
 
        /* fill the entry */
+       v = &reln->md_seg_fds[forknum][segno];
        v->mdfd_vfd = fd;
        v->mdfd_segno = segno;
-       v->mdfd_chain = NULL;
+
        Assert(_mdnblocks(reln, forknum, v) <= ((BlockNumber) RELSEG_SIZE));
 
        /* all done */
@@ -1718,68 +1834,126 @@ _mdfd_openseg(SMgrRelation reln, ForkNumber forknum, BlockNumber segno,
  */
 static MdfdVec *
 _mdfd_getseg(SMgrRelation reln, ForkNumber forknum, BlockNumber blkno,
-                        bool skipFsync, ExtensionBehavior behavior)
+                        bool skipFsync, int behavior)
 {
-       MdfdVec    *v = mdopen(reln, forknum, behavior);
+       MdfdVec    *v;
        BlockNumber targetseg;
        BlockNumber nextsegno;
 
-       if (!v)
-               return NULL;                    /* only possible if EXTENSION_RETURN_NULL */
+       /* some way to handle non-existent segments needs to be specified */
+       Assert(behavior &
+                  (EXTENSION_FAIL | EXTENSION_CREATE | EXTENSION_RETURN_NULL));
 
        targetseg = blkno / ((BlockNumber) RELSEG_SIZE);
-       for (nextsegno = 1; nextsegno <= targetseg; nextsegno++)
+
+       /* if an existing and opened segment, we're done */
+       if (targetseg < reln->md_num_open_segs[forknum])
+       {
+               v = &reln->md_seg_fds[forknum][targetseg];
+               return v;
+       }
+
+       /*
+        * The target segment is not yet open. Iterate over all the segments
+        * between the last opened and the target segment. This way missing
+        * segments either raise an error, or get created (according to
+        * 'behavior'). Start with either the last opened, or the first segment if
+        * none was opened before.
+        */
+       if (reln->md_num_open_segs[forknum] > 0)
+               v = &reln->md_seg_fds[forknum][reln->md_num_open_segs[forknum] - 1];
+       else
        {
+               v = mdopen(reln, forknum, behavior);
+               if (!v)
+                       return NULL;            /* if behavior & EXTENSION_RETURN_NULL */
+       }
+
+       for (nextsegno = reln->md_num_open_segs[forknum];
+                nextsegno <= targetseg; nextsegno++)
+       {
+               BlockNumber nblocks = _mdnblocks(reln, forknum, v);
+               int                     flags = 0;
+
                Assert(nextsegno == v->mdfd_segno + 1);
 
-               if (v->mdfd_chain == NULL)
+               if (nblocks > ((BlockNumber) RELSEG_SIZE))
+                       elog(FATAL, "segment too big");
+
+               if ((behavior & EXTENSION_CREATE) ||
+                       (InRecovery && (behavior & EXTENSION_CREATE_RECOVERY)))
                {
                        /*
                         * Normally we will create new segments only if authorized by the
                         * caller (i.e., we are doing mdextend()).  But when doing WAL
                         * recovery, create segments anyway; this allows cases such as
                         * replaying WAL data that has a write into a high-numbered
-                        * segment of a relation that was later deleted.  We want to go
+                        * segment of a relation that was later deleted. We want to go
                         * ahead and create the segments so we can finish out the replay.
+                        * However if the caller has specified
+                        * EXTENSION_REALLY_RETURN_NULL, then extension is not desired
+                        * even in recovery; we won't reach this point in that case.
                         *
                         * We have to maintain the invariant that segments before the last
-                        * active segment are of size RELSEG_SIZE; therefore, pad them out
-                        * with zeroes if needed.  (This only matters if caller is
-                        * extending the relation discontiguously, but that can happen in
-                        * hash indexes.)
+                        * active segment are of size RELSEG_SIZE; therefore, if
+                        * extending, pad them out with zeroes if needed.  (This only
+                        * matters if in recovery, or if the caller is extending the
+                        * relation discontiguously, but that can happen in hash indexes.)
                         */
-                       if (behavior == EXTENSION_CREATE || InRecovery)
+                       if (nblocks < ((BlockNumber) RELSEG_SIZE))
                        {
-                               if (_mdnblocks(reln, forknum, v) < RELSEG_SIZE)
-                               {
-                                       char       *zerobuf = palloc0(BLCKSZ);
+                               char       *zerobuf = palloc0(BLCKSZ);
 
-                                       mdextend(reln, forknum,
-                                                        nextsegno * ((BlockNumber) RELSEG_SIZE) - 1,
-                                                        zerobuf, skipFsync);
-                                       pfree(zerobuf);
-                               }
-                               v->mdfd_chain = _mdfd_openseg(reln, forknum, +nextsegno, O_CREAT);
+                               mdextend(reln, forknum,
+                                                nextsegno * ((BlockNumber) RELSEG_SIZE) - 1,
+                                                zerobuf, skipFsync);
+                               pfree(zerobuf);
                        }
-                       else
-                       {
-                               /* We won't create segment if not existent */
-                               v->mdfd_chain = _mdfd_openseg(reln, forknum, nextsegno, 0);
-                       }
-                       if (v->mdfd_chain == NULL)
+                       flags = O_CREAT;
+               }
+               else if (!(behavior & EXTENSION_DONT_CHECK_SIZE) &&
+                                nblocks < ((BlockNumber) RELSEG_SIZE))
+               {
+                       /*
+                        * When not extending (or explicitly including truncated
+                        * segments), only open the next segment if the current one is
+                        * exactly RELSEG_SIZE.  If not (this branch), either return NULL
+                        * or fail.
+                        */
+                       if (behavior & EXTENSION_RETURN_NULL)
                        {
-                               if (behavior == EXTENSION_RETURN_NULL &&
-                                       FILE_POSSIBLY_DELETED(errno))
-                                       return NULL;
-                               ereport(ERROR,
-                                               (errcode_for_file_access(),
-                                  errmsg("could not open file \"%s\" (target block %u): %m",
-                                                 _mdfd_segpath(reln, forknum, nextsegno),
-                                                 blkno)));
+                               /*
+                                * Some callers discern between reasons for _mdfd_getseg()
+                                * returning NULL based on errno. As there's no failing
+                                * syscall involved in this case, explicitly set errno to
+                                * ENOENT, as that seems the closest interpretation.
+                                */
+                               errno = ENOENT;
+                               return NULL;
                        }
+
+                       ereport(ERROR,
+                                       (errcode_for_file_access(),
+                                        errmsg("could not open file \"%s\" (target block %u): previous segment is only %u blocks",
+                                                       _mdfd_segpath(reln, forknum, nextsegno),
+                                                       blkno, nblocks)));
+               }
+
+               v = _mdfd_openseg(reln, forknum, nextsegno, flags);
+
+               if (v == NULL)
+               {
+                       if ((behavior & EXTENSION_RETURN_NULL) &&
+                               FILE_POSSIBLY_DELETED(errno))
+                               return NULL;
+                       ereport(ERROR,
+                                       (errcode_for_file_access(),
+                                        errmsg("could not open file \"%s\" (target block %u): %m",
+                                                       _mdfd_segpath(reln, forknum, nextsegno),
+                                                       blkno)));
                }
-               v = v->mdfd_chain;
        }
+
        return v;
 }
 
@@ -1791,7 +1965,7 @@ _mdnblocks(SMgrRelation reln, ForkNumber forknum, MdfdVec *seg)
 {
        off_t           len;
 
-       len = FileSeek(seg->mdfd_vfd, 0L, SEEK_END);
+       len = FileSize(seg->mdfd_vfd);
        if (len < 0)
                ereport(ERROR,
                                (errcode_for_file_access(),