1 /*-------------------------------------------------------------------------
4 * This code manages relations that reside on magnetic disk.
6 * Portions Copyright (c) 1996-2010, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * src/backend/storage/smgr/md.c
13 *-------------------------------------------------------------------------
21 #include "catalog/catalog.h"
22 #include "miscadmin.h"
23 #include "portability/instr_time.h"
24 #include "postmaster/bgwriter.h"
25 #include "storage/fd.h"
26 #include "storage/bufmgr.h"
27 #include "storage/relfilenode.h"
28 #include "storage/smgr.h"
29 #include "utils/hsearch.h"
30 #include "utils/memutils.h"
34 /* interval for calling AbsorbFsyncRequests in mdsync */
35 #define FSYNCS_PER_ABSORB 10
37 /* special values for the segno arg to RememberFsyncRequest */
38 #define FORGET_RELATION_FSYNC (InvalidBlockNumber)
39 #define FORGET_DATABASE_FSYNC (InvalidBlockNumber-1)
40 #define UNLINK_RELATION_REQUEST (InvalidBlockNumber-2)
43 * On Windows, we have to interpret EACCES as possibly meaning the same as
44 * ENOENT, because if a file is unlinked-but-not-yet-gone on that platform,
45 * that's what you get. Ugh. This code is designed so that we don't
46 * actually believe these cases are okay without further evidence (namely,
47 * a pending fsync request getting revoked ... see mdsync).
50 #define FILE_POSSIBLY_DELETED(err) ((err) == ENOENT)
52 #define FILE_POSSIBLY_DELETED(err) ((err) == ENOENT || (err) == EACCES)
56 * The magnetic disk storage manager keeps track of open file
57 * descriptors in its own descriptor pool. This is done to make it
58 * easier to support relations that are larger than the operating
59 * system's file size limit (often 2GBytes). In order to do that,
60 * we break relations up into "segment" files that are each shorter than
61 * the OS file size limit. The segment size is set by the RELSEG_SIZE
62 * configuration constant in pg_config.h.
64 * On disk, a relation must consist of consecutively numbered segment
65 * files in the pattern
66 * -- Zero or more full segments of exactly RELSEG_SIZE blocks each
67 * -- Exactly one partial segment of size 0 <= size < RELSEG_SIZE blocks
68 * -- Optionally, any number of inactive segments of size 0 blocks.
69 * The full and partial segments are collectively the "active" segments.
70 * Inactive segments are those that once contained data but are currently
71 * not needed because of an mdtruncate() operation. The reason for leaving
72 * them present at size zero, rather than unlinking them, is that other
73 * backends and/or the bgwriter might be holding open file references to
74 * such segments. If the relation expands again after mdtruncate(), such
75 * that a deactivated segment becomes active again, it is important that
76 * such file references still be valid --- else data might get written
77 * out to an unlinked old copy of a segment file that will eventually
80 * The file descriptor pointer (md_fd field) stored in the SMgrRelation
81 * cache is, therefore, just the head of a list of MdfdVec objects, one
82 * per segment. But note the md_fd pointer can be NULL, indicating
85 * Also note that mdfd_chain == NULL does not necessarily mean the relation
86 * doesn't have another segment after this one; we may just not have
87 * opened the next segment yet. (We could not have "all segments are
88 * in the chain" as an invariant anyway, since another backend could
89 * extend the relation when we weren't looking.) We do not make chain
90 * entries for inactive segments, however; as soon as we find a partial
91 * segment, we assume that any subsequent segments are inactive.
93 * All MdfdVec objects are palloc'd in the MdCxt memory context.
96 typedef struct _MdfdVec
98 File mdfd_vfd; /* fd number in fd.c's pool */
99 BlockNumber mdfd_segno; /* segment number, from 0 */
100 struct _MdfdVec *mdfd_chain; /* next segment, or NULL */
103 static MemoryContext MdCxt; /* context for all md.c allocations */
107 * In some contexts (currently, standalone backends and the bgwriter process)
108 * we keep track of pending fsync operations: we need to remember all relation
109 * segments that have been written since the last checkpoint, so that we can
110 * fsync them down to disk before completing the next checkpoint. This hash
111 * table remembers the pending operations. We use a hash table mostly as
112 * a convenient way of eliminating duplicate requests.
114 * We use a similar mechanism to remember no-longer-needed files that can
115 * be deleted after the next checkpoint, but we use a linked list instead of
116 * a hash table, because we don't expect there to be any duplicate requests.
118 * (Regular backends do not track pending operations locally, but forward
119 * them to the bgwriter.)
123 RelFileNodeBackend rnode; /* the targeted relation */
125 BlockNumber segno; /* which segment */
126 } PendingOperationTag;
128 typedef uint16 CycleCtr; /* can be any convenient integer size */
132 PendingOperationTag tag; /* hash table key (must be first!) */
133 bool canceled; /* T => request canceled, not yet removed */
134 CycleCtr cycle_ctr; /* mdsync_cycle_ctr when request was made */
135 } PendingOperationEntry;
139 RelFileNodeBackend rnode; /* the dead relation to delete */
140 CycleCtr cycle_ctr; /* mdckpt_cycle_ctr when request was made */
141 } PendingUnlinkEntry;
143 static HTAB *pendingOpsTable = NULL;
144 static List *pendingUnlinks = NIL;
146 static CycleCtr mdsync_cycle_ctr = 0;
147 static CycleCtr mdckpt_cycle_ctr = 0;
150 typedef enum /* behavior for mdopen & _mdfd_getseg */
152 EXTENSION_FAIL, /* ereport if segment not present */
153 EXTENSION_RETURN_NULL, /* return NULL if not present */
154 EXTENSION_CREATE /* create new segments as needed */
158 static MdfdVec *mdopen(SMgrRelation reln, ForkNumber forknum,
159 ExtensionBehavior behavior);
160 static void register_dirty_segment(SMgrRelation reln, ForkNumber forknum,
162 static void register_unlink(RelFileNodeBackend rnode);
163 static MdfdVec *_fdvec_alloc(void);
164 static char *_mdfd_segpath(SMgrRelation reln, ForkNumber forknum,
166 static MdfdVec *_mdfd_openseg(SMgrRelation reln, ForkNumber forkno,
167 BlockNumber segno, int oflags);
168 static MdfdVec *_mdfd_getseg(SMgrRelation reln, ForkNumber forkno,
169 BlockNumber blkno, bool skipFsync, ExtensionBehavior behavior);
170 static BlockNumber _mdnblocks(SMgrRelation reln, ForkNumber forknum,
175 * mdinit() -- Initialize private state for magnetic disk storage manager.
180 MdCxt = AllocSetContextCreate(TopMemoryContext,
182 ALLOCSET_DEFAULT_MINSIZE,
183 ALLOCSET_DEFAULT_INITSIZE,
184 ALLOCSET_DEFAULT_MAXSIZE);
187 * Create pending-operations hashtable if we need it. Currently, we need
188 * it if we are standalone (not under a postmaster) OR if we are a
189 * bootstrap-mode subprocess of a postmaster (that is, a startup or
192 if (!IsUnderPostmaster || IsBootstrapProcessingMode())
196 MemSet(&hash_ctl, 0, sizeof(hash_ctl));
197 hash_ctl.keysize = sizeof(PendingOperationTag);
198 hash_ctl.entrysize = sizeof(PendingOperationEntry);
199 hash_ctl.hash = tag_hash;
200 hash_ctl.hcxt = MdCxt;
201 pendingOpsTable = hash_create("Pending Ops Table",
204 HASH_ELEM | HASH_FUNCTION | HASH_CONTEXT);
205 pendingUnlinks = NIL;
210 * In archive recovery, we rely on bgwriter to do fsyncs, but we will have
211 * already created the pendingOpsTable during initialization of the startup
212 * process. Calling this function drops the local pendingOpsTable so that
213 * subsequent requests will be forwarded to bgwriter.
216 SetForwardFsyncRequests(void)
218 /* Perform any pending ops we may have queued up */
221 pendingOpsTable = NULL;
225 * mdexists() -- Does the physical file exist?
227 * Note: this will return true for lingering files, with pending deletions
230 mdexists(SMgrRelation reln, ForkNumber forkNum)
233 * Close it first, to ensure that we notice if the fork has been unlinked
234 * since we opened it.
236 mdclose(reln, forkNum);
238 return (mdopen(reln, forkNum, EXTENSION_RETURN_NULL) != NULL);
242 * mdcreate() -- Create a new relation on magnetic disk.
244 * If isRedo is true, it's okay for the relation to exist already.
247 mdcreate(SMgrRelation reln, ForkNumber forkNum, bool isRedo)
252 if (isRedo && reln->md_fd[forkNum] != NULL)
253 return; /* created and opened already... */
255 Assert(reln->md_fd[forkNum] == NULL);
257 path = relpath(reln->smgr_rnode, forkNum);
259 fd = PathNameOpenFile(path, O_RDWR | O_CREAT | O_EXCL | PG_BINARY, 0600);
263 int save_errno = errno;
266 * During bootstrap, there are cases where a system relation will be
267 * accessed (by internal backend processes) before the bootstrap
268 * script nominally creates it. Therefore, allow the file to exist
269 * already, even if isRedo is not set. (See also mdopen)
271 if (isRedo || IsBootstrapProcessingMode())
272 fd = PathNameOpenFile(path, O_RDWR | PG_BINARY, 0600);
275 /* be sure to report the error reported by create, not open */
278 (errcode_for_file_access(),
279 errmsg("could not create file \"%s\": %m", path)));
285 reln->md_fd[forkNum] = _fdvec_alloc();
287 reln->md_fd[forkNum]->mdfd_vfd = fd;
288 reln->md_fd[forkNum]->mdfd_segno = 0;
289 reln->md_fd[forkNum]->mdfd_chain = NULL;
293 * mdunlink() -- Unlink a relation.
295 * Note that we're passed a RelFileNode --- by the time this is called,
296 * there won't be an SMgrRelation hashtable entry anymore.
298 * Actually, we don't unlink the first segment file of the relation, but
299 * just truncate it to zero length, and record a request to unlink it after
300 * the next checkpoint. Additional segments can be unlinked immediately,
301 * however. Leaving the empty file in place prevents that relfilenode
302 * number from being reused. The scenario this protects us from is:
303 * 1. We delete a relation (and commit, and actually remove its file).
304 * 2. We create a new relation, which by chance gets the same relfilenode as
305 * the just-deleted one (OIDs must've wrapped around for that to happen).
306 * 3. We crash before another checkpoint occurs.
307 * During replay, we would delete the file and then recreate it, which is fine
308 * if the contents of the file were repopulated by subsequent WAL entries.
309 * But if we didn't WAL-log insertions, but instead relied on fsyncing the
310 * file after populating it (as for instance CLUSTER and CREATE INDEX do),
311 * the contents of the file would be lost forever. By leaving the empty file
312 * until after the next checkpoint, we prevent reassignment of the relfilenode
313 * number until it's safe, because relfilenode assignment skips over any
316 * If isRedo is true, it's okay for the relation to be already gone.
317 * Also, we should remove the file immediately instead of queuing a request
318 * for later, since during redo there's no possibility of creating a
319 * conflicting relation.
321 * Note: any failure should be reported as WARNING not ERROR, because
322 * we are usually not in a transaction anymore when this is called.
325 mdunlink(RelFileNodeBackend rnode, ForkNumber forkNum, bool isRedo)
331 * We have to clean out any pending fsync requests for the doomed
332 * relation, else the next mdsync() will fail.
334 ForgetRelationFsyncRequests(rnode, forkNum);
336 path = relpath(rnode, forkNum);
339 * Delete or truncate the first segment.
341 if (isRedo || forkNum != MAIN_FORKNUM)
346 if (!isRedo || errno != ENOENT)
348 (errcode_for_file_access(),
349 errmsg("could not remove file \"%s\": %m", path)));
354 /* truncate(2) would be easier here, but Windows hasn't got it */
357 fd = BasicOpenFile(path, O_RDWR | PG_BINARY, 0);
362 ret = ftruncate(fd, 0);
369 if (ret < 0 && errno != ENOENT)
371 (errcode_for_file_access(),
372 errmsg("could not truncate file \"%s\": %m", path)));
376 * Delete any additional segments.
380 char *segpath = (char *) palloc(strlen(path) + 12);
384 * Note that because we loop until getting ENOENT, we will correctly
385 * remove all inactive segments as well as active ones.
387 for (segno = 1;; segno++)
389 sprintf(segpath, "%s.%u", path, segno);
390 if (unlink(segpath) < 0)
392 /* ENOENT is expected after the last segment... */
395 (errcode_for_file_access(),
396 errmsg("could not remove file \"%s\": %m", segpath)));
405 /* Register request to unlink first segment later */
406 if (!isRedo && forkNum == MAIN_FORKNUM)
407 register_unlink(rnode);
411 * mdextend() -- Add a block to the specified relation.
413 * The semantics are nearly the same as mdwrite(): write at the
414 * specified position. However, this is to be used for the case of
415 * extending a relation (i.e., blocknum is at or beyond the current
416 * EOF). Note that we assume writing a block beyond current EOF
417 * causes intervening file space to become filled with zeroes.
420 mdextend(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum,
421 char *buffer, bool skipFsync)
427 /* This assert is too expensive to have on normally ... */
428 #ifdef CHECK_WRITE_VS_EXTEND
429 Assert(blocknum >= mdnblocks(reln, forknum));
433 * If a relation manages to grow to 2^32-1 blocks, refuse to extend it any
434 * more --- we mustn't create a block whose number actually is
435 * InvalidBlockNumber.
437 if (blocknum == InvalidBlockNumber)
439 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
440 errmsg("cannot extend file \"%s\" beyond %u blocks",
441 relpath(reln->smgr_rnode, forknum),
442 InvalidBlockNumber)));
444 v = _mdfd_getseg(reln, forknum, blocknum, skipFsync, EXTENSION_CREATE);
446 seekpos = (off_t) BLCKSZ *(blocknum % ((BlockNumber) RELSEG_SIZE));
448 Assert(seekpos < (off_t) BLCKSZ * RELSEG_SIZE);
451 * Note: because caller usually obtained blocknum by calling mdnblocks,
452 * which did a seek(SEEK_END), this seek is often redundant and will be
453 * optimized away by fd.c. It's not redundant, however, if there is a
454 * partial page at the end of the file. In that case we want to try to
455 * overwrite the partial page with a full page. It's also not redundant
456 * if bufmgr.c had to dump another buffer of the same file to make room
457 * for the new page's buffer.
459 if (FileSeek(v->mdfd_vfd, seekpos, SEEK_SET) != seekpos)
461 (errcode_for_file_access(),
462 errmsg("could not seek to block %u in file \"%s\": %m",
463 blocknum, FilePathName(v->mdfd_vfd))));
465 if ((nbytes = FileWrite(v->mdfd_vfd, buffer, BLCKSZ)) != BLCKSZ)
469 (errcode_for_file_access(),
470 errmsg("could not extend file \"%s\": %m",
471 FilePathName(v->mdfd_vfd)),
472 errhint("Check free disk space.")));
473 /* short write: complain appropriately */
475 (errcode(ERRCODE_DISK_FULL),
476 errmsg("could not extend file \"%s\": wrote only %d of %d bytes at block %u",
477 FilePathName(v->mdfd_vfd),
478 nbytes, BLCKSZ, blocknum),
479 errhint("Check free disk space.")));
482 if (!skipFsync && !SmgrIsTemp(reln))
483 register_dirty_segment(reln, forknum, v);
485 Assert(_mdnblocks(reln, forknum, v) <= ((BlockNumber) RELSEG_SIZE));
489 * mdopen() -- Open the specified relation.
491 * Note we only open the first segment, when there are multiple segments.
493 * If first segment is not present, either ereport or return NULL according
494 * to "behavior". We treat EXTENSION_CREATE the same as EXTENSION_FAIL;
495 * EXTENSION_CREATE means it's OK to extend an existing relation, not to
496 * invent one out of whole cloth.
499 mdopen(SMgrRelation reln, ForkNumber forknum, ExtensionBehavior behavior)
505 /* No work if already open */
506 if (reln->md_fd[forknum])
507 return reln->md_fd[forknum];
509 path = relpath(reln->smgr_rnode, forknum);
511 fd = PathNameOpenFile(path, O_RDWR | PG_BINARY, 0600);
516 * During bootstrap, there are cases where a system relation will be
517 * accessed (by internal backend processes) before the bootstrap
518 * script nominally creates it. Therefore, accept mdopen() as a
519 * substitute for mdcreate() in bootstrap mode only. (See mdcreate)
521 if (IsBootstrapProcessingMode())
522 fd = PathNameOpenFile(path, O_RDWR | O_CREAT | O_EXCL | PG_BINARY, 0600);
525 if (behavior == EXTENSION_RETURN_NULL &&
526 FILE_POSSIBLY_DELETED(errno))
532 (errcode_for_file_access(),
533 errmsg("could not open file \"%s\": %m", path)));
539 reln->md_fd[forknum] = mdfd = _fdvec_alloc();
542 mdfd->mdfd_segno = 0;
543 mdfd->mdfd_chain = NULL;
544 Assert(_mdnblocks(reln, forknum, mdfd) <= ((BlockNumber) RELSEG_SIZE));
550 * mdclose() -- Close the specified relation, if it isn't closed already.
553 mdclose(SMgrRelation reln, ForkNumber forknum)
555 MdfdVec *v = reln->md_fd[forknum];
557 /* No work if already closed */
561 reln->md_fd[forknum] = NULL; /* prevent dangling pointer after error */
567 /* if not closed already */
568 if (v->mdfd_vfd >= 0)
569 FileClose(v->mdfd_vfd);
570 /* Now free vector */
577 * mdprefetch() -- Initiate asynchronous read of the specified block of a relation
580 mdprefetch(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum)
586 v = _mdfd_getseg(reln, forknum, blocknum, false, EXTENSION_FAIL);
588 seekpos = (off_t) BLCKSZ *(blocknum % ((BlockNumber) RELSEG_SIZE));
590 Assert(seekpos < (off_t) BLCKSZ * RELSEG_SIZE);
592 (void) FilePrefetch(v->mdfd_vfd, seekpos, BLCKSZ);
593 #endif /* USE_PREFETCH */
598 * mdread() -- Read the specified block from a relation.
601 mdread(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum,
608 TRACE_POSTGRESQL_SMGR_MD_READ_START(forknum, blocknum,
609 reln->smgr_rnode.node.spcNode,
610 reln->smgr_rnode.node.dbNode,
611 reln->smgr_rnode.node.relNode,
612 reln->smgr_rnode.backend);
614 v = _mdfd_getseg(reln, forknum, blocknum, false, EXTENSION_FAIL);
616 seekpos = (off_t) BLCKSZ *(blocknum % ((BlockNumber) RELSEG_SIZE));
618 Assert(seekpos < (off_t) BLCKSZ * RELSEG_SIZE);
620 if (FileSeek(v->mdfd_vfd, seekpos, SEEK_SET) != seekpos)
622 (errcode_for_file_access(),
623 errmsg("could not seek to block %u in file \"%s\": %m",
624 blocknum, FilePathName(v->mdfd_vfd))));
626 nbytes = FileRead(v->mdfd_vfd, buffer, BLCKSZ);
628 TRACE_POSTGRESQL_SMGR_MD_READ_DONE(forknum, blocknum,
629 reln->smgr_rnode.node.spcNode,
630 reln->smgr_rnode.node.dbNode,
631 reln->smgr_rnode.node.relNode,
632 reln->smgr_rnode.backend,
636 if (nbytes != BLCKSZ)
640 (errcode_for_file_access(),
641 errmsg("could not read block %u in file \"%s\": %m",
642 blocknum, FilePathName(v->mdfd_vfd))));
645 * Short read: we are at or past EOF, or we read a partial block at
646 * EOF. Normally this is an error; upper levels should never try to
647 * read a nonexistent block. However, if zero_damaged_pages is ON or
648 * we are InRecovery, we should instead return zeroes without
649 * complaining. This allows, for example, the case of trying to
650 * update a block that was later truncated away.
652 if (zero_damaged_pages || InRecovery)
653 MemSet(buffer, 0, BLCKSZ);
656 (errcode(ERRCODE_DATA_CORRUPTED),
657 errmsg("could not read block %u in file \"%s\": read only %d of %d bytes",
658 blocknum, FilePathName(v->mdfd_vfd),
664 * mdwrite() -- Write the supplied block at the appropriate location.
666 * This is to be used only for updating already-existing blocks of a
667 * relation (ie, those before the current EOF). To extend a relation,
671 mdwrite(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum,
672 char *buffer, bool skipFsync)
678 /* This assert is too expensive to have on normally ... */
679 #ifdef CHECK_WRITE_VS_EXTEND
680 Assert(blocknum < mdnblocks(reln, forknum));
683 TRACE_POSTGRESQL_SMGR_MD_WRITE_START(forknum, blocknum,
684 reln->smgr_rnode.node.spcNode,
685 reln->smgr_rnode.node.dbNode,
686 reln->smgr_rnode.node.relNode,
687 reln->smgr_rnode.backend);
689 v = _mdfd_getseg(reln, forknum, blocknum, skipFsync, EXTENSION_FAIL);
691 seekpos = (off_t) BLCKSZ *(blocknum % ((BlockNumber) RELSEG_SIZE));
693 Assert(seekpos < (off_t) BLCKSZ * RELSEG_SIZE);
695 if (FileSeek(v->mdfd_vfd, seekpos, SEEK_SET) != seekpos)
697 (errcode_for_file_access(),
698 errmsg("could not seek to block %u in file \"%s\": %m",
699 blocknum, FilePathName(v->mdfd_vfd))));
701 nbytes = FileWrite(v->mdfd_vfd, buffer, BLCKSZ);
703 TRACE_POSTGRESQL_SMGR_MD_WRITE_DONE(forknum, blocknum,
704 reln->smgr_rnode.node.spcNode,
705 reln->smgr_rnode.node.dbNode,
706 reln->smgr_rnode.node.relNode,
707 reln->smgr_rnode.backend,
711 if (nbytes != BLCKSZ)
715 (errcode_for_file_access(),
716 errmsg("could not write block %u in file \"%s\": %m",
717 blocknum, FilePathName(v->mdfd_vfd))));
718 /* short write: complain appropriately */
720 (errcode(ERRCODE_DISK_FULL),
721 errmsg("could not write block %u in file \"%s\": wrote only %d of %d bytes",
723 FilePathName(v->mdfd_vfd),
725 errhint("Check free disk space.")));
728 if (!skipFsync && !SmgrIsTemp(reln))
729 register_dirty_segment(reln, forknum, v);
733 * mdnblocks() -- Get the number of blocks stored in a relation.
735 * Important side effect: all active segments of the relation are opened
736 * and added to the mdfd_chain list. If this routine has not been
737 * called, then only segments up to the last one actually touched
738 * are present in the chain.
741 mdnblocks(SMgrRelation reln, ForkNumber forknum)
743 MdfdVec *v = mdopen(reln, forknum, EXTENSION_FAIL);
745 BlockNumber segno = 0;
748 * Skip through any segments that aren't the last one, to avoid redundant
749 * seeks on them. We have previously verified that these segments are
750 * exactly RELSEG_SIZE long, and it's useless to recheck that each time.
752 * NOTE: this assumption could only be wrong if another backend has
753 * truncated the relation. We rely on higher code levels to handle that
754 * scenario by closing and re-opening the md fd, which is handled via
755 * relcache flush. (Since the bgwriter doesn't participate in relcache
756 * flush, it could have segment chain entries for inactive segments;
757 * that's OK because the bgwriter never needs to compute relation size.)
759 while (v->mdfd_chain != NULL)
767 nblocks = _mdnblocks(reln, forknum, v);
768 if (nblocks > ((BlockNumber) RELSEG_SIZE))
769 elog(FATAL, "segment too big");
770 if (nblocks < ((BlockNumber) RELSEG_SIZE))
771 return (segno * ((BlockNumber) RELSEG_SIZE)) + nblocks;
774 * If segment is exactly RELSEG_SIZE, advance to next one.
778 if (v->mdfd_chain == NULL)
781 * Because we pass O_CREAT, we will create the next segment (with
782 * zero length) immediately, if the last segment is of length
783 * RELSEG_SIZE. While perhaps not strictly necessary, this keeps
786 v->mdfd_chain = _mdfd_openseg(reln, forknum, segno, O_CREAT);
787 if (v->mdfd_chain == NULL)
789 (errcode_for_file_access(),
790 errmsg("could not open file \"%s\": %m",
791 _mdfd_segpath(reln, forknum, segno))));
799 * mdtruncate() -- Truncate relation to specified number of blocks.
802 mdtruncate(SMgrRelation reln, ForkNumber forknum, BlockNumber nblocks)
806 BlockNumber priorblocks;
809 * NOTE: mdnblocks makes sure we have opened all active segments, so that
810 * truncation loop will get them all!
812 curnblk = mdnblocks(reln, forknum);
813 if (nblocks > curnblk)
815 /* Bogus request ... but no complaint if InRecovery */
819 (errmsg("could not truncate file \"%s\" to %u blocks: it's only %u blocks now",
820 relpath(reln->smgr_rnode, forknum),
823 if (nblocks == curnblk)
824 return; /* no work */
826 v = mdopen(reln, forknum, EXTENSION_FAIL);
833 if (priorblocks > nblocks)
836 * This segment is no longer active (and has already been unlinked
837 * from the mdfd_chain). We truncate the file, but do not delete
838 * it, for reasons explained in the header comments.
840 if (FileTruncate(v->mdfd_vfd, 0) < 0)
842 (errcode_for_file_access(),
843 errmsg("could not truncate file \"%s\": %m",
844 FilePathName(v->mdfd_vfd))));
846 if (!SmgrIsTemp(reln))
847 register_dirty_segment(reln, forknum, v);
849 Assert(ov != reln->md_fd[forknum]); /* we never drop the 1st
853 else if (priorblocks + ((BlockNumber) RELSEG_SIZE) > nblocks)
856 * This is the last segment we want to keep. Truncate the file to
857 * the right length, and clear chain link that points to any
858 * remaining segments (which we shall zap). NOTE: if nblocks is
859 * exactly a multiple K of RELSEG_SIZE, we will truncate the K+1st
860 * segment to 0 length but keep it. This adheres to the invariant
861 * given in the header comments.
863 BlockNumber lastsegblocks = nblocks - priorblocks;
865 if (FileTruncate(v->mdfd_vfd, (off_t) lastsegblocks * BLCKSZ) < 0)
867 (errcode_for_file_access(),
868 errmsg("could not truncate file \"%s\" to %u blocks: %m",
869 FilePathName(v->mdfd_vfd),
871 if (!SmgrIsTemp(reln))
872 register_dirty_segment(reln, forknum, v);
874 ov->mdfd_chain = NULL;
879 * We still need this segment and 0 or more blocks beyond it, so
880 * nothing to do here.
884 priorblocks += RELSEG_SIZE;
889 * mdimmedsync() -- Immediately sync a relation to stable storage.
891 * Note that only writes already issued are synced; this routine knows
892 * nothing of dirty buffers that may exist inside the buffer manager.
895 mdimmedsync(SMgrRelation reln, ForkNumber forknum)
901 * NOTE: mdnblocks makes sure we have opened all active segments, so that
902 * fsync loop will get them all!
904 curnblk = mdnblocks(reln, forknum);
906 v = mdopen(reln, forknum, EXTENSION_FAIL);
910 if (FileSync(v->mdfd_vfd) < 0)
912 (errcode_for_file_access(),
913 errmsg("could not fsync file \"%s\": %m",
914 FilePathName(v->mdfd_vfd))));
920 * mdsync() -- Sync previous writes to stable storage.
925 static bool mdsync_in_progress = false;
927 HASH_SEQ_STATUS hstat;
928 PendingOperationEntry *entry;
931 /* Statistics on sync times */
933 instr_time sync_start,
938 uint64 total_elapsed = 0;
941 * This is only called during checkpoints, and checkpoints should only
942 * occur in processes that have created a pendingOpsTable.
944 if (!pendingOpsTable)
945 elog(ERROR, "cannot sync without a pendingOpsTable");
948 * If we are in the bgwriter, the sync had better include all fsync
949 * requests that were queued by backends up to this point. The tightest
950 * race condition that could occur is that a buffer that must be written
951 * and fsync'd for the checkpoint could have been dumped by a backend just
952 * before it was visited by BufferSync(). We know the backend will have
953 * queued an fsync request before clearing the buffer's dirtybit, so we
954 * are safe as long as we do an Absorb after completing BufferSync().
956 AbsorbFsyncRequests();
959 * To avoid excess fsync'ing (in the worst case, maybe a never-terminating
960 * checkpoint), we want to ignore fsync requests that are entered into the
961 * hashtable after this point --- they should be processed next time,
962 * instead. We use mdsync_cycle_ctr to tell old entries apart from new
963 * ones: new ones will have cycle_ctr equal to the incremented value of
966 * In normal circumstances, all entries present in the table at this point
967 * will have cycle_ctr exactly equal to the current (about to be old)
968 * value of mdsync_cycle_ctr. However, if we fail partway through the
969 * fsync'ing loop, then older values of cycle_ctr might remain when we
970 * come back here to try again. Repeated checkpoint failures would
971 * eventually wrap the counter around to the point where an old entry
972 * might appear new, causing us to skip it, possibly allowing a checkpoint
973 * to succeed that should not have. To forestall wraparound, any time the
974 * previous mdsync() failed to complete, run through the table and
975 * forcibly set cycle_ctr = mdsync_cycle_ctr.
977 * Think not to merge this loop with the main loop, as the problem is
978 * exactly that that loop may fail before having visited all the entries.
979 * From a performance point of view it doesn't matter anyway, as this path
980 * will never be taken in a system that's functioning normally.
982 if (mdsync_in_progress)
984 /* prior try failed, so update any stale cycle_ctr values */
985 hash_seq_init(&hstat, pendingOpsTable);
986 while ((entry = (PendingOperationEntry *) hash_seq_search(&hstat)) != NULL)
988 entry->cycle_ctr = mdsync_cycle_ctr;
992 /* Advance counter so that new hashtable entries are distinguishable */
995 /* Set flag to detect failure if we don't reach the end of the loop */
996 mdsync_in_progress = true;
998 /* Now scan the hashtable for fsync requests to process */
999 absorb_counter = FSYNCS_PER_ABSORB;
1000 hash_seq_init(&hstat, pendingOpsTable);
1001 while ((entry = (PendingOperationEntry *) hash_seq_search(&hstat)) != NULL)
1004 * If the entry is new then don't process it this time. Note that
1005 * "continue" bypasses the hash-remove call at the bottom of the loop.
1007 if (entry->cycle_ctr == mdsync_cycle_ctr)
1010 /* Else assert we haven't missed it */
1011 Assert((CycleCtr) (entry->cycle_ctr + 1) == mdsync_cycle_ctr);
1014 * If fsync is off then we don't have to bother opening the file at
1015 * all. (We delay checking until this point so that changing fsync on
1016 * the fly behaves sensibly.) Also, if the entry is marked canceled,
1017 * fall through to delete it.
1019 if (enableFsync && !entry->canceled)
1024 * If in bgwriter, we want to absorb pending requests every so
1025 * often to prevent overflow of the fsync request queue. It is
1026 * unspecified whether newly-added entries will be visited by
1027 * hash_seq_search, but we don't care since we don't need to
1028 * process them anyway.
1030 if (--absorb_counter <= 0)
1032 AbsorbFsyncRequests();
1033 absorb_counter = FSYNCS_PER_ABSORB;
1037 * The fsync table could contain requests to fsync segments that
1038 * have been deleted (unlinked) by the time we get to them. Rather
1039 * than just hoping an ENOENT (or EACCES on Windows) error can be
1040 * ignored, what we do on error is absorb pending requests and
1041 * then retry. Since mdunlink() queues a "revoke" message before
1042 * actually unlinking, the fsync request is guaranteed to be
1043 * marked canceled after the absorb if it really was this case.
1044 * DROP DATABASE likewise has to tell us to forget fsync requests
1045 * before it starts deletions.
1047 for (failures = 0;; failures++) /* loop exits at "break" */
1054 * Find or create an smgr hash entry for this relation. This
1055 * may seem a bit unclean -- md calling smgr? But it's really
1056 * the best solution. It ensures that the open file reference
1057 * isn't permanently leaked if we get an error here. (You may
1058 * say "but an unreferenced SMgrRelation is still a leak!" Not
1059 * really, because the only case in which a checkpoint is done
1060 * by a process that isn't about to shut down is in the
1061 * bgwriter, and it will periodically do smgrcloseall(). This
1062 * fact justifies our not closing the reln in the success path
1063 * either, which is a good thing since in non-bgwriter cases
1064 * we couldn't safely do that.) Furthermore, in many cases
1065 * the relation will have been dirtied through this same smgr
1066 * relation, and so we can save a file open/close cycle.
1068 reln = smgropen(entry->tag.rnode.node,
1069 entry->tag.rnode.backend);
1072 * It is possible that the relation has been dropped or
1073 * truncated since the fsync request was entered. Therefore,
1074 * allow ENOENT, but only if we didn't fail already on this
1075 * file. This applies both during _mdfd_getseg() and during
1076 * FileSync, since fd.c might have closed the file behind our
1079 seg = _mdfd_getseg(reln, entry->tag.forknum,
1080 entry->tag.segno * ((BlockNumber) RELSEG_SIZE),
1081 false, EXTENSION_RETURN_NULL);
1083 if (log_checkpoints)
1084 INSTR_TIME_SET_CURRENT(sync_start);
1086 INSTR_TIME_SET_ZERO(sync_start);
1089 FileSync(seg->mdfd_vfd) >= 0)
1091 if (log_checkpoints && (! INSTR_TIME_IS_ZERO(sync_start)))
1093 INSTR_TIME_SET_CURRENT(sync_end);
1094 sync_diff = sync_end;
1095 INSTR_TIME_SUBTRACT(sync_diff, sync_start);
1096 elapsed = INSTR_TIME_GET_MICROSEC(sync_diff);
1097 if (elapsed > longest)
1099 total_elapsed += elapsed;
1101 elog(DEBUG1, "checkpoint sync: number=%d file=%s time=%.3f msec",
1102 processed, FilePathName(seg->mdfd_vfd), (double) elapsed / 1000);
1105 break; /* success; break out of retry loop */
1109 * XXX is there any point in allowing more than one retry?
1110 * Don't see one at the moment, but easy to change the test
1113 path = _mdfd_segpath(reln, entry->tag.forknum,
1115 if (!FILE_POSSIBLY_DELETED(errno) ||
1118 (errcode_for_file_access(),
1119 errmsg("could not fsync file \"%s\": %m", path)));
1122 (errcode_for_file_access(),
1123 errmsg("could not fsync file \"%s\" but retrying: %m",
1128 * Absorb incoming requests and check to see if canceled.
1130 AbsorbFsyncRequests();
1131 absorb_counter = FSYNCS_PER_ABSORB; /* might as well... */
1133 if (entry->canceled)
1135 } /* end retry loop */
1139 * If we get here, either we fsync'd successfully, or we don't have to
1140 * because enableFsync is off, or the entry is (now) marked canceled.
1141 * Okay to delete it.
1143 if (hash_search(pendingOpsTable, &entry->tag,
1144 HASH_REMOVE, NULL) == NULL)
1145 elog(ERROR, "pendingOpsTable corrupted");
1146 } /* end loop over hashtable entries */
1148 /* Return sync performance metrics for report at checkpoint end */
1149 CheckpointStats.ckpt_sync_rels = processed;
1150 CheckpointStats.ckpt_longest_sync = longest;
1151 CheckpointStats.ckpt_agg_sync_time = total_elapsed;
1153 /* Flag successful completion of mdsync */
1154 mdsync_in_progress = false;
1158 * mdpreckpt() -- Do pre-checkpoint work
1160 * To distinguish unlink requests that arrived before this checkpoint
1161 * started from those that arrived during the checkpoint, we use a cycle
1162 * counter similar to the one we use for fsync requests. That cycle
1163 * counter is incremented here.
1165 * This must be called *before* the checkpoint REDO point is determined.
1166 * That ensures that we won't delete files too soon.
1168 * Note that we can't do anything here that depends on the assumption
1169 * that the checkpoint will be completed.
1177 * In case the prior checkpoint wasn't completed, stamp all entries in the
1178 * list with the current cycle counter. Anything that's in the list at
1179 * the start of checkpoint can surely be deleted after the checkpoint is
1180 * finished, regardless of when the request was made.
1182 foreach(cell, pendingUnlinks)
1184 PendingUnlinkEntry *entry = (PendingUnlinkEntry *) lfirst(cell);
1186 entry->cycle_ctr = mdckpt_cycle_ctr;
1190 * Any unlink requests arriving after this point will be assigned the next
1191 * cycle counter, and won't be unlinked until next checkpoint.
1197 * mdpostckpt() -- Do post-checkpoint work
1199 * Remove any lingering files that can now be safely removed.
1204 while (pendingUnlinks != NIL)
1206 PendingUnlinkEntry *entry = (PendingUnlinkEntry *) linitial(pendingUnlinks);
1210 * New entries are appended to the end, so if the entry is new we've
1211 * reached the end of old entries.
1213 if (entry->cycle_ctr == mdckpt_cycle_ctr)
1216 /* Else assert we haven't missed it */
1217 Assert((CycleCtr) (entry->cycle_ctr + 1) == mdckpt_cycle_ctr);
1219 /* Unlink the file */
1220 path = relpath(entry->rnode, MAIN_FORKNUM);
1221 if (unlink(path) < 0)
1224 * There's a race condition, when the database is dropped at the
1225 * same time that we process the pending unlink requests. If the
1226 * DROP DATABASE deletes the file before we do, we will get ENOENT
1227 * here. rmtree() also has to ignore ENOENT errors, to deal with
1228 * the possibility that we delete the file first.
1230 if (errno != ENOENT)
1232 (errcode_for_file_access(),
1233 errmsg("could not remove file \"%s\": %m", path)));
1237 pendingUnlinks = list_delete_first(pendingUnlinks);
1243 * register_dirty_segment() -- Mark a relation segment as needing fsync
1245 * If there is a local pending-ops table, just make an entry in it for
1246 * mdsync to process later. Otherwise, try to pass off the fsync request
1247 * to the background writer process. If that fails, just do the fsync
1248 * locally before returning (we expect this will not happen often enough
1249 * to be a performance problem).
1252 register_dirty_segment(SMgrRelation reln, ForkNumber forknum, MdfdVec *seg)
1254 if (pendingOpsTable)
1256 /* push it into local pending-ops table */
1257 RememberFsyncRequest(reln->smgr_rnode, forknum, seg->mdfd_segno);
1261 if (ForwardFsyncRequest(reln->smgr_rnode, forknum, seg->mdfd_segno))
1262 return; /* passed it off successfully */
1265 (errmsg("could not forward fsync request because request queue is full")));
1267 if (FileSync(seg->mdfd_vfd) < 0)
1269 (errcode_for_file_access(),
1270 errmsg("could not fsync file \"%s\": %m",
1271 FilePathName(seg->mdfd_vfd))));
1276 * register_unlink() -- Schedule a file to be deleted after next checkpoint
1278 * As with register_dirty_segment, this could involve either a local or
1279 * a remote pending-ops table.
1282 register_unlink(RelFileNodeBackend rnode)
1284 if (pendingOpsTable)
1286 /* push it into local pending-ops table */
1287 RememberFsyncRequest(rnode, MAIN_FORKNUM, UNLINK_RELATION_REQUEST);
1292 * Notify the bgwriter about it. If we fail to queue the request
1293 * message, we have to sleep and try again, because we can't simply
1294 * delete the file now. Ugly, but hopefully won't happen often.
1296 * XXX should we just leave the file orphaned instead?
1298 Assert(IsUnderPostmaster);
1299 while (!ForwardFsyncRequest(rnode, MAIN_FORKNUM,
1300 UNLINK_RELATION_REQUEST))
1301 pg_usleep(10000L); /* 10 msec seems a good number */
1306 * RememberFsyncRequest() -- callback from bgwriter side of fsync request
1308 * We stuff most fsync requests into the local hash table for execution
1309 * during the bgwriter's next checkpoint. UNLINK requests go into a
1310 * separate linked list, however, because they get processed separately.
1312 * The range of possible segment numbers is way less than the range of
1313 * BlockNumber, so we can reserve high values of segno for special purposes.
1315 * - FORGET_RELATION_FSYNC means to cancel pending fsyncs for a relation
1316 * - FORGET_DATABASE_FSYNC means to cancel pending fsyncs for a whole database
1317 * - UNLINK_RELATION_REQUEST is a request to delete the file after the next
1320 * (Handling the FORGET_* requests is a tad slow because the hash table has
1321 * to be searched linearly, but it doesn't seem worth rethinking the table
1322 * structure for them.)
1325 RememberFsyncRequest(RelFileNodeBackend rnode, ForkNumber forknum,
1328 Assert(pendingOpsTable);
1330 if (segno == FORGET_RELATION_FSYNC)
1332 /* Remove any pending requests for the entire relation */
1333 HASH_SEQ_STATUS hstat;
1334 PendingOperationEntry *entry;
1336 hash_seq_init(&hstat, pendingOpsTable);
1337 while ((entry = (PendingOperationEntry *) hash_seq_search(&hstat)) != NULL)
1339 if (RelFileNodeBackendEquals(entry->tag.rnode, rnode) &&
1340 entry->tag.forknum == forknum)
1342 /* Okay, cancel this entry */
1343 entry->canceled = true;
1347 else if (segno == FORGET_DATABASE_FSYNC)
1349 /* Remove any pending requests for the entire database */
1350 HASH_SEQ_STATUS hstat;
1351 PendingOperationEntry *entry;
1356 /* Remove fsync requests */
1357 hash_seq_init(&hstat, pendingOpsTable);
1358 while ((entry = (PendingOperationEntry *) hash_seq_search(&hstat)) != NULL)
1360 if (entry->tag.rnode.node.dbNode == rnode.node.dbNode)
1362 /* Okay, cancel this entry */
1363 entry->canceled = true;
1367 /* Remove unlink requests */
1369 for (cell = list_head(pendingUnlinks); cell; cell = next)
1371 PendingUnlinkEntry *entry = (PendingUnlinkEntry *) lfirst(cell);
1374 if (entry->rnode.node.dbNode == rnode.node.dbNode)
1376 pendingUnlinks = list_delete_cell(pendingUnlinks, cell, prev);
1383 else if (segno == UNLINK_RELATION_REQUEST)
1385 /* Unlink request: put it in the linked list */
1386 MemoryContext oldcxt = MemoryContextSwitchTo(MdCxt);
1387 PendingUnlinkEntry *entry;
1389 entry = palloc(sizeof(PendingUnlinkEntry));
1390 entry->rnode = rnode;
1391 entry->cycle_ctr = mdckpt_cycle_ctr;
1393 pendingUnlinks = lappend(pendingUnlinks, entry);
1395 MemoryContextSwitchTo(oldcxt);
1399 /* Normal case: enter a request to fsync this segment */
1400 PendingOperationTag key;
1401 PendingOperationEntry *entry;
1404 /* ensure any pad bytes in the hash key are zeroed */
1405 MemSet(&key, 0, sizeof(key));
1407 key.forknum = forknum;
1410 entry = (PendingOperationEntry *) hash_search(pendingOpsTable,
1414 /* if new or previously canceled entry, initialize it */
1415 if (!found || entry->canceled)
1417 entry->canceled = false;
1418 entry->cycle_ctr = mdsync_cycle_ctr;
1422 * NB: it's intentional that we don't change cycle_ctr if the entry
1423 * already exists. The fsync request must be treated as old, even
1424 * though the new request will be satisfied too by any subsequent
1427 * However, if the entry is present but is marked canceled, we should
1428 * act just as though it wasn't there. The only case where this could
1429 * happen would be if a file had been deleted, we received but did not
1430 * yet act on the cancel request, and the same relfilenode was then
1431 * assigned to a new file. We mustn't lose the new request, but it
1432 * should be considered new not old.
1438 * ForgetRelationFsyncRequests -- forget any fsyncs for a rel
1441 ForgetRelationFsyncRequests(RelFileNodeBackend rnode, ForkNumber forknum)
1443 if (pendingOpsTable)
1445 /* standalone backend or startup process: fsync state is local */
1446 RememberFsyncRequest(rnode, forknum, FORGET_RELATION_FSYNC);
1448 else if (IsUnderPostmaster)
1451 * Notify the bgwriter about it. If we fail to queue the revoke
1452 * message, we have to sleep and try again ... ugly, but hopefully
1453 * won't happen often.
1455 * XXX should we CHECK_FOR_INTERRUPTS in this loop? Escaping with an
1456 * error would leave the no-longer-used file still present on disk,
1457 * which would be bad, so I'm inclined to assume that the bgwriter
1458 * will always empty the queue soon.
1460 while (!ForwardFsyncRequest(rnode, forknum, FORGET_RELATION_FSYNC))
1461 pg_usleep(10000L); /* 10 msec seems a good number */
1464 * Note we don't wait for the bgwriter to actually absorb the revoke
1465 * message; see mdsync() for the implications.
1471 * ForgetDatabaseFsyncRequests -- forget any fsyncs and unlinks for a DB
1474 ForgetDatabaseFsyncRequests(Oid dbid)
1476 RelFileNodeBackend rnode;
1478 rnode.node.dbNode = dbid;
1479 rnode.node.spcNode = 0;
1480 rnode.node.relNode = 0;
1481 rnode.backend = InvalidBackendId;
1483 if (pendingOpsTable)
1485 /* standalone backend or startup process: fsync state is local */
1486 RememberFsyncRequest(rnode, InvalidForkNumber, FORGET_DATABASE_FSYNC);
1488 else if (IsUnderPostmaster)
1490 /* see notes in ForgetRelationFsyncRequests */
1491 while (!ForwardFsyncRequest(rnode, InvalidForkNumber,
1492 FORGET_DATABASE_FSYNC))
1493 pg_usleep(10000L); /* 10 msec seems a good number */
1499 * _fdvec_alloc() -- Make a MdfdVec object.
1504 return (MdfdVec *) MemoryContextAlloc(MdCxt, sizeof(MdfdVec));
1508 * Return the filename for the specified segment of the relation. The
1509 * returned string is palloc'd.
1512 _mdfd_segpath(SMgrRelation reln, ForkNumber forknum, BlockNumber segno)
1517 path = relpath(reln->smgr_rnode, forknum);
1521 /* be sure we have enough space for the '.segno' */
1522 fullpath = (char *) palloc(strlen(path) + 12);
1523 sprintf(fullpath, "%s.%u", path, segno);
1533 * Open the specified segment of the relation,
1534 * and make a MdfdVec object for it. Returns NULL on failure.
1537 _mdfd_openseg(SMgrRelation reln, ForkNumber forknum, BlockNumber segno,
1544 fullpath = _mdfd_segpath(reln, forknum, segno);
1547 fd = PathNameOpenFile(fullpath, O_RDWR | PG_BINARY | oflags, 0600);
1554 /* allocate an mdfdvec entry for it */
1557 /* fill the entry */
1559 v->mdfd_segno = segno;
1560 v->mdfd_chain = NULL;
1561 Assert(_mdnblocks(reln, forknum, v) <= ((BlockNumber) RELSEG_SIZE));
1568 * _mdfd_getseg() -- Find the segment of the relation holding the
1571 * If the segment doesn't exist, we ereport, return NULL, or create the
1572 * segment, according to "behavior". Note: skipFsync is only used in the
1573 * EXTENSION_CREATE case.
1576 _mdfd_getseg(SMgrRelation reln, ForkNumber forknum, BlockNumber blkno,
1577 bool skipFsync, ExtensionBehavior behavior)
1579 MdfdVec *v = mdopen(reln, forknum, behavior);
1580 BlockNumber targetseg;
1581 BlockNumber nextsegno;
1584 return NULL; /* only possible if EXTENSION_RETURN_NULL */
1586 targetseg = blkno / ((BlockNumber) RELSEG_SIZE);
1587 for (nextsegno = 1; nextsegno <= targetseg; nextsegno++)
1589 Assert(nextsegno == v->mdfd_segno + 1);
1591 if (v->mdfd_chain == NULL)
1594 * Normally we will create new segments only if authorized by the
1595 * caller (i.e., we are doing mdextend()). But when doing WAL
1596 * recovery, create segments anyway; this allows cases such as
1597 * replaying WAL data that has a write into a high-numbered
1598 * segment of a relation that was later deleted. We want to go
1599 * ahead and create the segments so we can finish out the replay.
1601 * We have to maintain the invariant that segments before the last
1602 * active segment are of size RELSEG_SIZE; therefore, pad them out
1603 * with zeroes if needed. (This only matters if caller is
1604 * extending the relation discontiguously, but that can happen in
1607 if (behavior == EXTENSION_CREATE || InRecovery)
1609 if (_mdnblocks(reln, forknum, v) < RELSEG_SIZE)
1611 char *zerobuf = palloc0(BLCKSZ);
1613 mdextend(reln, forknum,
1614 nextsegno * ((BlockNumber) RELSEG_SIZE) - 1,
1615 zerobuf, skipFsync);
1618 v->mdfd_chain = _mdfd_openseg(reln, forknum, +nextsegno, O_CREAT);
1622 /* We won't create segment if not existent */
1623 v->mdfd_chain = _mdfd_openseg(reln, forknum, nextsegno, 0);
1625 if (v->mdfd_chain == NULL)
1627 if (behavior == EXTENSION_RETURN_NULL &&
1628 FILE_POSSIBLY_DELETED(errno))
1631 (errcode_for_file_access(),
1632 errmsg("could not open file \"%s\" (target block %u): %m",
1633 _mdfd_segpath(reln, forknum, nextsegno),
1643 * Get number of blocks present in a single disk file
1646 _mdnblocks(SMgrRelation reln, ForkNumber forknum, MdfdVec *seg)
1650 len = FileSeek(seg->mdfd_vfd, 0L, SEEK_END);
1653 (errcode_for_file_access(),
1654 errmsg("could not seek to end of file \"%s\": %m",
1655 FilePathName(seg->mdfd_vfd))));
1656 /* note that this calculation will ignore any partial block at EOF */
1657 return (BlockNumber) (len / BLCKSZ);