1 /*-------------------------------------------------------------------------
4 * This code manages relations that reside on magnetic disk.
6 * Portions Copyright (c) 1996-2011, 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
38 * Special values for the segno arg to RememberFsyncRequest.
40 * Note that CompactBgwriterRequestQueue assumes that it's OK to remove an
41 * fsync request from the queue if an identical, subsequent request is found.
42 * See comments there before making changes here.
44 #define FORGET_RELATION_FSYNC (InvalidBlockNumber)
45 #define FORGET_DATABASE_FSYNC (InvalidBlockNumber-1)
46 #define UNLINK_RELATION_REQUEST (InvalidBlockNumber-2)
49 * On Windows, we have to interpret EACCES as possibly meaning the same as
50 * ENOENT, because if a file is unlinked-but-not-yet-gone on that platform,
51 * that's what you get. Ugh. This code is designed so that we don't
52 * actually believe these cases are okay without further evidence (namely,
53 * a pending fsync request getting revoked ... see mdsync).
56 #define FILE_POSSIBLY_DELETED(err) ((err) == ENOENT)
58 #define FILE_POSSIBLY_DELETED(err) ((err) == ENOENT || (err) == EACCES)
62 * The magnetic disk storage manager keeps track of open file
63 * descriptors in its own descriptor pool. This is done to make it
64 * easier to support relations that are larger than the operating
65 * system's file size limit (often 2GBytes). In order to do that,
66 * we break relations up into "segment" files that are each shorter than
67 * the OS file size limit. The segment size is set by the RELSEG_SIZE
68 * configuration constant in pg_config.h.
70 * On disk, a relation must consist of consecutively numbered segment
71 * files in the pattern
72 * -- Zero or more full segments of exactly RELSEG_SIZE blocks each
73 * -- Exactly one partial segment of size 0 <= size < RELSEG_SIZE blocks
74 * -- Optionally, any number of inactive segments of size 0 blocks.
75 * The full and partial segments are collectively the "active" segments.
76 * Inactive segments are those that once contained data but are currently
77 * not needed because of an mdtruncate() operation. The reason for leaving
78 * them present at size zero, rather than unlinking them, is that other
79 * backends and/or the bgwriter might be holding open file references to
80 * such segments. If the relation expands again after mdtruncate(), such
81 * that a deactivated segment becomes active again, it is important that
82 * such file references still be valid --- else data might get written
83 * out to an unlinked old copy of a segment file that will eventually
86 * The file descriptor pointer (md_fd field) stored in the SMgrRelation
87 * cache is, therefore, just the head of a list of MdfdVec objects, one
88 * per segment. But note the md_fd pointer can be NULL, indicating
91 * Also note that mdfd_chain == NULL does not necessarily mean the relation
92 * doesn't have another segment after this one; we may just not have
93 * opened the next segment yet. (We could not have "all segments are
94 * in the chain" as an invariant anyway, since another backend could
95 * extend the relation when we weren't looking.) We do not make chain
96 * entries for inactive segments, however; as soon as we find a partial
97 * segment, we assume that any subsequent segments are inactive.
99 * All MdfdVec objects are palloc'd in the MdCxt memory context.
102 typedef struct _MdfdVec
104 File mdfd_vfd; /* fd number in fd.c's pool */
105 BlockNumber mdfd_segno; /* segment number, from 0 */
106 struct _MdfdVec *mdfd_chain; /* next segment, or NULL */
109 static MemoryContext MdCxt; /* context for all md.c allocations */
113 * In some contexts (currently, standalone backends and the bgwriter process)
114 * we keep track of pending fsync operations: we need to remember all relation
115 * segments that have been written since the last checkpoint, so that we can
116 * fsync them down to disk before completing the next checkpoint. This hash
117 * table remembers the pending operations. We use a hash table mostly as
118 * a convenient way of eliminating duplicate requests.
120 * We use a similar mechanism to remember no-longer-needed files that can
121 * be deleted after the next checkpoint, but we use a linked list instead of
122 * a hash table, because we don't expect there to be any duplicate requests.
124 * (Regular backends do not track pending operations locally, but forward
125 * them to the bgwriter.)
129 RelFileNodeBackend rnode; /* the targeted relation */
131 BlockNumber segno; /* which segment */
132 } PendingOperationTag;
134 typedef uint16 CycleCtr; /* can be any convenient integer size */
138 PendingOperationTag tag; /* hash table key (must be first!) */
139 bool canceled; /* T => request canceled, not yet removed */
140 CycleCtr cycle_ctr; /* mdsync_cycle_ctr when request was made */
141 } PendingOperationEntry;
145 RelFileNodeBackend rnode; /* the dead relation to delete */
146 CycleCtr cycle_ctr; /* mdckpt_cycle_ctr when request was made */
147 } PendingUnlinkEntry;
149 static HTAB *pendingOpsTable = NULL;
150 static List *pendingUnlinks = NIL;
152 static CycleCtr mdsync_cycle_ctr = 0;
153 static CycleCtr mdckpt_cycle_ctr = 0;
156 typedef enum /* behavior for mdopen & _mdfd_getseg */
158 EXTENSION_FAIL, /* ereport if segment not present */
159 EXTENSION_RETURN_NULL, /* return NULL if not present */
160 EXTENSION_CREATE /* create new segments as needed */
164 static MdfdVec *mdopen(SMgrRelation reln, ForkNumber forknum,
165 ExtensionBehavior behavior);
166 static void register_dirty_segment(SMgrRelation reln, ForkNumber forknum,
168 static void register_unlink(RelFileNodeBackend rnode);
169 static MdfdVec *_fdvec_alloc(void);
170 static char *_mdfd_segpath(SMgrRelation reln, ForkNumber forknum,
172 static MdfdVec *_mdfd_openseg(SMgrRelation reln, ForkNumber forkno,
173 BlockNumber segno, int oflags);
174 static MdfdVec *_mdfd_getseg(SMgrRelation reln, ForkNumber forkno,
175 BlockNumber blkno, bool skipFsync, ExtensionBehavior behavior);
176 static BlockNumber _mdnblocks(SMgrRelation reln, ForkNumber forknum,
181 * mdinit() -- Initialize private state for magnetic disk storage manager.
186 MdCxt = AllocSetContextCreate(TopMemoryContext,
188 ALLOCSET_DEFAULT_MINSIZE,
189 ALLOCSET_DEFAULT_INITSIZE,
190 ALLOCSET_DEFAULT_MAXSIZE);
193 * Create pending-operations hashtable if we need it. Currently, we need
194 * it if we are standalone (not under a postmaster) OR if we are a
195 * bootstrap-mode subprocess of a postmaster (that is, a startup or
198 if (!IsUnderPostmaster || IsBootstrapProcessingMode())
202 MemSet(&hash_ctl, 0, sizeof(hash_ctl));
203 hash_ctl.keysize = sizeof(PendingOperationTag);
204 hash_ctl.entrysize = sizeof(PendingOperationEntry);
205 hash_ctl.hash = tag_hash;
206 hash_ctl.hcxt = MdCxt;
207 pendingOpsTable = hash_create("Pending Ops Table",
210 HASH_ELEM | HASH_FUNCTION | HASH_CONTEXT);
211 pendingUnlinks = NIL;
216 * In archive recovery, we rely on bgwriter to do fsyncs, but we will have
217 * already created the pendingOpsTable during initialization of the startup
218 * process. Calling this function drops the local pendingOpsTable so that
219 * subsequent requests will be forwarded to bgwriter.
222 SetForwardFsyncRequests(void)
224 /* Perform any pending ops we may have queued up */
227 pendingOpsTable = NULL;
231 * mdexists() -- Does the physical file exist?
233 * Note: this will return true for lingering files, with pending deletions
236 mdexists(SMgrRelation reln, ForkNumber forkNum)
239 * Close it first, to ensure that we notice if the fork has been unlinked
240 * since we opened it.
242 mdclose(reln, forkNum);
244 return (mdopen(reln, forkNum, EXTENSION_RETURN_NULL) != NULL);
248 * mdcreate() -- Create a new relation on magnetic disk.
250 * If isRedo is true, it's okay for the relation to exist already.
253 mdcreate(SMgrRelation reln, ForkNumber forkNum, bool isRedo)
258 if (isRedo && reln->md_fd[forkNum] != NULL)
259 return; /* created and opened already... */
261 Assert(reln->md_fd[forkNum] == NULL);
263 path = relpath(reln->smgr_rnode, forkNum);
265 fd = PathNameOpenFile(path, O_RDWR | O_CREAT | O_EXCL | PG_BINARY, 0600);
269 int save_errno = errno;
272 * During bootstrap, there are cases where a system relation will be
273 * accessed (by internal backend processes) before the bootstrap
274 * script nominally creates it. Therefore, allow the file to exist
275 * already, even if isRedo is not set. (See also mdopen)
277 if (isRedo || IsBootstrapProcessingMode())
278 fd = PathNameOpenFile(path, O_RDWR | PG_BINARY, 0600);
281 /* be sure to report the error reported by create, not open */
284 (errcode_for_file_access(),
285 errmsg("could not create file \"%s\": %m", path)));
291 reln->md_fd[forkNum] = _fdvec_alloc();
293 reln->md_fd[forkNum]->mdfd_vfd = fd;
294 reln->md_fd[forkNum]->mdfd_segno = 0;
295 reln->md_fd[forkNum]->mdfd_chain = NULL;
299 * mdunlink() -- Unlink a relation.
301 * Note that we're passed a RelFileNode --- by the time this is called,
302 * there won't be an SMgrRelation hashtable entry anymore.
304 * Actually, we don't unlink the first segment file of the relation, but
305 * just truncate it to zero length, and record a request to unlink it after
306 * the next checkpoint. Additional segments can be unlinked immediately,
307 * however. Leaving the empty file in place prevents that relfilenode
308 * number from being reused. The scenario this protects us from is:
309 * 1. We delete a relation (and commit, and actually remove its file).
310 * 2. We create a new relation, which by chance gets the same relfilenode as
311 * the just-deleted one (OIDs must've wrapped around for that to happen).
312 * 3. We crash before another checkpoint occurs.
313 * During replay, we would delete the file and then recreate it, which is fine
314 * if the contents of the file were repopulated by subsequent WAL entries.
315 * But if we didn't WAL-log insertions, but instead relied on fsyncing the
316 * file after populating it (as for instance CLUSTER and CREATE INDEX do),
317 * the contents of the file would be lost forever. By leaving the empty file
318 * until after the next checkpoint, we prevent reassignment of the relfilenode
319 * number until it's safe, because relfilenode assignment skips over any
322 * If isRedo is true, it's okay for the relation to be already gone.
323 * Also, we should remove the file immediately instead of queuing a request
324 * for later, since during redo there's no possibility of creating a
325 * conflicting relation.
327 * Note: any failure should be reported as WARNING not ERROR, because
328 * we are usually not in a transaction anymore when this is called.
331 mdunlink(RelFileNodeBackend rnode, ForkNumber forkNum, bool isRedo)
337 * We have to clean out any pending fsync requests for the doomed
338 * relation, else the next mdsync() will fail.
340 ForgetRelationFsyncRequests(rnode, forkNum);
342 path = relpath(rnode, forkNum);
345 * Delete or truncate the first segment.
347 if (isRedo || forkNum != MAIN_FORKNUM)
352 if (!isRedo || errno != ENOENT)
354 (errcode_for_file_access(),
355 errmsg("could not remove file \"%s\": %m", path)));
360 /* truncate(2) would be easier here, but Windows hasn't got it */
363 fd = BasicOpenFile(path, O_RDWR | PG_BINARY, 0);
368 ret = ftruncate(fd, 0);
375 if (ret < 0 && errno != ENOENT)
377 (errcode_for_file_access(),
378 errmsg("could not truncate file \"%s\": %m", path)));
382 * Delete any additional segments.
386 char *segpath = (char *) palloc(strlen(path) + 12);
390 * Note that because we loop until getting ENOENT, we will correctly
391 * remove all inactive segments as well as active ones.
393 for (segno = 1;; segno++)
395 sprintf(segpath, "%s.%u", path, segno);
396 if (unlink(segpath) < 0)
398 /* ENOENT is expected after the last segment... */
401 (errcode_for_file_access(),
402 errmsg("could not remove file \"%s\": %m", segpath)));
411 /* Register request to unlink first segment later */
412 if (!isRedo && forkNum == MAIN_FORKNUM)
413 register_unlink(rnode);
417 * mdextend() -- Add a block to the specified relation.
419 * The semantics are nearly the same as mdwrite(): write at the
420 * specified position. However, this is to be used for the case of
421 * extending a relation (i.e., blocknum is at or beyond the current
422 * EOF). Note that we assume writing a block beyond current EOF
423 * causes intervening file space to become filled with zeroes.
426 mdextend(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum,
427 char *buffer, bool skipFsync)
433 /* This assert is too expensive to have on normally ... */
434 #ifdef CHECK_WRITE_VS_EXTEND
435 Assert(blocknum >= mdnblocks(reln, forknum));
439 * If a relation manages to grow to 2^32-1 blocks, refuse to extend it any
440 * more --- we mustn't create a block whose number actually is
441 * InvalidBlockNumber.
443 if (blocknum == InvalidBlockNumber)
445 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
446 errmsg("cannot extend file \"%s\" beyond %u blocks",
447 relpath(reln->smgr_rnode, forknum),
448 InvalidBlockNumber)));
450 v = _mdfd_getseg(reln, forknum, blocknum, skipFsync, EXTENSION_CREATE);
452 seekpos = (off_t) BLCKSZ *(blocknum % ((BlockNumber) RELSEG_SIZE));
454 Assert(seekpos < (off_t) BLCKSZ * RELSEG_SIZE);
457 * Note: because caller usually obtained blocknum by calling mdnblocks,
458 * which did a seek(SEEK_END), this seek is often redundant and will be
459 * optimized away by fd.c. It's not redundant, however, if there is a
460 * partial page at the end of the file. In that case we want to try to
461 * overwrite the partial page with a full page. It's also not redundant
462 * if bufmgr.c had to dump another buffer of the same file to make room
463 * for the new page's buffer.
465 if (FileSeek(v->mdfd_vfd, seekpos, SEEK_SET) != seekpos)
467 (errcode_for_file_access(),
468 errmsg("could not seek to block %u in file \"%s\": %m",
469 blocknum, FilePathName(v->mdfd_vfd))));
471 if ((nbytes = FileWrite(v->mdfd_vfd, buffer, BLCKSZ)) != BLCKSZ)
475 (errcode_for_file_access(),
476 errmsg("could not extend file \"%s\": %m",
477 FilePathName(v->mdfd_vfd)),
478 errhint("Check free disk space.")));
479 /* short write: complain appropriately */
481 (errcode(ERRCODE_DISK_FULL),
482 errmsg("could not extend file \"%s\": wrote only %d of %d bytes at block %u",
483 FilePathName(v->mdfd_vfd),
484 nbytes, BLCKSZ, blocknum),
485 errhint("Check free disk space.")));
488 if (!skipFsync && !SmgrIsTemp(reln))
489 register_dirty_segment(reln, forknum, v);
491 Assert(_mdnblocks(reln, forknum, v) <= ((BlockNumber) RELSEG_SIZE));
495 * mdopen() -- Open the specified relation.
497 * Note we only open the first segment, when there are multiple segments.
499 * If first segment is not present, either ereport or return NULL according
500 * to "behavior". We treat EXTENSION_CREATE the same as EXTENSION_FAIL;
501 * EXTENSION_CREATE means it's OK to extend an existing relation, not to
502 * invent one out of whole cloth.
505 mdopen(SMgrRelation reln, ForkNumber forknum, ExtensionBehavior behavior)
511 /* No work if already open */
512 if (reln->md_fd[forknum])
513 return reln->md_fd[forknum];
515 path = relpath(reln->smgr_rnode, forknum);
517 fd = PathNameOpenFile(path, O_RDWR | PG_BINARY, 0600);
522 * During bootstrap, there are cases where a system relation will be
523 * accessed (by internal backend processes) before the bootstrap
524 * script nominally creates it. Therefore, accept mdopen() as a
525 * substitute for mdcreate() in bootstrap mode only. (See mdcreate)
527 if (IsBootstrapProcessingMode())
528 fd = PathNameOpenFile(path, O_RDWR | O_CREAT | O_EXCL | PG_BINARY, 0600);
531 if (behavior == EXTENSION_RETURN_NULL &&
532 FILE_POSSIBLY_DELETED(errno))
538 (errcode_for_file_access(),
539 errmsg("could not open file \"%s\": %m", path)));
545 reln->md_fd[forknum] = mdfd = _fdvec_alloc();
548 mdfd->mdfd_segno = 0;
549 mdfd->mdfd_chain = NULL;
550 Assert(_mdnblocks(reln, forknum, mdfd) <= ((BlockNumber) RELSEG_SIZE));
556 * mdclose() -- Close the specified relation, if it isn't closed already.
559 mdclose(SMgrRelation reln, ForkNumber forknum)
561 MdfdVec *v = reln->md_fd[forknum];
563 /* No work if already closed */
567 reln->md_fd[forknum] = NULL; /* prevent dangling pointer after error */
573 /* if not closed already */
574 if (v->mdfd_vfd >= 0)
575 FileClose(v->mdfd_vfd);
576 /* Now free vector */
583 * mdprefetch() -- Initiate asynchronous read of the specified block of a relation
586 mdprefetch(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum)
592 v = _mdfd_getseg(reln, forknum, blocknum, false, EXTENSION_FAIL);
594 seekpos = (off_t) BLCKSZ *(blocknum % ((BlockNumber) RELSEG_SIZE));
596 Assert(seekpos < (off_t) BLCKSZ * RELSEG_SIZE);
598 (void) FilePrefetch(v->mdfd_vfd, seekpos, BLCKSZ);
599 #endif /* USE_PREFETCH */
604 * mdread() -- Read the specified block from a relation.
607 mdread(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum,
614 TRACE_POSTGRESQL_SMGR_MD_READ_START(forknum, blocknum,
615 reln->smgr_rnode.node.spcNode,
616 reln->smgr_rnode.node.dbNode,
617 reln->smgr_rnode.node.relNode,
618 reln->smgr_rnode.backend);
620 v = _mdfd_getseg(reln, forknum, blocknum, false, EXTENSION_FAIL);
622 seekpos = (off_t) BLCKSZ *(blocknum % ((BlockNumber) RELSEG_SIZE));
624 Assert(seekpos < (off_t) BLCKSZ * RELSEG_SIZE);
626 if (FileSeek(v->mdfd_vfd, seekpos, SEEK_SET) != seekpos)
628 (errcode_for_file_access(),
629 errmsg("could not seek to block %u in file \"%s\": %m",
630 blocknum, FilePathName(v->mdfd_vfd))));
632 nbytes = FileRead(v->mdfd_vfd, buffer, BLCKSZ);
634 TRACE_POSTGRESQL_SMGR_MD_READ_DONE(forknum, blocknum,
635 reln->smgr_rnode.node.spcNode,
636 reln->smgr_rnode.node.dbNode,
637 reln->smgr_rnode.node.relNode,
638 reln->smgr_rnode.backend,
642 if (nbytes != BLCKSZ)
646 (errcode_for_file_access(),
647 errmsg("could not read block %u in file \"%s\": %m",
648 blocknum, FilePathName(v->mdfd_vfd))));
651 * Short read: we are at or past EOF, or we read a partial block at
652 * EOF. Normally this is an error; upper levels should never try to
653 * read a nonexistent block. However, if zero_damaged_pages is ON or
654 * we are InRecovery, we should instead return zeroes without
655 * complaining. This allows, for example, the case of trying to
656 * update a block that was later truncated away.
658 if (zero_damaged_pages || InRecovery)
659 MemSet(buffer, 0, BLCKSZ);
662 (errcode(ERRCODE_DATA_CORRUPTED),
663 errmsg("could not read block %u in file \"%s\": read only %d of %d bytes",
664 blocknum, FilePathName(v->mdfd_vfd),
670 * mdwrite() -- Write the supplied block at the appropriate location.
672 * This is to be used only for updating already-existing blocks of a
673 * relation (ie, those before the current EOF). To extend a relation,
677 mdwrite(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum,
678 char *buffer, bool skipFsync)
684 /* This assert is too expensive to have on normally ... */
685 #ifdef CHECK_WRITE_VS_EXTEND
686 Assert(blocknum < mdnblocks(reln, forknum));
689 TRACE_POSTGRESQL_SMGR_MD_WRITE_START(forknum, blocknum,
690 reln->smgr_rnode.node.spcNode,
691 reln->smgr_rnode.node.dbNode,
692 reln->smgr_rnode.node.relNode,
693 reln->smgr_rnode.backend);
695 v = _mdfd_getseg(reln, forknum, blocknum, skipFsync, EXTENSION_FAIL);
697 seekpos = (off_t) BLCKSZ *(blocknum % ((BlockNumber) RELSEG_SIZE));
699 Assert(seekpos < (off_t) BLCKSZ * RELSEG_SIZE);
701 if (FileSeek(v->mdfd_vfd, seekpos, SEEK_SET) != seekpos)
703 (errcode_for_file_access(),
704 errmsg("could not seek to block %u in file \"%s\": %m",
705 blocknum, FilePathName(v->mdfd_vfd))));
707 nbytes = FileWrite(v->mdfd_vfd, buffer, BLCKSZ);
709 TRACE_POSTGRESQL_SMGR_MD_WRITE_DONE(forknum, blocknum,
710 reln->smgr_rnode.node.spcNode,
711 reln->smgr_rnode.node.dbNode,
712 reln->smgr_rnode.node.relNode,
713 reln->smgr_rnode.backend,
717 if (nbytes != BLCKSZ)
721 (errcode_for_file_access(),
722 errmsg("could not write block %u in file \"%s\": %m",
723 blocknum, FilePathName(v->mdfd_vfd))));
724 /* short write: complain appropriately */
726 (errcode(ERRCODE_DISK_FULL),
727 errmsg("could not write block %u in file \"%s\": wrote only %d of %d bytes",
729 FilePathName(v->mdfd_vfd),
731 errhint("Check free disk space.")));
734 if (!skipFsync && !SmgrIsTemp(reln))
735 register_dirty_segment(reln, forknum, v);
739 * mdnblocks() -- Get the number of blocks stored in a relation.
741 * Important side effect: all active segments of the relation are opened
742 * and added to the mdfd_chain list. If this routine has not been
743 * called, then only segments up to the last one actually touched
744 * are present in the chain.
747 mdnblocks(SMgrRelation reln, ForkNumber forknum)
749 MdfdVec *v = mdopen(reln, forknum, EXTENSION_FAIL);
751 BlockNumber segno = 0;
754 * Skip through any segments that aren't the last one, to avoid redundant
755 * seeks on them. We have previously verified that these segments are
756 * exactly RELSEG_SIZE long, and it's useless to recheck that each time.
758 * NOTE: this assumption could only be wrong if another backend has
759 * truncated the relation. We rely on higher code levels to handle that
760 * scenario by closing and re-opening the md fd, which is handled via
761 * relcache flush. (Since the bgwriter doesn't participate in relcache
762 * flush, it could have segment chain entries for inactive segments;
763 * that's OK because the bgwriter never needs to compute relation size.)
765 while (v->mdfd_chain != NULL)
773 nblocks = _mdnblocks(reln, forknum, v);
774 if (nblocks > ((BlockNumber) RELSEG_SIZE))
775 elog(FATAL, "segment too big");
776 if (nblocks < ((BlockNumber) RELSEG_SIZE))
777 return (segno * ((BlockNumber) RELSEG_SIZE)) + nblocks;
780 * If segment is exactly RELSEG_SIZE, advance to next one.
784 if (v->mdfd_chain == NULL)
787 * Because we pass O_CREAT, we will create the next segment (with
788 * zero length) immediately, if the last segment is of length
789 * RELSEG_SIZE. While perhaps not strictly necessary, this keeps
792 v->mdfd_chain = _mdfd_openseg(reln, forknum, segno, O_CREAT);
793 if (v->mdfd_chain == NULL)
795 (errcode_for_file_access(),
796 errmsg("could not open file \"%s\": %m",
797 _mdfd_segpath(reln, forknum, segno))));
805 * mdtruncate() -- Truncate relation to specified number of blocks.
808 mdtruncate(SMgrRelation reln, ForkNumber forknum, BlockNumber nblocks)
812 BlockNumber priorblocks;
815 * NOTE: mdnblocks makes sure we have opened all active segments, so that
816 * truncation loop will get them all!
818 curnblk = mdnblocks(reln, forknum);
819 if (nblocks > curnblk)
821 /* Bogus request ... but no complaint if InRecovery */
825 (errmsg("could not truncate file \"%s\" to %u blocks: it's only %u blocks now",
826 relpath(reln->smgr_rnode, forknum),
829 if (nblocks == curnblk)
830 return; /* no work */
832 v = mdopen(reln, forknum, EXTENSION_FAIL);
839 if (priorblocks > nblocks)
842 * This segment is no longer active (and has already been unlinked
843 * from the mdfd_chain). We truncate the file, but do not delete
844 * it, for reasons explained in the header comments.
846 if (FileTruncate(v->mdfd_vfd, 0) < 0)
848 (errcode_for_file_access(),
849 errmsg("could not truncate file \"%s\": %m",
850 FilePathName(v->mdfd_vfd))));
852 if (!SmgrIsTemp(reln))
853 register_dirty_segment(reln, forknum, v);
855 Assert(ov != reln->md_fd[forknum]); /* we never drop the 1st
859 else if (priorblocks + ((BlockNumber) RELSEG_SIZE) > nblocks)
862 * This is the last segment we want to keep. Truncate the file to
863 * the right length, and clear chain link that points to any
864 * remaining segments (which we shall zap). NOTE: if nblocks is
865 * exactly a multiple K of RELSEG_SIZE, we will truncate the K+1st
866 * segment to 0 length but keep it. This adheres to the invariant
867 * given in the header comments.
869 BlockNumber lastsegblocks = nblocks - priorblocks;
871 if (FileTruncate(v->mdfd_vfd, (off_t) lastsegblocks * BLCKSZ) < 0)
873 (errcode_for_file_access(),
874 errmsg("could not truncate file \"%s\" to %u blocks: %m",
875 FilePathName(v->mdfd_vfd),
877 if (!SmgrIsTemp(reln))
878 register_dirty_segment(reln, forknum, v);
880 ov->mdfd_chain = NULL;
885 * We still need this segment and 0 or more blocks beyond it, so
886 * nothing to do here.
890 priorblocks += RELSEG_SIZE;
895 * mdimmedsync() -- Immediately sync a relation to stable storage.
897 * Note that only writes already issued are synced; this routine knows
898 * nothing of dirty buffers that may exist inside the buffer manager.
901 mdimmedsync(SMgrRelation reln, ForkNumber forknum)
907 * NOTE: mdnblocks makes sure we have opened all active segments, so that
908 * fsync loop will get them all!
910 curnblk = mdnblocks(reln, forknum);
912 v = mdopen(reln, forknum, EXTENSION_FAIL);
916 if (FileSync(v->mdfd_vfd) < 0)
918 (errcode_for_file_access(),
919 errmsg("could not fsync file \"%s\": %m",
920 FilePathName(v->mdfd_vfd))));
926 * mdsync() -- Sync previous writes to stable storage.
931 static bool mdsync_in_progress = false;
933 HASH_SEQ_STATUS hstat;
934 PendingOperationEntry *entry;
937 /* Statistics on sync times */
939 instr_time sync_start,
944 uint64 total_elapsed = 0;
947 * This is only called during checkpoints, and checkpoints should only
948 * occur in processes that have created a pendingOpsTable.
950 if (!pendingOpsTable)
951 elog(ERROR, "cannot sync without a pendingOpsTable");
954 * If we are in the bgwriter, the sync had better include all fsync
955 * requests that were queued by backends up to this point. The tightest
956 * race condition that could occur is that a buffer that must be written
957 * and fsync'd for the checkpoint could have been dumped by a backend just
958 * before it was visited by BufferSync(). We know the backend will have
959 * queued an fsync request before clearing the buffer's dirtybit, so we
960 * are safe as long as we do an Absorb after completing BufferSync().
962 AbsorbFsyncRequests();
965 * To avoid excess fsync'ing (in the worst case, maybe a never-terminating
966 * checkpoint), we want to ignore fsync requests that are entered into the
967 * hashtable after this point --- they should be processed next time,
968 * instead. We use mdsync_cycle_ctr to tell old entries apart from new
969 * ones: new ones will have cycle_ctr equal to the incremented value of
972 * In normal circumstances, all entries present in the table at this point
973 * will have cycle_ctr exactly equal to the current (about to be old)
974 * value of mdsync_cycle_ctr. However, if we fail partway through the
975 * fsync'ing loop, then older values of cycle_ctr might remain when we
976 * come back here to try again. Repeated checkpoint failures would
977 * eventually wrap the counter around to the point where an old entry
978 * might appear new, causing us to skip it, possibly allowing a checkpoint
979 * to succeed that should not have. To forestall wraparound, any time the
980 * previous mdsync() failed to complete, run through the table and
981 * forcibly set cycle_ctr = mdsync_cycle_ctr.
983 * Think not to merge this loop with the main loop, as the problem is
984 * exactly that that loop may fail before having visited all the entries.
985 * From a performance point of view it doesn't matter anyway, as this path
986 * will never be taken in a system that's functioning normally.
988 if (mdsync_in_progress)
990 /* prior try failed, so update any stale cycle_ctr values */
991 hash_seq_init(&hstat, pendingOpsTable);
992 while ((entry = (PendingOperationEntry *) hash_seq_search(&hstat)) != NULL)
994 entry->cycle_ctr = mdsync_cycle_ctr;
998 /* Advance counter so that new hashtable entries are distinguishable */
1001 /* Set flag to detect failure if we don't reach the end of the loop */
1002 mdsync_in_progress = true;
1004 /* Now scan the hashtable for fsync requests to process */
1005 absorb_counter = FSYNCS_PER_ABSORB;
1006 hash_seq_init(&hstat, pendingOpsTable);
1007 while ((entry = (PendingOperationEntry *) hash_seq_search(&hstat)) != NULL)
1010 * If the entry is new then don't process it this time. Note that
1011 * "continue" bypasses the hash-remove call at the bottom of the loop.
1013 if (entry->cycle_ctr == mdsync_cycle_ctr)
1016 /* Else assert we haven't missed it */
1017 Assert((CycleCtr) (entry->cycle_ctr + 1) == mdsync_cycle_ctr);
1020 * If fsync is off then we don't have to bother opening the file at
1021 * all. (We delay checking until this point so that changing fsync on
1022 * the fly behaves sensibly.) Also, if the entry is marked canceled,
1023 * fall through to delete it.
1025 if (enableFsync && !entry->canceled)
1030 * If in bgwriter, we want to absorb pending requests every so
1031 * often to prevent overflow of the fsync request queue. It is
1032 * unspecified whether newly-added entries will be visited by
1033 * hash_seq_search, but we don't care since we don't need to
1034 * process them anyway.
1036 if (--absorb_counter <= 0)
1038 AbsorbFsyncRequests();
1039 absorb_counter = FSYNCS_PER_ABSORB;
1043 * The fsync table could contain requests to fsync segments that
1044 * have been deleted (unlinked) by the time we get to them. Rather
1045 * than just hoping an ENOENT (or EACCES on Windows) error can be
1046 * ignored, what we do on error is absorb pending requests and
1047 * then retry. Since mdunlink() queues a "revoke" message before
1048 * actually unlinking, the fsync request is guaranteed to be
1049 * marked canceled after the absorb if it really was this case.
1050 * DROP DATABASE likewise has to tell us to forget fsync requests
1051 * before it starts deletions.
1053 for (failures = 0;; failures++) /* loop exits at "break" */
1060 * Find or create an smgr hash entry for this relation. This
1061 * may seem a bit unclean -- md calling smgr? But it's really
1062 * the best solution. It ensures that the open file reference
1063 * isn't permanently leaked if we get an error here. (You may
1064 * say "but an unreferenced SMgrRelation is still a leak!" Not
1065 * really, because the only case in which a checkpoint is done
1066 * by a process that isn't about to shut down is in the
1067 * bgwriter, and it will periodically do smgrcloseall(). This
1068 * fact justifies our not closing the reln in the success path
1069 * either, which is a good thing since in non-bgwriter cases
1070 * we couldn't safely do that.) Furthermore, in many cases
1071 * the relation will have been dirtied through this same smgr
1072 * relation, and so we can save a file open/close cycle.
1074 reln = smgropen(entry->tag.rnode.node,
1075 entry->tag.rnode.backend);
1078 * It is possible that the relation has been dropped or
1079 * truncated since the fsync request was entered. Therefore,
1080 * allow ENOENT, but only if we didn't fail already on this
1081 * file. This applies both during _mdfd_getseg() and during
1082 * FileSync, since fd.c might have closed the file behind our
1085 seg = _mdfd_getseg(reln, entry->tag.forknum,
1086 entry->tag.segno * ((BlockNumber) RELSEG_SIZE),
1087 false, EXTENSION_RETURN_NULL);
1089 if (log_checkpoints)
1090 INSTR_TIME_SET_CURRENT(sync_start);
1092 INSTR_TIME_SET_ZERO(sync_start);
1095 FileSync(seg->mdfd_vfd) >= 0)
1097 if (log_checkpoints && (!INSTR_TIME_IS_ZERO(sync_start)))
1099 INSTR_TIME_SET_CURRENT(sync_end);
1100 sync_diff = sync_end;
1101 INSTR_TIME_SUBTRACT(sync_diff, sync_start);
1102 elapsed = INSTR_TIME_GET_MICROSEC(sync_diff);
1103 if (elapsed > longest)
1105 total_elapsed += elapsed;
1107 elog(DEBUG1, "checkpoint sync: number=%d file=%s time=%.3f msec",
1108 processed, FilePathName(seg->mdfd_vfd), (double) elapsed / 1000);
1111 break; /* success; break out of retry loop */
1115 * XXX is there any point in allowing more than one retry?
1116 * Don't see one at the moment, but easy to change the test
1119 path = _mdfd_segpath(reln, entry->tag.forknum,
1121 if (!FILE_POSSIBLY_DELETED(errno) ||
1124 (errcode_for_file_access(),
1125 errmsg("could not fsync file \"%s\": %m", path)));
1128 (errcode_for_file_access(),
1129 errmsg("could not fsync file \"%s\" but retrying: %m",
1134 * Absorb incoming requests and check to see if canceled.
1136 AbsorbFsyncRequests();
1137 absorb_counter = FSYNCS_PER_ABSORB; /* might as well... */
1139 if (entry->canceled)
1141 } /* end retry loop */
1145 * If we get here, either we fsync'd successfully, or we don't have to
1146 * because enableFsync is off, or the entry is (now) marked canceled.
1147 * Okay to delete it.
1149 if (hash_search(pendingOpsTable, &entry->tag,
1150 HASH_REMOVE, NULL) == NULL)
1151 elog(ERROR, "pendingOpsTable corrupted");
1152 } /* end loop over hashtable entries */
1154 /* Return sync performance metrics for report at checkpoint end */
1155 CheckpointStats.ckpt_sync_rels = processed;
1156 CheckpointStats.ckpt_longest_sync = longest;
1157 CheckpointStats.ckpt_agg_sync_time = total_elapsed;
1159 /* Flag successful completion of mdsync */
1160 mdsync_in_progress = false;
1164 * mdpreckpt() -- Do pre-checkpoint work
1166 * To distinguish unlink requests that arrived before this checkpoint
1167 * started from those that arrived during the checkpoint, we use a cycle
1168 * counter similar to the one we use for fsync requests. That cycle
1169 * counter is incremented here.
1171 * This must be called *before* the checkpoint REDO point is determined.
1172 * That ensures that we won't delete files too soon.
1174 * Note that we can't do anything here that depends on the assumption
1175 * that the checkpoint will be completed.
1183 * In case the prior checkpoint wasn't completed, stamp all entries in the
1184 * list with the current cycle counter. Anything that's in the list at
1185 * the start of checkpoint can surely be deleted after the checkpoint is
1186 * finished, regardless of when the request was made.
1188 foreach(cell, pendingUnlinks)
1190 PendingUnlinkEntry *entry = (PendingUnlinkEntry *) lfirst(cell);
1192 entry->cycle_ctr = mdckpt_cycle_ctr;
1196 * Any unlink requests arriving after this point will be assigned the next
1197 * cycle counter, and won't be unlinked until next checkpoint.
1203 * mdpostckpt() -- Do post-checkpoint work
1205 * Remove any lingering files that can now be safely removed.
1210 while (pendingUnlinks != NIL)
1212 PendingUnlinkEntry *entry = (PendingUnlinkEntry *) linitial(pendingUnlinks);
1216 * New entries are appended to the end, so if the entry is new we've
1217 * reached the end of old entries.
1219 if (entry->cycle_ctr == mdckpt_cycle_ctr)
1222 /* Else assert we haven't missed it */
1223 Assert((CycleCtr) (entry->cycle_ctr + 1) == mdckpt_cycle_ctr);
1225 /* Unlink the file */
1226 path = relpath(entry->rnode, MAIN_FORKNUM);
1227 if (unlink(path) < 0)
1230 * There's a race condition, when the database is dropped at the
1231 * same time that we process the pending unlink requests. If the
1232 * DROP DATABASE deletes the file before we do, we will get ENOENT
1233 * here. rmtree() also has to ignore ENOENT errors, to deal with
1234 * the possibility that we delete the file first.
1236 if (errno != ENOENT)
1238 (errcode_for_file_access(),
1239 errmsg("could not remove file \"%s\": %m", path)));
1243 pendingUnlinks = list_delete_first(pendingUnlinks);
1249 * register_dirty_segment() -- Mark a relation segment as needing fsync
1251 * If there is a local pending-ops table, just make an entry in it for
1252 * mdsync to process later. Otherwise, try to pass off the fsync request
1253 * to the background writer process. If that fails, just do the fsync
1254 * locally before returning (we expect this will not happen often enough
1255 * to be a performance problem).
1258 register_dirty_segment(SMgrRelation reln, ForkNumber forknum, MdfdVec *seg)
1260 if (pendingOpsTable)
1262 /* push it into local pending-ops table */
1263 RememberFsyncRequest(reln->smgr_rnode, forknum, seg->mdfd_segno);
1267 if (ForwardFsyncRequest(reln->smgr_rnode, forknum, seg->mdfd_segno))
1268 return; /* passed it off successfully */
1271 (errmsg("could not forward fsync request because request queue is full")));
1273 if (FileSync(seg->mdfd_vfd) < 0)
1275 (errcode_for_file_access(),
1276 errmsg("could not fsync file \"%s\": %m",
1277 FilePathName(seg->mdfd_vfd))));
1282 * register_unlink() -- Schedule a file to be deleted after next checkpoint
1284 * As with register_dirty_segment, this could involve either a local or
1285 * a remote pending-ops table.
1288 register_unlink(RelFileNodeBackend rnode)
1290 if (pendingOpsTable)
1292 /* push it into local pending-ops table */
1293 RememberFsyncRequest(rnode, MAIN_FORKNUM, UNLINK_RELATION_REQUEST);
1298 * Notify the bgwriter about it. If we fail to queue the request
1299 * message, we have to sleep and try again, because we can't simply
1300 * delete the file now. Ugly, but hopefully won't happen often.
1302 * XXX should we just leave the file orphaned instead?
1304 Assert(IsUnderPostmaster);
1305 while (!ForwardFsyncRequest(rnode, MAIN_FORKNUM,
1306 UNLINK_RELATION_REQUEST))
1307 pg_usleep(10000L); /* 10 msec seems a good number */
1312 * RememberFsyncRequest() -- callback from bgwriter side of fsync request
1314 * We stuff most fsync requests into the local hash table for execution
1315 * during the bgwriter's next checkpoint. UNLINK requests go into a
1316 * separate linked list, however, because they get processed separately.
1318 * The range of possible segment numbers is way less than the range of
1319 * BlockNumber, so we can reserve high values of segno for special purposes.
1321 * - FORGET_RELATION_FSYNC means to cancel pending fsyncs for a relation
1322 * - FORGET_DATABASE_FSYNC means to cancel pending fsyncs for a whole database
1323 * - UNLINK_RELATION_REQUEST is a request to delete the file after the next
1326 * (Handling the FORGET_* requests is a tad slow because the hash table has
1327 * to be searched linearly, but it doesn't seem worth rethinking the table
1328 * structure for them.)
1331 RememberFsyncRequest(RelFileNodeBackend rnode, ForkNumber forknum,
1334 Assert(pendingOpsTable);
1336 if (segno == FORGET_RELATION_FSYNC)
1338 /* Remove any pending requests for the entire relation */
1339 HASH_SEQ_STATUS hstat;
1340 PendingOperationEntry *entry;
1342 hash_seq_init(&hstat, pendingOpsTable);
1343 while ((entry = (PendingOperationEntry *) hash_seq_search(&hstat)) != NULL)
1345 if (RelFileNodeBackendEquals(entry->tag.rnode, rnode) &&
1346 entry->tag.forknum == forknum)
1348 /* Okay, cancel this entry */
1349 entry->canceled = true;
1353 else if (segno == FORGET_DATABASE_FSYNC)
1355 /* Remove any pending requests for the entire database */
1356 HASH_SEQ_STATUS hstat;
1357 PendingOperationEntry *entry;
1362 /* Remove fsync requests */
1363 hash_seq_init(&hstat, pendingOpsTable);
1364 while ((entry = (PendingOperationEntry *) hash_seq_search(&hstat)) != NULL)
1366 if (entry->tag.rnode.node.dbNode == rnode.node.dbNode)
1368 /* Okay, cancel this entry */
1369 entry->canceled = true;
1373 /* Remove unlink requests */
1375 for (cell = list_head(pendingUnlinks); cell; cell = next)
1377 PendingUnlinkEntry *entry = (PendingUnlinkEntry *) lfirst(cell);
1380 if (entry->rnode.node.dbNode == rnode.node.dbNode)
1382 pendingUnlinks = list_delete_cell(pendingUnlinks, cell, prev);
1389 else if (segno == UNLINK_RELATION_REQUEST)
1391 /* Unlink request: put it in the linked list */
1392 MemoryContext oldcxt = MemoryContextSwitchTo(MdCxt);
1393 PendingUnlinkEntry *entry;
1395 entry = palloc(sizeof(PendingUnlinkEntry));
1396 entry->rnode = rnode;
1397 entry->cycle_ctr = mdckpt_cycle_ctr;
1399 pendingUnlinks = lappend(pendingUnlinks, entry);
1401 MemoryContextSwitchTo(oldcxt);
1405 /* Normal case: enter a request to fsync this segment */
1406 PendingOperationTag key;
1407 PendingOperationEntry *entry;
1410 /* ensure any pad bytes in the hash key are zeroed */
1411 MemSet(&key, 0, sizeof(key));
1413 key.forknum = forknum;
1416 entry = (PendingOperationEntry *) hash_search(pendingOpsTable,
1420 /* if new or previously canceled entry, initialize it */
1421 if (!found || entry->canceled)
1423 entry->canceled = false;
1424 entry->cycle_ctr = mdsync_cycle_ctr;
1428 * NB: it's intentional that we don't change cycle_ctr if the entry
1429 * already exists. The fsync request must be treated as old, even
1430 * though the new request will be satisfied too by any subsequent
1433 * However, if the entry is present but is marked canceled, we should
1434 * act just as though it wasn't there. The only case where this could
1435 * happen would be if a file had been deleted, we received but did not
1436 * yet act on the cancel request, and the same relfilenode was then
1437 * assigned to a new file. We mustn't lose the new request, but it
1438 * should be considered new not old.
1444 * ForgetRelationFsyncRequests -- forget any fsyncs for a rel
1447 ForgetRelationFsyncRequests(RelFileNodeBackend rnode, ForkNumber forknum)
1449 if (pendingOpsTable)
1451 /* standalone backend or startup process: fsync state is local */
1452 RememberFsyncRequest(rnode, forknum, FORGET_RELATION_FSYNC);
1454 else if (IsUnderPostmaster)
1457 * Notify the bgwriter about it. If we fail to queue the revoke
1458 * message, we have to sleep and try again ... ugly, but hopefully
1459 * won't happen often.
1461 * XXX should we CHECK_FOR_INTERRUPTS in this loop? Escaping with an
1462 * error would leave the no-longer-used file still present on disk,
1463 * which would be bad, so I'm inclined to assume that the bgwriter
1464 * will always empty the queue soon.
1466 while (!ForwardFsyncRequest(rnode, forknum, FORGET_RELATION_FSYNC))
1467 pg_usleep(10000L); /* 10 msec seems a good number */
1470 * Note we don't wait for the bgwriter to actually absorb the revoke
1471 * message; see mdsync() for the implications.
1477 * ForgetDatabaseFsyncRequests -- forget any fsyncs and unlinks for a DB
1480 ForgetDatabaseFsyncRequests(Oid dbid)
1482 RelFileNodeBackend rnode;
1484 rnode.node.dbNode = dbid;
1485 rnode.node.spcNode = 0;
1486 rnode.node.relNode = 0;
1487 rnode.backend = InvalidBackendId;
1489 if (pendingOpsTable)
1491 /* standalone backend or startup process: fsync state is local */
1492 RememberFsyncRequest(rnode, InvalidForkNumber, FORGET_DATABASE_FSYNC);
1494 else if (IsUnderPostmaster)
1496 /* see notes in ForgetRelationFsyncRequests */
1497 while (!ForwardFsyncRequest(rnode, InvalidForkNumber,
1498 FORGET_DATABASE_FSYNC))
1499 pg_usleep(10000L); /* 10 msec seems a good number */
1505 * _fdvec_alloc() -- Make a MdfdVec object.
1510 return (MdfdVec *) MemoryContextAlloc(MdCxt, sizeof(MdfdVec));
1514 * Return the filename for the specified segment of the relation. The
1515 * returned string is palloc'd.
1518 _mdfd_segpath(SMgrRelation reln, ForkNumber forknum, BlockNumber segno)
1523 path = relpath(reln->smgr_rnode, forknum);
1527 /* be sure we have enough space for the '.segno' */
1528 fullpath = (char *) palloc(strlen(path) + 12);
1529 sprintf(fullpath, "%s.%u", path, segno);
1539 * Open the specified segment of the relation,
1540 * and make a MdfdVec object for it. Returns NULL on failure.
1543 _mdfd_openseg(SMgrRelation reln, ForkNumber forknum, BlockNumber segno,
1550 fullpath = _mdfd_segpath(reln, forknum, segno);
1553 fd = PathNameOpenFile(fullpath, O_RDWR | PG_BINARY | oflags, 0600);
1560 /* allocate an mdfdvec entry for it */
1563 /* fill the entry */
1565 v->mdfd_segno = segno;
1566 v->mdfd_chain = NULL;
1567 Assert(_mdnblocks(reln, forknum, v) <= ((BlockNumber) RELSEG_SIZE));
1574 * _mdfd_getseg() -- Find the segment of the relation holding the
1577 * If the segment doesn't exist, we ereport, return NULL, or create the
1578 * segment, according to "behavior". Note: skipFsync is only used in the
1579 * EXTENSION_CREATE case.
1582 _mdfd_getseg(SMgrRelation reln, ForkNumber forknum, BlockNumber blkno,
1583 bool skipFsync, ExtensionBehavior behavior)
1585 MdfdVec *v = mdopen(reln, forknum, behavior);
1586 BlockNumber targetseg;
1587 BlockNumber nextsegno;
1590 return NULL; /* only possible if EXTENSION_RETURN_NULL */
1592 targetseg = blkno / ((BlockNumber) RELSEG_SIZE);
1593 for (nextsegno = 1; nextsegno <= targetseg; nextsegno++)
1595 Assert(nextsegno == v->mdfd_segno + 1);
1597 if (v->mdfd_chain == NULL)
1600 * Normally we will create new segments only if authorized by the
1601 * caller (i.e., we are doing mdextend()). But when doing WAL
1602 * recovery, create segments anyway; this allows cases such as
1603 * replaying WAL data that has a write into a high-numbered
1604 * segment of a relation that was later deleted. We want to go
1605 * ahead and create the segments so we can finish out the replay.
1607 * We have to maintain the invariant that segments before the last
1608 * active segment are of size RELSEG_SIZE; therefore, pad them out
1609 * with zeroes if needed. (This only matters if caller is
1610 * extending the relation discontiguously, but that can happen in
1613 if (behavior == EXTENSION_CREATE || InRecovery)
1615 if (_mdnblocks(reln, forknum, v) < RELSEG_SIZE)
1617 char *zerobuf = palloc0(BLCKSZ);
1619 mdextend(reln, forknum,
1620 nextsegno * ((BlockNumber) RELSEG_SIZE) - 1,
1621 zerobuf, skipFsync);
1624 v->mdfd_chain = _mdfd_openseg(reln, forknum, +nextsegno, O_CREAT);
1628 /* We won't create segment if not existent */
1629 v->mdfd_chain = _mdfd_openseg(reln, forknum, nextsegno, 0);
1631 if (v->mdfd_chain == NULL)
1633 if (behavior == EXTENSION_RETURN_NULL &&
1634 FILE_POSSIBLY_DELETED(errno))
1637 (errcode_for_file_access(),
1638 errmsg("could not open file \"%s\" (target block %u): %m",
1639 _mdfd_segpath(reln, forknum, nextsegno),
1649 * Get number of blocks present in a single disk file
1652 _mdnblocks(SMgrRelation reln, ForkNumber forknum, MdfdVec *seg)
1656 len = FileSeek(seg->mdfd_vfd, 0L, SEEK_END);
1659 (errcode_for_file_access(),
1660 errmsg("could not seek to end of file \"%s\": %m",
1661 FilePathName(seg->mdfd_vfd))));
1662 /* note that this calculation will ignore any partial block at EOF */
1663 return (BlockNumber) (len / BLCKSZ);