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 "postmaster/bgwriter.h"
24 #include "storage/fd.h"
25 #include "storage/bufmgr.h"
26 #include "storage/relfilenode.h"
27 #include "storage/smgr.h"
28 #include "utils/hsearch.h"
29 #include "utils/memutils.h"
33 /* interval for calling AbsorbFsyncRequests in mdsync */
34 #define FSYNCS_PER_ABSORB 10
36 /* special values for the segno arg to RememberFsyncRequest */
37 #define FORGET_RELATION_FSYNC (InvalidBlockNumber)
38 #define FORGET_DATABASE_FSYNC (InvalidBlockNumber-1)
39 #define UNLINK_RELATION_REQUEST (InvalidBlockNumber-2)
42 * On Windows, we have to interpret EACCES as possibly meaning the same as
43 * ENOENT, because if a file is unlinked-but-not-yet-gone on that platform,
44 * that's what you get. Ugh. This code is designed so that we don't
45 * actually believe these cases are okay without further evidence (namely,
46 * a pending fsync request getting revoked ... see mdsync).
49 #define FILE_POSSIBLY_DELETED(err) ((err) == ENOENT)
51 #define FILE_POSSIBLY_DELETED(err) ((err) == ENOENT || (err) == EACCES)
55 * The magnetic disk storage manager keeps track of open file
56 * descriptors in its own descriptor pool. This is done to make it
57 * easier to support relations that are larger than the operating
58 * system's file size limit (often 2GBytes). In order to do that,
59 * we break relations up into "segment" files that are each shorter than
60 * the OS file size limit. The segment size is set by the RELSEG_SIZE
61 * configuration constant in pg_config.h.
63 * On disk, a relation must consist of consecutively numbered segment
64 * files in the pattern
65 * -- Zero or more full segments of exactly RELSEG_SIZE blocks each
66 * -- Exactly one partial segment of size 0 <= size < RELSEG_SIZE blocks
67 * -- Optionally, any number of inactive segments of size 0 blocks.
68 * The full and partial segments are collectively the "active" segments.
69 * Inactive segments are those that once contained data but are currently
70 * not needed because of an mdtruncate() operation. The reason for leaving
71 * them present at size zero, rather than unlinking them, is that other
72 * backends and/or the bgwriter might be holding open file references to
73 * such segments. If the relation expands again after mdtruncate(), such
74 * that a deactivated segment becomes active again, it is important that
75 * such file references still be valid --- else data might get written
76 * out to an unlinked old copy of a segment file that will eventually
79 * The file descriptor pointer (md_fd field) stored in the SMgrRelation
80 * cache is, therefore, just the head of a list of MdfdVec objects, one
81 * per segment. But note the md_fd pointer can be NULL, indicating
84 * Also note that mdfd_chain == NULL does not necessarily mean the relation
85 * doesn't have another segment after this one; we may just not have
86 * opened the next segment yet. (We could not have "all segments are
87 * in the chain" as an invariant anyway, since another backend could
88 * extend the relation when we weren't looking.) We do not make chain
89 * entries for inactive segments, however; as soon as we find a partial
90 * segment, we assume that any subsequent segments are inactive.
92 * All MdfdVec objects are palloc'd in the MdCxt memory context.
95 typedef struct _MdfdVec
97 File mdfd_vfd; /* fd number in fd.c's pool */
98 BlockNumber mdfd_segno; /* segment number, from 0 */
99 struct _MdfdVec *mdfd_chain; /* next segment, or NULL */
102 static MemoryContext MdCxt; /* context for all md.c allocations */
106 * In some contexts (currently, standalone backends and the bgwriter process)
107 * we keep track of pending fsync operations: we need to remember all relation
108 * segments that have been written since the last checkpoint, so that we can
109 * fsync them down to disk before completing the next checkpoint. This hash
110 * table remembers the pending operations. We use a hash table mostly as
111 * a convenient way of eliminating duplicate requests.
113 * We use a similar mechanism to remember no-longer-needed files that can
114 * be deleted after the next checkpoint, but we use a linked list instead of
115 * a hash table, because we don't expect there to be any duplicate requests.
117 * (Regular backends do not track pending operations locally, but forward
118 * them to the bgwriter.)
122 RelFileNodeBackend rnode; /* the targeted relation */
124 BlockNumber segno; /* which segment */
125 } PendingOperationTag;
127 typedef uint16 CycleCtr; /* can be any convenient integer size */
131 PendingOperationTag tag; /* hash table key (must be first!) */
132 bool canceled; /* T => request canceled, not yet removed */
133 CycleCtr cycle_ctr; /* mdsync_cycle_ctr when request was made */
134 } PendingOperationEntry;
138 RelFileNodeBackend rnode; /* the dead relation to delete */
139 CycleCtr cycle_ctr; /* mdckpt_cycle_ctr when request was made */
140 } PendingUnlinkEntry;
142 static HTAB *pendingOpsTable = NULL;
143 static List *pendingUnlinks = NIL;
145 static CycleCtr mdsync_cycle_ctr = 0;
146 static CycleCtr mdckpt_cycle_ctr = 0;
149 typedef enum /* behavior for mdopen & _mdfd_getseg */
151 EXTENSION_FAIL, /* ereport if segment not present */
152 EXTENSION_RETURN_NULL, /* return NULL if not present */
153 EXTENSION_CREATE /* create new segments as needed */
157 static MdfdVec *mdopen(SMgrRelation reln, ForkNumber forknum,
158 ExtensionBehavior behavior);
159 static void register_dirty_segment(SMgrRelation reln, ForkNumber forknum,
161 static void register_unlink(RelFileNodeBackend rnode);
162 static MdfdVec *_fdvec_alloc(void);
163 static char *_mdfd_segpath(SMgrRelation reln, ForkNumber forknum,
165 static MdfdVec *_mdfd_openseg(SMgrRelation reln, ForkNumber forkno,
166 BlockNumber segno, int oflags);
167 static MdfdVec *_mdfd_getseg(SMgrRelation reln, ForkNumber forkno,
168 BlockNumber blkno, bool skipFsync, ExtensionBehavior behavior);
169 static BlockNumber _mdnblocks(SMgrRelation reln, ForkNumber forknum,
174 * mdinit() -- Initialize private state for magnetic disk storage manager.
179 MdCxt = AllocSetContextCreate(TopMemoryContext,
181 ALLOCSET_DEFAULT_MINSIZE,
182 ALLOCSET_DEFAULT_INITSIZE,
183 ALLOCSET_DEFAULT_MAXSIZE);
186 * Create pending-operations hashtable if we need it. Currently, we need
187 * it if we are standalone (not under a postmaster) OR if we are a
188 * bootstrap-mode subprocess of a postmaster (that is, a startup or
191 if (!IsUnderPostmaster || IsBootstrapProcessingMode())
195 MemSet(&hash_ctl, 0, sizeof(hash_ctl));
196 hash_ctl.keysize = sizeof(PendingOperationTag);
197 hash_ctl.entrysize = sizeof(PendingOperationEntry);
198 hash_ctl.hash = tag_hash;
199 hash_ctl.hcxt = MdCxt;
200 pendingOpsTable = hash_create("Pending Ops Table",
203 HASH_ELEM | HASH_FUNCTION | HASH_CONTEXT);
204 pendingUnlinks = NIL;
209 * In archive recovery, we rely on bgwriter to do fsyncs, but we will have
210 * already created the pendingOpsTable during initialization of the startup
211 * process. Calling this function drops the local pendingOpsTable so that
212 * subsequent requests will be forwarded to bgwriter.
215 SetForwardFsyncRequests(void)
217 /* Perform any pending ops we may have queued up */
220 pendingOpsTable = NULL;
224 * mdexists() -- Does the physical file exist?
226 * Note: this will return true for lingering files, with pending deletions
229 mdexists(SMgrRelation reln, ForkNumber forkNum)
232 * Close it first, to ensure that we notice if the fork has been unlinked
233 * since we opened it.
235 mdclose(reln, forkNum);
237 return (mdopen(reln, forkNum, EXTENSION_RETURN_NULL) != NULL);
241 * mdcreate() -- Create a new relation on magnetic disk.
243 * If isRedo is true, it's okay for the relation to exist already.
246 mdcreate(SMgrRelation reln, ForkNumber forkNum, bool isRedo)
251 if (isRedo && reln->md_fd[forkNum] != NULL)
252 return; /* created and opened already... */
254 Assert(reln->md_fd[forkNum] == NULL);
256 path = relpath(reln->smgr_rnode, forkNum);
258 fd = PathNameOpenFile(path, O_RDWR | O_CREAT | O_EXCL | PG_BINARY, 0600);
262 int save_errno = errno;
265 * During bootstrap, there are cases where a system relation will be
266 * accessed (by internal backend processes) before the bootstrap
267 * script nominally creates it. Therefore, allow the file to exist
268 * already, even if isRedo is not set. (See also mdopen)
270 if (isRedo || IsBootstrapProcessingMode())
271 fd = PathNameOpenFile(path, O_RDWR | PG_BINARY, 0600);
274 /* be sure to report the error reported by create, not open */
277 (errcode_for_file_access(),
278 errmsg("could not create file \"%s\": %m", path)));
284 reln->md_fd[forkNum] = _fdvec_alloc();
286 reln->md_fd[forkNum]->mdfd_vfd = fd;
287 reln->md_fd[forkNum]->mdfd_segno = 0;
288 reln->md_fd[forkNum]->mdfd_chain = NULL;
292 * mdunlink() -- Unlink a relation.
294 * Note that we're passed a RelFileNode --- by the time this is called,
295 * there won't be an SMgrRelation hashtable entry anymore.
297 * Actually, we don't unlink the first segment file of the relation, but
298 * just truncate it to zero length, and record a request to unlink it after
299 * the next checkpoint. Additional segments can be unlinked immediately,
300 * however. Leaving the empty file in place prevents that relfilenode
301 * number from being reused. The scenario this protects us from is:
302 * 1. We delete a relation (and commit, and actually remove its file).
303 * 2. We create a new relation, which by chance gets the same relfilenode as
304 * the just-deleted one (OIDs must've wrapped around for that to happen).
305 * 3. We crash before another checkpoint occurs.
306 * During replay, we would delete the file and then recreate it, which is fine
307 * if the contents of the file were repopulated by subsequent WAL entries.
308 * But if we didn't WAL-log insertions, but instead relied on fsyncing the
309 * file after populating it (as for instance CLUSTER and CREATE INDEX do),
310 * the contents of the file would be lost forever. By leaving the empty file
311 * until after the next checkpoint, we prevent reassignment of the relfilenode
312 * number until it's safe, because relfilenode assignment skips over any
315 * If isRedo is true, it's okay for the relation to be already gone.
316 * Also, we should remove the file immediately instead of queuing a request
317 * for later, since during redo there's no possibility of creating a
318 * conflicting relation.
320 * Note: any failure should be reported as WARNING not ERROR, because
321 * we are usually not in a transaction anymore when this is called.
324 mdunlink(RelFileNodeBackend rnode, ForkNumber forkNum, bool isRedo)
330 * We have to clean out any pending fsync requests for the doomed
331 * relation, else the next mdsync() will fail.
333 ForgetRelationFsyncRequests(rnode, forkNum);
335 path = relpath(rnode, forkNum);
338 * Delete or truncate the first segment.
340 if (isRedo || forkNum != MAIN_FORKNUM)
345 if (!isRedo || errno != ENOENT)
347 (errcode_for_file_access(),
348 errmsg("could not remove file \"%s\": %m", path)));
353 /* truncate(2) would be easier here, but Windows hasn't got it */
356 fd = BasicOpenFile(path, O_RDWR | PG_BINARY, 0);
361 ret = ftruncate(fd, 0);
368 if (ret < 0 && errno != ENOENT)
370 (errcode_for_file_access(),
371 errmsg("could not truncate file \"%s\": %m", path)));
375 * Delete any additional segments.
379 char *segpath = (char *) palloc(strlen(path) + 12);
383 * Note that because we loop until getting ENOENT, we will correctly
384 * remove all inactive segments as well as active ones.
386 for (segno = 1;; segno++)
388 sprintf(segpath, "%s.%u", path, segno);
389 if (unlink(segpath) < 0)
391 /* ENOENT is expected after the last segment... */
394 (errcode_for_file_access(),
395 errmsg("could not remove file \"%s\": %m", segpath)));
404 /* Register request to unlink first segment later */
405 if (!isRedo && forkNum == MAIN_FORKNUM)
406 register_unlink(rnode);
410 * mdextend() -- Add a block to the specified relation.
412 * The semantics are nearly the same as mdwrite(): write at the
413 * specified position. However, this is to be used for the case of
414 * extending a relation (i.e., blocknum is at or beyond the current
415 * EOF). Note that we assume writing a block beyond current EOF
416 * causes intervening file space to become filled with zeroes.
419 mdextend(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum,
420 char *buffer, bool skipFsync)
426 /* This assert is too expensive to have on normally ... */
427 #ifdef CHECK_WRITE_VS_EXTEND
428 Assert(blocknum >= mdnblocks(reln, forknum));
432 * If a relation manages to grow to 2^32-1 blocks, refuse to extend it any
433 * more --- we mustn't create a block whose number actually is
434 * InvalidBlockNumber.
436 if (blocknum == InvalidBlockNumber)
438 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
439 errmsg("cannot extend file \"%s\" beyond %u blocks",
440 relpath(reln->smgr_rnode, forknum),
441 InvalidBlockNumber)));
443 v = _mdfd_getseg(reln, forknum, blocknum, skipFsync, EXTENSION_CREATE);
445 seekpos = (off_t) BLCKSZ *(blocknum % ((BlockNumber) RELSEG_SIZE));
447 Assert(seekpos < (off_t) BLCKSZ * RELSEG_SIZE);
450 * Note: because caller usually obtained blocknum by calling mdnblocks,
451 * which did a seek(SEEK_END), this seek is often redundant and will be
452 * optimized away by fd.c. It's not redundant, however, if there is a
453 * partial page at the end of the file. In that case we want to try to
454 * overwrite the partial page with a full page. It's also not redundant
455 * if bufmgr.c had to dump another buffer of the same file to make room
456 * for the new page's buffer.
458 if (FileSeek(v->mdfd_vfd, seekpos, SEEK_SET) != seekpos)
460 (errcode_for_file_access(),
461 errmsg("could not seek to block %u in file \"%s\": %m",
462 blocknum, FilePathName(v->mdfd_vfd))));
464 if ((nbytes = FileWrite(v->mdfd_vfd, buffer, BLCKSZ)) != BLCKSZ)
468 (errcode_for_file_access(),
469 errmsg("could not extend file \"%s\": %m",
470 FilePathName(v->mdfd_vfd)),
471 errhint("Check free disk space.")));
472 /* short write: complain appropriately */
474 (errcode(ERRCODE_DISK_FULL),
475 errmsg("could not extend file \"%s\": wrote only %d of %d bytes at block %u",
476 FilePathName(v->mdfd_vfd),
477 nbytes, BLCKSZ, blocknum),
478 errhint("Check free disk space.")));
481 if (!skipFsync && !SmgrIsTemp(reln))
482 register_dirty_segment(reln, forknum, v);
484 Assert(_mdnblocks(reln, forknum, v) <= ((BlockNumber) RELSEG_SIZE));
488 * mdopen() -- Open the specified relation.
490 * Note we only open the first segment, when there are multiple segments.
492 * If first segment is not present, either ereport or return NULL according
493 * to "behavior". We treat EXTENSION_CREATE the same as EXTENSION_FAIL;
494 * EXTENSION_CREATE means it's OK to extend an existing relation, not to
495 * invent one out of whole cloth.
498 mdopen(SMgrRelation reln, ForkNumber forknum, ExtensionBehavior behavior)
504 /* No work if already open */
505 if (reln->md_fd[forknum])
506 return reln->md_fd[forknum];
508 path = relpath(reln->smgr_rnode, forknum);
510 fd = PathNameOpenFile(path, O_RDWR | PG_BINARY, 0600);
515 * During bootstrap, there are cases where a system relation will be
516 * accessed (by internal backend processes) before the bootstrap
517 * script nominally creates it. Therefore, accept mdopen() as a
518 * substitute for mdcreate() in bootstrap mode only. (See mdcreate)
520 if (IsBootstrapProcessingMode())
521 fd = PathNameOpenFile(path, O_RDWR | O_CREAT | O_EXCL | PG_BINARY, 0600);
524 if (behavior == EXTENSION_RETURN_NULL &&
525 FILE_POSSIBLY_DELETED(errno))
531 (errcode_for_file_access(),
532 errmsg("could not open file \"%s\": %m", path)));
538 reln->md_fd[forknum] = mdfd = _fdvec_alloc();
541 mdfd->mdfd_segno = 0;
542 mdfd->mdfd_chain = NULL;
543 Assert(_mdnblocks(reln, forknum, mdfd) <= ((BlockNumber) RELSEG_SIZE));
549 * mdclose() -- Close the specified relation, if it isn't closed already.
552 mdclose(SMgrRelation reln, ForkNumber forknum)
554 MdfdVec *v = reln->md_fd[forknum];
556 /* No work if already closed */
560 reln->md_fd[forknum] = NULL; /* prevent dangling pointer after error */
566 /* if not closed already */
567 if (v->mdfd_vfd >= 0)
568 FileClose(v->mdfd_vfd);
569 /* Now free vector */
576 * mdprefetch() -- Initiate asynchronous read of the specified block of a relation
579 mdprefetch(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum)
585 v = _mdfd_getseg(reln, forknum, blocknum, false, EXTENSION_FAIL);
587 seekpos = (off_t) BLCKSZ *(blocknum % ((BlockNumber) RELSEG_SIZE));
589 Assert(seekpos < (off_t) BLCKSZ * RELSEG_SIZE);
591 (void) FilePrefetch(v->mdfd_vfd, seekpos, BLCKSZ);
592 #endif /* USE_PREFETCH */
597 * mdread() -- Read the specified block from a relation.
600 mdread(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum,
607 TRACE_POSTGRESQL_SMGR_MD_READ_START(forknum, blocknum,
608 reln->smgr_rnode.node.spcNode,
609 reln->smgr_rnode.node.dbNode,
610 reln->smgr_rnode.node.relNode,
611 reln->smgr_rnode.backend);
613 v = _mdfd_getseg(reln, forknum, blocknum, false, EXTENSION_FAIL);
615 seekpos = (off_t) BLCKSZ *(blocknum % ((BlockNumber) RELSEG_SIZE));
617 Assert(seekpos < (off_t) BLCKSZ * RELSEG_SIZE);
619 if (FileSeek(v->mdfd_vfd, seekpos, SEEK_SET) != seekpos)
621 (errcode_for_file_access(),
622 errmsg("could not seek to block %u in file \"%s\": %m",
623 blocknum, FilePathName(v->mdfd_vfd))));
625 nbytes = FileRead(v->mdfd_vfd, buffer, BLCKSZ);
627 TRACE_POSTGRESQL_SMGR_MD_READ_DONE(forknum, blocknum,
628 reln->smgr_rnode.node.spcNode,
629 reln->smgr_rnode.node.dbNode,
630 reln->smgr_rnode.node.relNode,
631 reln->smgr_rnode.backend,
635 if (nbytes != BLCKSZ)
639 (errcode_for_file_access(),
640 errmsg("could not read block %u in file \"%s\": %m",
641 blocknum, FilePathName(v->mdfd_vfd))));
644 * Short read: we are at or past EOF, or we read a partial block at
645 * EOF. Normally this is an error; upper levels should never try to
646 * read a nonexistent block. However, if zero_damaged_pages is ON or
647 * we are InRecovery, we should instead return zeroes without
648 * complaining. This allows, for example, the case of trying to
649 * update a block that was later truncated away.
651 if (zero_damaged_pages || InRecovery)
652 MemSet(buffer, 0, BLCKSZ);
655 (errcode(ERRCODE_DATA_CORRUPTED),
656 errmsg("could not read block %u in file \"%s\": read only %d of %d bytes",
657 blocknum, FilePathName(v->mdfd_vfd),
663 * mdwrite() -- Write the supplied block at the appropriate location.
665 * This is to be used only for updating already-existing blocks of a
666 * relation (ie, those before the current EOF). To extend a relation,
670 mdwrite(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum,
671 char *buffer, bool skipFsync)
677 /* This assert is too expensive to have on normally ... */
678 #ifdef CHECK_WRITE_VS_EXTEND
679 Assert(blocknum < mdnblocks(reln, forknum));
682 TRACE_POSTGRESQL_SMGR_MD_WRITE_START(forknum, blocknum,
683 reln->smgr_rnode.node.spcNode,
684 reln->smgr_rnode.node.dbNode,
685 reln->smgr_rnode.node.relNode,
686 reln->smgr_rnode.backend);
688 v = _mdfd_getseg(reln, forknum, blocknum, skipFsync, EXTENSION_FAIL);
690 seekpos = (off_t) BLCKSZ *(blocknum % ((BlockNumber) RELSEG_SIZE));
692 Assert(seekpos < (off_t) BLCKSZ * RELSEG_SIZE);
694 if (FileSeek(v->mdfd_vfd, seekpos, SEEK_SET) != seekpos)
696 (errcode_for_file_access(),
697 errmsg("could not seek to block %u in file \"%s\": %m",
698 blocknum, FilePathName(v->mdfd_vfd))));
700 nbytes = FileWrite(v->mdfd_vfd, buffer, BLCKSZ);
702 TRACE_POSTGRESQL_SMGR_MD_WRITE_DONE(forknum, blocknum,
703 reln->smgr_rnode.node.spcNode,
704 reln->smgr_rnode.node.dbNode,
705 reln->smgr_rnode.node.relNode,
706 reln->smgr_rnode.backend,
710 if (nbytes != BLCKSZ)
714 (errcode_for_file_access(),
715 errmsg("could not write block %u in file \"%s\": %m",
716 blocknum, FilePathName(v->mdfd_vfd))));
717 /* short write: complain appropriately */
719 (errcode(ERRCODE_DISK_FULL),
720 errmsg("could not write block %u in file \"%s\": wrote only %d of %d bytes",
722 FilePathName(v->mdfd_vfd),
724 errhint("Check free disk space.")));
727 if (!skipFsync && !SmgrIsTemp(reln))
728 register_dirty_segment(reln, forknum, v);
732 * mdnblocks() -- Get the number of blocks stored in a relation.
734 * Important side effect: all active segments of the relation are opened
735 * and added to the mdfd_chain list. If this routine has not been
736 * called, then only segments up to the last one actually touched
737 * are present in the chain.
740 mdnblocks(SMgrRelation reln, ForkNumber forknum)
742 MdfdVec *v = mdopen(reln, forknum, EXTENSION_FAIL);
744 BlockNumber segno = 0;
747 * Skip through any segments that aren't the last one, to avoid redundant
748 * seeks on them. We have previously verified that these segments are
749 * exactly RELSEG_SIZE long, and it's useless to recheck that each time.
751 * NOTE: this assumption could only be wrong if another backend has
752 * truncated the relation. We rely on higher code levels to handle that
753 * scenario by closing and re-opening the md fd, which is handled via
754 * relcache flush. (Since the bgwriter doesn't participate in relcache
755 * flush, it could have segment chain entries for inactive segments;
756 * that's OK because the bgwriter never needs to compute relation size.)
758 while (v->mdfd_chain != NULL)
766 nblocks = _mdnblocks(reln, forknum, v);
767 if (nblocks > ((BlockNumber) RELSEG_SIZE))
768 elog(FATAL, "segment too big");
769 if (nblocks < ((BlockNumber) RELSEG_SIZE))
770 return (segno * ((BlockNumber) RELSEG_SIZE)) + nblocks;
773 * If segment is exactly RELSEG_SIZE, advance to next one.
777 if (v->mdfd_chain == NULL)
780 * Because we pass O_CREAT, we will create the next segment (with
781 * zero length) immediately, if the last segment is of length
782 * RELSEG_SIZE. While perhaps not strictly necessary, this keeps
785 v->mdfd_chain = _mdfd_openseg(reln, forknum, segno, O_CREAT);
786 if (v->mdfd_chain == NULL)
788 (errcode_for_file_access(),
789 errmsg("could not open file \"%s\": %m",
790 _mdfd_segpath(reln, forknum, segno))));
798 * mdtruncate() -- Truncate relation to specified number of blocks.
801 mdtruncate(SMgrRelation reln, ForkNumber forknum, BlockNumber nblocks)
805 BlockNumber priorblocks;
808 * NOTE: mdnblocks makes sure we have opened all active segments, so that
809 * truncation loop will get them all!
811 curnblk = mdnblocks(reln, forknum);
812 if (nblocks > curnblk)
814 /* Bogus request ... but no complaint if InRecovery */
818 (errmsg("could not truncate file \"%s\" to %u blocks: it's only %u blocks now",
819 relpath(reln->smgr_rnode, forknum),
822 if (nblocks == curnblk)
823 return; /* no work */
825 v = mdopen(reln, forknum, EXTENSION_FAIL);
832 if (priorblocks > nblocks)
835 * This segment is no longer active (and has already been unlinked
836 * from the mdfd_chain). We truncate the file, but do not delete
837 * it, for reasons explained in the header comments.
839 if (FileTruncate(v->mdfd_vfd, 0) < 0)
841 (errcode_for_file_access(),
842 errmsg("could not truncate file \"%s\": %m",
843 FilePathName(v->mdfd_vfd))));
845 if (!SmgrIsTemp(reln))
846 register_dirty_segment(reln, forknum, v);
848 Assert(ov != reln->md_fd[forknum]); /* we never drop the 1st
852 else if (priorblocks + ((BlockNumber) RELSEG_SIZE) > nblocks)
855 * This is the last segment we want to keep. Truncate the file to
856 * the right length, and clear chain link that points to any
857 * remaining segments (which we shall zap). NOTE: if nblocks is
858 * exactly a multiple K of RELSEG_SIZE, we will truncate the K+1st
859 * segment to 0 length but keep it. This adheres to the invariant
860 * given in the header comments.
862 BlockNumber lastsegblocks = nblocks - priorblocks;
864 if (FileTruncate(v->mdfd_vfd, (off_t) lastsegblocks * BLCKSZ) < 0)
866 (errcode_for_file_access(),
867 errmsg("could not truncate file \"%s\" to %u blocks: %m",
868 FilePathName(v->mdfd_vfd),
870 if (!SmgrIsTemp(reln))
871 register_dirty_segment(reln, forknum, v);
873 ov->mdfd_chain = NULL;
878 * We still need this segment and 0 or more blocks beyond it, so
879 * nothing to do here.
883 priorblocks += RELSEG_SIZE;
888 * mdimmedsync() -- Immediately sync a relation to stable storage.
890 * Note that only writes already issued are synced; this routine knows
891 * nothing of dirty buffers that may exist inside the buffer manager.
894 mdimmedsync(SMgrRelation reln, ForkNumber forknum)
900 * NOTE: mdnblocks makes sure we have opened all active segments, so that
901 * fsync loop will get them all!
903 curnblk = mdnblocks(reln, forknum);
905 v = mdopen(reln, forknum, EXTENSION_FAIL);
909 if (FileSync(v->mdfd_vfd) < 0)
911 (errcode_for_file_access(),
912 errmsg("could not fsync file \"%s\": %m",
913 FilePathName(v->mdfd_vfd))));
919 * mdsync() -- Sync previous writes to stable storage.
924 static bool mdsync_in_progress = false;
926 HASH_SEQ_STATUS hstat;
927 PendingOperationEntry *entry;
931 * This is only called during checkpoints, and checkpoints should only
932 * occur in processes that have created a pendingOpsTable.
934 if (!pendingOpsTable)
935 elog(ERROR, "cannot sync without a pendingOpsTable");
938 * If we are in the bgwriter, the sync had better include all fsync
939 * requests that were queued by backends up to this point. The tightest
940 * race condition that could occur is that a buffer that must be written
941 * and fsync'd for the checkpoint could have been dumped by a backend just
942 * before it was visited by BufferSync(). We know the backend will have
943 * queued an fsync request before clearing the buffer's dirtybit, so we
944 * are safe as long as we do an Absorb after completing BufferSync().
946 AbsorbFsyncRequests();
949 * To avoid excess fsync'ing (in the worst case, maybe a never-terminating
950 * checkpoint), we want to ignore fsync requests that are entered into the
951 * hashtable after this point --- they should be processed next time,
952 * instead. We use mdsync_cycle_ctr to tell old entries apart from new
953 * ones: new ones will have cycle_ctr equal to the incremented value of
956 * In normal circumstances, all entries present in the table at this point
957 * will have cycle_ctr exactly equal to the current (about to be old)
958 * value of mdsync_cycle_ctr. However, if we fail partway through the
959 * fsync'ing loop, then older values of cycle_ctr might remain when we
960 * come back here to try again. Repeated checkpoint failures would
961 * eventually wrap the counter around to the point where an old entry
962 * might appear new, causing us to skip it, possibly allowing a checkpoint
963 * to succeed that should not have. To forestall wraparound, any time the
964 * previous mdsync() failed to complete, run through the table and
965 * forcibly set cycle_ctr = mdsync_cycle_ctr.
967 * Think not to merge this loop with the main loop, as the problem is
968 * exactly that that loop may fail before having visited all the entries.
969 * From a performance point of view it doesn't matter anyway, as this path
970 * will never be taken in a system that's functioning normally.
972 if (mdsync_in_progress)
974 /* prior try failed, so update any stale cycle_ctr values */
975 hash_seq_init(&hstat, pendingOpsTable);
976 while ((entry = (PendingOperationEntry *) hash_seq_search(&hstat)) != NULL)
978 entry->cycle_ctr = mdsync_cycle_ctr;
982 /* Advance counter so that new hashtable entries are distinguishable */
985 /* Set flag to detect failure if we don't reach the end of the loop */
986 mdsync_in_progress = true;
988 /* Now scan the hashtable for fsync requests to process */
989 absorb_counter = FSYNCS_PER_ABSORB;
990 hash_seq_init(&hstat, pendingOpsTable);
991 while ((entry = (PendingOperationEntry *) hash_seq_search(&hstat)) != NULL)
994 * If the entry is new then don't process it this time. Note that
995 * "continue" bypasses the hash-remove call at the bottom of the loop.
997 if (entry->cycle_ctr == mdsync_cycle_ctr)
1000 /* Else assert we haven't missed it */
1001 Assert((CycleCtr) (entry->cycle_ctr + 1) == mdsync_cycle_ctr);
1004 * If fsync is off then we don't have to bother opening the file at
1005 * all. (We delay checking until this point so that changing fsync on
1006 * the fly behaves sensibly.) Also, if the entry is marked canceled,
1007 * fall through to delete it.
1009 if (enableFsync && !entry->canceled)
1014 * If in bgwriter, we want to absorb pending requests every so
1015 * often to prevent overflow of the fsync request queue. It is
1016 * unspecified whether newly-added entries will be visited by
1017 * hash_seq_search, but we don't care since we don't need to
1018 * process them anyway.
1020 if (--absorb_counter <= 0)
1022 AbsorbFsyncRequests();
1023 absorb_counter = FSYNCS_PER_ABSORB;
1027 * The fsync table could contain requests to fsync segments that
1028 * have been deleted (unlinked) by the time we get to them. Rather
1029 * than just hoping an ENOENT (or EACCES on Windows) error can be
1030 * ignored, what we do on error is absorb pending requests and
1031 * then retry. Since mdunlink() queues a "revoke" message before
1032 * actually unlinking, the fsync request is guaranteed to be
1033 * marked canceled after the absorb if it really was this case.
1034 * DROP DATABASE likewise has to tell us to forget fsync requests
1035 * before it starts deletions.
1037 for (failures = 0;; failures++) /* loop exits at "break" */
1044 * Find or create an smgr hash entry for this relation. This
1045 * may seem a bit unclean -- md calling smgr? But it's really
1046 * the best solution. It ensures that the open file reference
1047 * isn't permanently leaked if we get an error here. (You may
1048 * say "but an unreferenced SMgrRelation is still a leak!" Not
1049 * really, because the only case in which a checkpoint is done
1050 * by a process that isn't about to shut down is in the
1051 * bgwriter, and it will periodically do smgrcloseall(). This
1052 * fact justifies our not closing the reln in the success path
1053 * either, which is a good thing since in non-bgwriter cases
1054 * we couldn't safely do that.) Furthermore, in many cases
1055 * the relation will have been dirtied through this same smgr
1056 * relation, and so we can save a file open/close cycle.
1058 reln = smgropen(entry->tag.rnode.node,
1059 entry->tag.rnode.backend);
1062 * It is possible that the relation has been dropped or
1063 * truncated since the fsync request was entered. Therefore,
1064 * allow ENOENT, but only if we didn't fail already on this
1065 * file. This applies both during _mdfd_getseg() and during
1066 * FileSync, since fd.c might have closed the file behind our
1069 seg = _mdfd_getseg(reln, entry->tag.forknum,
1070 entry->tag.segno * ((BlockNumber) RELSEG_SIZE),
1071 false, EXTENSION_RETURN_NULL);
1073 FileSync(seg->mdfd_vfd) >= 0)
1074 break; /* success; break out of retry loop */
1077 * XXX is there any point in allowing more than one retry?
1078 * Don't see one at the moment, but easy to change the test
1081 path = _mdfd_segpath(reln, entry->tag.forknum,
1083 if (!FILE_POSSIBLY_DELETED(errno) ||
1086 (errcode_for_file_access(),
1087 errmsg("could not fsync file \"%s\": %m", path)));
1090 (errcode_for_file_access(),
1091 errmsg("could not fsync file \"%s\" but retrying: %m",
1096 * Absorb incoming requests and check to see if canceled.
1098 AbsorbFsyncRequests();
1099 absorb_counter = FSYNCS_PER_ABSORB; /* might as well... */
1101 if (entry->canceled)
1103 } /* end retry loop */
1107 * If we get here, either we fsync'd successfully, or we don't have to
1108 * because enableFsync is off, or the entry is (now) marked canceled.
1109 * Okay to delete it.
1111 if (hash_search(pendingOpsTable, &entry->tag,
1112 HASH_REMOVE, NULL) == NULL)
1113 elog(ERROR, "pendingOpsTable corrupted");
1114 } /* end loop over hashtable entries */
1116 /* Flag successful completion of mdsync */
1117 mdsync_in_progress = false;
1121 * mdpreckpt() -- Do pre-checkpoint work
1123 * To distinguish unlink requests that arrived before this checkpoint
1124 * started from those that arrived during the checkpoint, we use a cycle
1125 * counter similar to the one we use for fsync requests. That cycle
1126 * counter is incremented here.
1128 * This must be called *before* the checkpoint REDO point is determined.
1129 * That ensures that we won't delete files too soon.
1131 * Note that we can't do anything here that depends on the assumption
1132 * that the checkpoint will be completed.
1140 * In case the prior checkpoint wasn't completed, stamp all entries in the
1141 * list with the current cycle counter. Anything that's in the list at
1142 * the start of checkpoint can surely be deleted after the checkpoint is
1143 * finished, regardless of when the request was made.
1145 foreach(cell, pendingUnlinks)
1147 PendingUnlinkEntry *entry = (PendingUnlinkEntry *) lfirst(cell);
1149 entry->cycle_ctr = mdckpt_cycle_ctr;
1153 * Any unlink requests arriving after this point will be assigned the next
1154 * cycle counter, and won't be unlinked until next checkpoint.
1160 * mdpostckpt() -- Do post-checkpoint work
1162 * Remove any lingering files that can now be safely removed.
1167 while (pendingUnlinks != NIL)
1169 PendingUnlinkEntry *entry = (PendingUnlinkEntry *) linitial(pendingUnlinks);
1173 * New entries are appended to the end, so if the entry is new we've
1174 * reached the end of old entries.
1176 if (entry->cycle_ctr == mdckpt_cycle_ctr)
1179 /* Else assert we haven't missed it */
1180 Assert((CycleCtr) (entry->cycle_ctr + 1) == mdckpt_cycle_ctr);
1182 /* Unlink the file */
1183 path = relpath(entry->rnode, MAIN_FORKNUM);
1184 if (unlink(path) < 0)
1187 * There's a race condition, when the database is dropped at the
1188 * same time that we process the pending unlink requests. If the
1189 * DROP DATABASE deletes the file before we do, we will get ENOENT
1190 * here. rmtree() also has to ignore ENOENT errors, to deal with
1191 * the possibility that we delete the file first.
1193 if (errno != ENOENT)
1195 (errcode_for_file_access(),
1196 errmsg("could not remove file \"%s\": %m", path)));
1200 pendingUnlinks = list_delete_first(pendingUnlinks);
1206 * register_dirty_segment() -- Mark a relation segment as needing fsync
1208 * If there is a local pending-ops table, just make an entry in it for
1209 * mdsync to process later. Otherwise, try to pass off the fsync request
1210 * to the background writer process. If that fails, just do the fsync
1211 * locally before returning (we expect this will not happen often enough
1212 * to be a performance problem).
1215 register_dirty_segment(SMgrRelation reln, ForkNumber forknum, MdfdVec *seg)
1217 if (pendingOpsTable)
1219 /* push it into local pending-ops table */
1220 RememberFsyncRequest(reln->smgr_rnode, forknum, seg->mdfd_segno);
1224 if (ForwardFsyncRequest(reln->smgr_rnode, forknum, seg->mdfd_segno))
1225 return; /* passed it off successfully */
1227 if (FileSync(seg->mdfd_vfd) < 0)
1229 (errcode_for_file_access(),
1230 errmsg("could not fsync file \"%s\": %m",
1231 FilePathName(seg->mdfd_vfd))));
1236 * register_unlink() -- Schedule a file to be deleted after next checkpoint
1238 * As with register_dirty_segment, this could involve either a local or
1239 * a remote pending-ops table.
1242 register_unlink(RelFileNodeBackend rnode)
1244 if (pendingOpsTable)
1246 /* push it into local pending-ops table */
1247 RememberFsyncRequest(rnode, MAIN_FORKNUM, UNLINK_RELATION_REQUEST);
1252 * Notify the bgwriter about it. If we fail to queue the request
1253 * message, we have to sleep and try again, because we can't simply
1254 * delete the file now. Ugly, but hopefully won't happen often.
1256 * XXX should we just leave the file orphaned instead?
1258 Assert(IsUnderPostmaster);
1259 while (!ForwardFsyncRequest(rnode, MAIN_FORKNUM,
1260 UNLINK_RELATION_REQUEST))
1261 pg_usleep(10000L); /* 10 msec seems a good number */
1266 * RememberFsyncRequest() -- callback from bgwriter side of fsync request
1268 * We stuff most fsync requests into the local hash table for execution
1269 * during the bgwriter's next checkpoint. UNLINK requests go into a
1270 * separate linked list, however, because they get processed separately.
1272 * The range of possible segment numbers is way less than the range of
1273 * BlockNumber, so we can reserve high values of segno for special purposes.
1275 * - FORGET_RELATION_FSYNC means to cancel pending fsyncs for a relation
1276 * - FORGET_DATABASE_FSYNC means to cancel pending fsyncs for a whole database
1277 * - UNLINK_RELATION_REQUEST is a request to delete the file after the next
1280 * (Handling the FORGET_* requests is a tad slow because the hash table has
1281 * to be searched linearly, but it doesn't seem worth rethinking the table
1282 * structure for them.)
1285 RememberFsyncRequest(RelFileNodeBackend rnode, ForkNumber forknum,
1288 Assert(pendingOpsTable);
1290 if (segno == FORGET_RELATION_FSYNC)
1292 /* Remove any pending requests for the entire relation */
1293 HASH_SEQ_STATUS hstat;
1294 PendingOperationEntry *entry;
1296 hash_seq_init(&hstat, pendingOpsTable);
1297 while ((entry = (PendingOperationEntry *) hash_seq_search(&hstat)) != NULL)
1299 if (RelFileNodeBackendEquals(entry->tag.rnode, rnode) &&
1300 entry->tag.forknum == forknum)
1302 /* Okay, cancel this entry */
1303 entry->canceled = true;
1307 else if (segno == FORGET_DATABASE_FSYNC)
1309 /* Remove any pending requests for the entire database */
1310 HASH_SEQ_STATUS hstat;
1311 PendingOperationEntry *entry;
1316 /* Remove fsync requests */
1317 hash_seq_init(&hstat, pendingOpsTable);
1318 while ((entry = (PendingOperationEntry *) hash_seq_search(&hstat)) != NULL)
1320 if (entry->tag.rnode.node.dbNode == rnode.node.dbNode)
1322 /* Okay, cancel this entry */
1323 entry->canceled = true;
1327 /* Remove unlink requests */
1329 for (cell = list_head(pendingUnlinks); cell; cell = next)
1331 PendingUnlinkEntry *entry = (PendingUnlinkEntry *) lfirst(cell);
1334 if (entry->rnode.node.dbNode == rnode.node.dbNode)
1336 pendingUnlinks = list_delete_cell(pendingUnlinks, cell, prev);
1343 else if (segno == UNLINK_RELATION_REQUEST)
1345 /* Unlink request: put it in the linked list */
1346 MemoryContext oldcxt = MemoryContextSwitchTo(MdCxt);
1347 PendingUnlinkEntry *entry;
1349 entry = palloc(sizeof(PendingUnlinkEntry));
1350 entry->rnode = rnode;
1351 entry->cycle_ctr = mdckpt_cycle_ctr;
1353 pendingUnlinks = lappend(pendingUnlinks, entry);
1355 MemoryContextSwitchTo(oldcxt);
1359 /* Normal case: enter a request to fsync this segment */
1360 PendingOperationTag key;
1361 PendingOperationEntry *entry;
1364 /* ensure any pad bytes in the hash key are zeroed */
1365 MemSet(&key, 0, sizeof(key));
1367 key.forknum = forknum;
1370 entry = (PendingOperationEntry *) hash_search(pendingOpsTable,
1374 /* if new or previously canceled entry, initialize it */
1375 if (!found || entry->canceled)
1377 entry->canceled = false;
1378 entry->cycle_ctr = mdsync_cycle_ctr;
1382 * NB: it's intentional that we don't change cycle_ctr if the entry
1383 * already exists. The fsync request must be treated as old, even
1384 * though the new request will be satisfied too by any subsequent
1387 * However, if the entry is present but is marked canceled, we should
1388 * act just as though it wasn't there. The only case where this could
1389 * happen would be if a file had been deleted, we received but did not
1390 * yet act on the cancel request, and the same relfilenode was then
1391 * assigned to a new file. We mustn't lose the new request, but it
1392 * should be considered new not old.
1398 * ForgetRelationFsyncRequests -- forget any fsyncs for a rel
1401 ForgetRelationFsyncRequests(RelFileNodeBackend rnode, ForkNumber forknum)
1403 if (pendingOpsTable)
1405 /* standalone backend or startup process: fsync state is local */
1406 RememberFsyncRequest(rnode, forknum, FORGET_RELATION_FSYNC);
1408 else if (IsUnderPostmaster)
1411 * Notify the bgwriter about it. If we fail to queue the revoke
1412 * message, we have to sleep and try again ... ugly, but hopefully
1413 * won't happen often.
1415 * XXX should we CHECK_FOR_INTERRUPTS in this loop? Escaping with an
1416 * error would leave the no-longer-used file still present on disk,
1417 * which would be bad, so I'm inclined to assume that the bgwriter
1418 * will always empty the queue soon.
1420 while (!ForwardFsyncRequest(rnode, forknum, FORGET_RELATION_FSYNC))
1421 pg_usleep(10000L); /* 10 msec seems a good number */
1424 * Note we don't wait for the bgwriter to actually absorb the revoke
1425 * message; see mdsync() for the implications.
1431 * ForgetDatabaseFsyncRequests -- forget any fsyncs and unlinks for a DB
1434 ForgetDatabaseFsyncRequests(Oid dbid)
1436 RelFileNodeBackend rnode;
1438 rnode.node.dbNode = dbid;
1439 rnode.node.spcNode = 0;
1440 rnode.node.relNode = 0;
1441 rnode.backend = InvalidBackendId;
1443 if (pendingOpsTable)
1445 /* standalone backend or startup process: fsync state is local */
1446 RememberFsyncRequest(rnode, InvalidForkNumber, FORGET_DATABASE_FSYNC);
1448 else if (IsUnderPostmaster)
1450 /* see notes in ForgetRelationFsyncRequests */
1451 while (!ForwardFsyncRequest(rnode, InvalidForkNumber,
1452 FORGET_DATABASE_FSYNC))
1453 pg_usleep(10000L); /* 10 msec seems a good number */
1459 * _fdvec_alloc() -- Make a MdfdVec object.
1464 return (MdfdVec *) MemoryContextAlloc(MdCxt, sizeof(MdfdVec));
1468 * Return the filename for the specified segment of the relation. The
1469 * returned string is palloc'd.
1472 _mdfd_segpath(SMgrRelation reln, ForkNumber forknum, BlockNumber segno)
1477 path = relpath(reln->smgr_rnode, forknum);
1481 /* be sure we have enough space for the '.segno' */
1482 fullpath = (char *) palloc(strlen(path) + 12);
1483 sprintf(fullpath, "%s.%u", path, segno);
1493 * Open the specified segment of the relation,
1494 * and make a MdfdVec object for it. Returns NULL on failure.
1497 _mdfd_openseg(SMgrRelation reln, ForkNumber forknum, BlockNumber segno,
1504 fullpath = _mdfd_segpath(reln, forknum, segno);
1507 fd = PathNameOpenFile(fullpath, O_RDWR | PG_BINARY | oflags, 0600);
1514 /* allocate an mdfdvec entry for it */
1517 /* fill the entry */
1519 v->mdfd_segno = segno;
1520 v->mdfd_chain = NULL;
1521 Assert(_mdnblocks(reln, forknum, v) <= ((BlockNumber) RELSEG_SIZE));
1528 * _mdfd_getseg() -- Find the segment of the relation holding the
1531 * If the segment doesn't exist, we ereport, return NULL, or create the
1532 * segment, according to "behavior". Note: skipFsync is only used in the
1533 * EXTENSION_CREATE case.
1536 _mdfd_getseg(SMgrRelation reln, ForkNumber forknum, BlockNumber blkno,
1537 bool skipFsync, ExtensionBehavior behavior)
1539 MdfdVec *v = mdopen(reln, forknum, behavior);
1540 BlockNumber targetseg;
1541 BlockNumber nextsegno;
1544 return NULL; /* only possible if EXTENSION_RETURN_NULL */
1546 targetseg = blkno / ((BlockNumber) RELSEG_SIZE);
1547 for (nextsegno = 1; nextsegno <= targetseg; nextsegno++)
1549 Assert(nextsegno == v->mdfd_segno + 1);
1551 if (v->mdfd_chain == NULL)
1554 * Normally we will create new segments only if authorized by the
1555 * caller (i.e., we are doing mdextend()). But when doing WAL
1556 * recovery, create segments anyway; this allows cases such as
1557 * replaying WAL data that has a write into a high-numbered
1558 * segment of a relation that was later deleted. We want to go
1559 * ahead and create the segments so we can finish out the replay.
1561 * We have to maintain the invariant that segments before the last
1562 * active segment are of size RELSEG_SIZE; therefore, pad them out
1563 * with zeroes if needed. (This only matters if caller is
1564 * extending the relation discontiguously, but that can happen in
1567 if (behavior == EXTENSION_CREATE || InRecovery)
1569 if (_mdnblocks(reln, forknum, v) < RELSEG_SIZE)
1571 char *zerobuf = palloc0(BLCKSZ);
1573 mdextend(reln, forknum,
1574 nextsegno * ((BlockNumber) RELSEG_SIZE) - 1,
1575 zerobuf, skipFsync);
1578 v->mdfd_chain = _mdfd_openseg(reln, forknum, +nextsegno, O_CREAT);
1582 /* We won't create segment if not existent */
1583 v->mdfd_chain = _mdfd_openseg(reln, forknum, nextsegno, 0);
1585 if (v->mdfd_chain == NULL)
1587 if (behavior == EXTENSION_RETURN_NULL &&
1588 FILE_POSSIBLY_DELETED(errno))
1591 (errcode_for_file_access(),
1592 errmsg("could not open file \"%s\" (target block %u): %m",
1593 _mdfd_segpath(reln, forknum, nextsegno),
1603 * Get number of blocks present in a single disk file
1606 _mdnblocks(SMgrRelation reln, ForkNumber forknum, MdfdVec *seg)
1610 len = FileSeek(seg->mdfd_vfd, 0L, SEEK_END);
1613 (errcode_for_file_access(),
1614 errmsg("could not seek to end of file \"%s\": %m",
1615 FilePathName(seg->mdfd_vfd))));
1616 /* note that this calculation will ignore any partial block at EOF */
1617 return (BlockNumber) (len / BLCKSZ);