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