1 /*-------------------------------------------------------------------------
4 * This code manages relations that reside on magnetic disk.
6 * Or at least, that was what the Berkeley folk had in mind when they named
7 * this file. In reality, what this code provides is an interface from
8 * the smgr API to Unix-like filesystem APIs, so it will work with any type
9 * of device for which the operating system provides filesystem support.
10 * It doesn't matter whether the bits are on spinning rust or some other
13 * Portions Copyright (c) 1996-2014, PostgreSQL Global Development Group
14 * Portions Copyright (c) 1994, Regents of the University of California
18 * src/backend/storage/smgr/md.c
20 *-------------------------------------------------------------------------
28 #include "miscadmin.h"
29 #include "access/xlog.h"
30 #include "catalog/catalog.h"
31 #include "portability/instr_time.h"
32 #include "postmaster/bgwriter.h"
33 #include "storage/fd.h"
34 #include "storage/bufmgr.h"
35 #include "storage/relfilenode.h"
36 #include "storage/smgr.h"
37 #include "utils/hsearch.h"
38 #include "utils/memutils.h"
42 /* intervals for calling AbsorbFsyncRequests in mdsync and mdpostckpt */
43 #define FSYNCS_PER_ABSORB 10
44 #define UNLINKS_PER_ABSORB 10
47 * Special values for the segno arg to RememberFsyncRequest.
49 * Note that CompactCheckpointerRequestQueue assumes that it's OK to remove an
50 * fsync request from the queue if an identical, subsequent request is found.
51 * See comments there before making changes here.
53 #define FORGET_RELATION_FSYNC (InvalidBlockNumber)
54 #define FORGET_DATABASE_FSYNC (InvalidBlockNumber-1)
55 #define UNLINK_RELATION_REQUEST (InvalidBlockNumber-2)
58 * On Windows, we have to interpret EACCES as possibly meaning the same as
59 * ENOENT, because if a file is unlinked-but-not-yet-gone on that platform,
60 * that's what you get. Ugh. This code is designed so that we don't
61 * actually believe these cases are okay without further evidence (namely,
62 * a pending fsync request getting canceled ... see mdsync).
65 #define FILE_POSSIBLY_DELETED(err) ((err) == ENOENT)
67 #define FILE_POSSIBLY_DELETED(err) ((err) == ENOENT || (err) == EACCES)
71 * The magnetic disk storage manager keeps track of open file
72 * descriptors in its own descriptor pool. This is done to make it
73 * easier to support relations that are larger than the operating
74 * system's file size limit (often 2GBytes). In order to do that,
75 * we break relations up into "segment" files that are each shorter than
76 * the OS file size limit. The segment size is set by the RELSEG_SIZE
77 * configuration constant in pg_config.h.
79 * On disk, a relation must consist of consecutively numbered segment
80 * files in the pattern
81 * -- Zero or more full segments of exactly RELSEG_SIZE blocks each
82 * -- Exactly one partial segment of size 0 <= size < RELSEG_SIZE blocks
83 * -- Optionally, any number of inactive segments of size 0 blocks.
84 * The full and partial segments are collectively the "active" segments.
85 * Inactive segments are those that once contained data but are currently
86 * not needed because of an mdtruncate() operation. The reason for leaving
87 * them present at size zero, rather than unlinking them, is that other
88 * backends and/or the checkpointer might be holding open file references to
89 * such segments. If the relation expands again after mdtruncate(), such
90 * that a deactivated segment becomes active again, it is important that
91 * such file references still be valid --- else data might get written
92 * out to an unlinked old copy of a segment file that will eventually
95 * The file descriptor pointer (md_fd field) stored in the SMgrRelation
96 * cache is, therefore, just the head of a list of MdfdVec objects, one
97 * per segment. But note the md_fd pointer can be NULL, indicating
100 * Also note that mdfd_chain == NULL does not necessarily mean the relation
101 * doesn't have another segment after this one; we may just not have
102 * opened the next segment yet. (We could not have "all segments are
103 * in the chain" as an invariant anyway, since another backend could
104 * extend the relation when we weren't looking.) We do not make chain
105 * entries for inactive segments, however; as soon as we find a partial
106 * segment, we assume that any subsequent segments are inactive.
108 * All MdfdVec objects are palloc'd in the MdCxt memory context.
111 typedef struct _MdfdVec
113 File mdfd_vfd; /* fd number in fd.c's pool */
114 BlockNumber mdfd_segno; /* segment number, from 0 */
115 struct _MdfdVec *mdfd_chain; /* next segment, or NULL */
118 static MemoryContext MdCxt; /* context for all MdfdVec objects */
122 * In some contexts (currently, standalone backends and the checkpointer)
123 * we keep track of pending fsync operations: we need to remember all relation
124 * segments that have been written since the last checkpoint, so that we can
125 * fsync them down to disk before completing the next checkpoint. This hash
126 * table remembers the pending operations. We use a hash table mostly as
127 * a convenient way of merging duplicate requests.
129 * We use a similar mechanism to remember no-longer-needed files that can
130 * be deleted after the next checkpoint, but we use a linked list instead of
131 * a hash table, because we don't expect there to be any duplicate requests.
133 * These mechanisms are only used for non-temp relations; we never fsync
134 * temp rels, nor do we need to postpone their deletion (see comments in
137 * (Regular backends do not track pending operations locally, but forward
138 * them to the checkpointer.)
140 typedef uint16 CycleCtr; /* can be any convenient integer size */
144 RelFileNode rnode; /* hash table key (must be first!) */
145 CycleCtr cycle_ctr; /* mdsync_cycle_ctr of oldest request */
146 /* requests[f] has bit n set if we need to fsync segment n of fork f */
147 Bitmapset *requests[MAX_FORKNUM + 1];
148 /* canceled[f] is true if we canceled fsyncs for fork "recently" */
149 bool canceled[MAX_FORKNUM + 1];
150 } PendingOperationEntry;
154 RelFileNode rnode; /* the dead relation to delete */
155 CycleCtr cycle_ctr; /* mdckpt_cycle_ctr when request was made */
156 } PendingUnlinkEntry;
158 static HTAB *pendingOpsTable = NULL;
159 static List *pendingUnlinks = NIL;
160 static MemoryContext pendingOpsCxt; /* context for the above */
162 static CycleCtr mdsync_cycle_ctr = 0;
163 static CycleCtr mdckpt_cycle_ctr = 0;
166 typedef enum /* behavior for mdopen & _mdfd_getseg */
168 EXTENSION_FAIL, /* ereport if segment not present */
169 EXTENSION_RETURN_NULL, /* return NULL if not present */
170 EXTENSION_CREATE /* create new segments as needed */
174 static void mdunlinkfork(RelFileNodeBackend rnode, ForkNumber forkNum,
176 static MdfdVec *mdopen(SMgrRelation reln, ForkNumber forknum,
177 ExtensionBehavior behavior);
178 static void register_dirty_segment(SMgrRelation reln, ForkNumber forknum,
180 static void register_unlink(RelFileNodeBackend rnode);
181 static MdfdVec *_fdvec_alloc(void);
182 static char *_mdfd_segpath(SMgrRelation reln, ForkNumber forknum,
184 static MdfdVec *_mdfd_openseg(SMgrRelation reln, ForkNumber forkno,
185 BlockNumber segno, int oflags);
186 static MdfdVec *_mdfd_getseg(SMgrRelation reln, ForkNumber forkno,
187 BlockNumber blkno, bool skipFsync, ExtensionBehavior behavior);
188 static BlockNumber _mdnblocks(SMgrRelation reln, ForkNumber forknum,
193 * mdinit() -- Initialize private state for magnetic disk storage manager.
198 MdCxt = AllocSetContextCreate(TopMemoryContext,
200 ALLOCSET_DEFAULT_MINSIZE,
201 ALLOCSET_DEFAULT_INITSIZE,
202 ALLOCSET_DEFAULT_MAXSIZE);
205 * Create pending-operations hashtable if we need it. Currently, we need
206 * it if we are standalone (not under a postmaster) or if we are a startup
207 * or checkpointer auxiliary process.
209 if (!IsUnderPostmaster || AmStartupProcess() || AmCheckpointerProcess())
214 * XXX: The checkpointer needs to add entries to the pending ops table
215 * when absorbing fsync requests. That is done within a critical
216 * section, which isn't usually allowed, but we make an exception.
217 * It means that there's a theoretical possibility that you run out of
218 * memory while absorbing fsync requests, which leads to a PANIC.
219 * Fortunately the hash table is small so that's unlikely to happen in
222 pendingOpsCxt = AllocSetContextCreate(MdCxt,
223 "Pending Ops Context",
224 ALLOCSET_DEFAULT_MINSIZE,
225 ALLOCSET_DEFAULT_INITSIZE,
226 ALLOCSET_DEFAULT_MAXSIZE);
227 MemoryContextAllowInCriticalSection(pendingOpsCxt, true);
229 MemSet(&hash_ctl, 0, sizeof(hash_ctl));
230 hash_ctl.keysize = sizeof(RelFileNode);
231 hash_ctl.entrysize = sizeof(PendingOperationEntry);
232 hash_ctl.hcxt = pendingOpsCxt;
233 pendingOpsTable = hash_create("Pending Ops Table",
236 HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
237 pendingUnlinks = NIL;
242 * In archive recovery, we rely on checkpointer to do fsyncs, but we will have
243 * already created the pendingOpsTable during initialization of the startup
244 * process. Calling this function drops the local pendingOpsTable so that
245 * subsequent requests will be forwarded to checkpointer.
248 SetForwardFsyncRequests(void)
250 /* Perform any pending fsyncs we may have queued up, then drop table */
254 hash_destroy(pendingOpsTable);
256 pendingOpsTable = NULL;
259 * We should not have any pending unlink requests, since mdunlink doesn't
260 * queue unlink requests when isRedo.
262 Assert(pendingUnlinks == NIL);
266 * mdexists() -- Does the physical file exist?
268 * Note: this will return true for lingering files, with pending deletions
271 mdexists(SMgrRelation reln, ForkNumber forkNum)
274 * Close it first, to ensure that we notice if the fork has been unlinked
275 * since we opened it.
277 mdclose(reln, forkNum);
279 return (mdopen(reln, forkNum, EXTENSION_RETURN_NULL) != NULL);
283 * mdcreate() -- Create a new relation on magnetic disk.
285 * If isRedo is true, it's okay for the relation to exist already.
288 mdcreate(SMgrRelation reln, ForkNumber forkNum, bool isRedo)
293 if (isRedo && reln->md_fd[forkNum] != NULL)
294 return; /* created and opened already... */
296 Assert(reln->md_fd[forkNum] == NULL);
298 path = relpath(reln->smgr_rnode, forkNum);
300 fd = PathNameOpenFile(path, O_RDWR | O_CREAT | O_EXCL | PG_BINARY, 0600);
304 int save_errno = errno;
307 * During bootstrap, there are cases where a system relation will be
308 * accessed (by internal backend processes) before the bootstrap
309 * script nominally creates it. Therefore, allow the file to exist
310 * already, even if isRedo is not set. (See also mdopen)
312 if (isRedo || IsBootstrapProcessingMode())
313 fd = PathNameOpenFile(path, O_RDWR | PG_BINARY, 0600);
316 /* be sure to report the error reported by create, not open */
319 (errcode_for_file_access(),
320 errmsg("could not create file \"%s\": %m", path)));
326 reln->md_fd[forkNum] = _fdvec_alloc();
328 reln->md_fd[forkNum]->mdfd_vfd = fd;
329 reln->md_fd[forkNum]->mdfd_segno = 0;
330 reln->md_fd[forkNum]->mdfd_chain = NULL;
334 * mdunlink() -- Unlink a relation.
336 * Note that we're passed a RelFileNodeBackend --- by the time this is called,
337 * there won't be an SMgrRelation hashtable entry anymore.
339 * forkNum can be a fork number to delete a specific fork, or InvalidForkNumber
340 * to delete all forks.
342 * For regular relations, we don't unlink the first segment file of the rel,
343 * but just truncate it to zero length, and record a request to unlink it after
344 * the next checkpoint. Additional segments can be unlinked immediately,
345 * however. Leaving the empty file in place prevents that relfilenode
346 * number from being reused. The scenario this protects us from is:
347 * 1. We delete a relation (and commit, and actually remove its file).
348 * 2. We create a new relation, which by chance gets the same relfilenode as
349 * the just-deleted one (OIDs must've wrapped around for that to happen).
350 * 3. We crash before another checkpoint occurs.
351 * During replay, we would delete the file and then recreate it, which is fine
352 * if the contents of the file were repopulated by subsequent WAL entries.
353 * But if we didn't WAL-log insertions, but instead relied on fsyncing the
354 * file after populating it (as for instance CLUSTER and CREATE INDEX do),
355 * the contents of the file would be lost forever. By leaving the empty file
356 * until after the next checkpoint, we prevent reassignment of the relfilenode
357 * number until it's safe, because relfilenode assignment skips over any
360 * We do not need to go through this dance for temp relations, though, because
361 * we never make WAL entries for temp rels, and so a temp rel poses no threat
362 * to the health of a regular rel that has taken over its relfilenode number.
363 * The fact that temp rels and regular rels have different file naming
364 * patterns provides additional safety.
366 * All the above applies only to the relation's main fork; other forks can
367 * just be removed immediately, since they are not needed to prevent the
368 * relfilenode number from being recycled. Also, we do not carefully
369 * track whether other forks have been created or not, but just attempt to
370 * unlink them unconditionally; so we should never complain about ENOENT.
372 * If isRedo is true, it's unsurprising for the relation to be already gone.
373 * Also, we should remove the file immediately instead of queuing a request
374 * for later, since during redo there's no possibility of creating a
375 * conflicting relation.
377 * Note: any failure should be reported as WARNING not ERROR, because
378 * we are usually not in a transaction anymore when this is called.
381 mdunlink(RelFileNodeBackend rnode, ForkNumber forkNum, bool isRedo)
384 * We have to clean out any pending fsync requests for the doomed
385 * relation, else the next mdsync() will fail. There can't be any such
386 * requests for a temp relation, though. We can send just one request
387 * even when deleting multiple forks, since the fsync queuing code accepts
388 * the "InvalidForkNumber = all forks" convention.
390 if (!RelFileNodeBackendIsTemp(rnode))
391 ForgetRelationFsyncRequests(rnode.node, forkNum);
393 /* Now do the per-fork work */
394 if (forkNum == InvalidForkNumber)
396 for (forkNum = 0; forkNum <= MAX_FORKNUM; forkNum++)
397 mdunlinkfork(rnode, forkNum, isRedo);
400 mdunlinkfork(rnode, forkNum, isRedo);
404 mdunlinkfork(RelFileNodeBackend rnode, ForkNumber forkNum, bool isRedo)
409 path = relpath(rnode, forkNum);
412 * Delete or truncate the first segment.
414 if (isRedo || forkNum != MAIN_FORKNUM || RelFileNodeBackendIsTemp(rnode))
417 if (ret < 0 && errno != ENOENT)
419 (errcode_for_file_access(),
420 errmsg("could not remove file \"%s\": %m", path)));
424 /* truncate(2) would be easier here, but Windows hasn't got it */
427 fd = OpenTransientFile(path, O_RDWR | PG_BINARY, 0);
432 ret = ftruncate(fd, 0);
434 CloseTransientFile(fd);
439 if (ret < 0 && errno != ENOENT)
441 (errcode_for_file_access(),
442 errmsg("could not truncate file \"%s\": %m", path)));
444 /* Register request to unlink first segment later */
445 register_unlink(rnode);
449 * Delete any additional segments.
453 char *segpath = (char *) palloc(strlen(path) + 12);
457 * Note that because we loop until getting ENOENT, we will correctly
458 * remove all inactive segments as well as active ones.
460 for (segno = 1;; segno++)
462 sprintf(segpath, "%s.%u", path, segno);
463 if (unlink(segpath) < 0)
465 /* ENOENT is expected after the last segment... */
468 (errcode_for_file_access(),
469 errmsg("could not remove file \"%s\": %m", segpath)));
480 * mdextend() -- Add a block to the specified relation.
482 * The semantics are nearly the same as mdwrite(): write at the
483 * specified position. However, this is to be used for the case of
484 * extending a relation (i.e., blocknum is at or beyond the current
485 * EOF). Note that we assume writing a block beyond current EOF
486 * causes intervening file space to become filled with zeroes.
489 mdextend(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum,
490 char *buffer, bool skipFsync)
496 /* This assert is too expensive to have on normally ... */
497 #ifdef CHECK_WRITE_VS_EXTEND
498 Assert(blocknum >= mdnblocks(reln, forknum));
502 * If a relation manages to grow to 2^32-1 blocks, refuse to extend it any
503 * more --- we mustn't create a block whose number actually is
504 * InvalidBlockNumber.
506 if (blocknum == InvalidBlockNumber)
508 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
509 errmsg("cannot extend file \"%s\" beyond %u blocks",
510 relpath(reln->smgr_rnode, forknum),
511 InvalidBlockNumber)));
513 v = _mdfd_getseg(reln, forknum, blocknum, skipFsync, EXTENSION_CREATE);
515 seekpos = (off_t) BLCKSZ *(blocknum % ((BlockNumber) RELSEG_SIZE));
517 Assert(seekpos < (off_t) BLCKSZ * RELSEG_SIZE);
520 * Note: because caller usually obtained blocknum by calling mdnblocks,
521 * which did a seek(SEEK_END), this seek is often redundant and will be
522 * optimized away by fd.c. It's not redundant, however, if there is a
523 * partial page at the end of the file. In that case we want to try to
524 * overwrite the partial page with a full page. It's also not redundant
525 * if bufmgr.c had to dump another buffer of the same file to make room
526 * for the new page's buffer.
528 if (FileSeek(v->mdfd_vfd, seekpos, SEEK_SET) != seekpos)
530 (errcode_for_file_access(),
531 errmsg("could not seek to block %u in file \"%s\": %m",
532 blocknum, FilePathName(v->mdfd_vfd))));
534 if ((nbytes = FileWrite(v->mdfd_vfd, buffer, BLCKSZ)) != BLCKSZ)
538 (errcode_for_file_access(),
539 errmsg("could not extend file \"%s\": %m",
540 FilePathName(v->mdfd_vfd)),
541 errhint("Check free disk space.")));
542 /* short write: complain appropriately */
544 (errcode(ERRCODE_DISK_FULL),
545 errmsg("could not extend file \"%s\": wrote only %d of %d bytes at block %u",
546 FilePathName(v->mdfd_vfd),
547 nbytes, BLCKSZ, blocknum),
548 errhint("Check free disk space.")));
551 if (!skipFsync && !SmgrIsTemp(reln))
552 register_dirty_segment(reln, forknum, v);
554 Assert(_mdnblocks(reln, forknum, v) <= ((BlockNumber) RELSEG_SIZE));
558 * mdopen() -- Open the specified relation.
560 * Note we only open the first segment, when there are multiple segments.
562 * If first segment is not present, either ereport or return NULL according
563 * to "behavior". We treat EXTENSION_CREATE the same as EXTENSION_FAIL;
564 * EXTENSION_CREATE means it's OK to extend an existing relation, not to
565 * invent one out of whole cloth.
568 mdopen(SMgrRelation reln, ForkNumber forknum, ExtensionBehavior behavior)
574 /* No work if already open */
575 if (reln->md_fd[forknum])
576 return reln->md_fd[forknum];
578 path = relpath(reln->smgr_rnode, forknum);
580 fd = PathNameOpenFile(path, O_RDWR | PG_BINARY, 0600);
585 * During bootstrap, there are cases where a system relation will be
586 * accessed (by internal backend processes) before the bootstrap
587 * script nominally creates it. Therefore, accept mdopen() as a
588 * substitute for mdcreate() in bootstrap mode only. (See mdcreate)
590 if (IsBootstrapProcessingMode())
591 fd = PathNameOpenFile(path, O_RDWR | O_CREAT | O_EXCL | PG_BINARY, 0600);
594 if (behavior == EXTENSION_RETURN_NULL &&
595 FILE_POSSIBLY_DELETED(errno))
601 (errcode_for_file_access(),
602 errmsg("could not open file \"%s\": %m", path)));
608 reln->md_fd[forknum] = mdfd = _fdvec_alloc();
611 mdfd->mdfd_segno = 0;
612 mdfd->mdfd_chain = NULL;
613 Assert(_mdnblocks(reln, forknum, mdfd) <= ((BlockNumber) RELSEG_SIZE));
619 * mdclose() -- Close the specified relation, if it isn't closed already.
622 mdclose(SMgrRelation reln, ForkNumber forknum)
624 MdfdVec *v = reln->md_fd[forknum];
626 /* No work if already closed */
630 reln->md_fd[forknum] = NULL; /* prevent dangling pointer after error */
636 /* if not closed already */
637 if (v->mdfd_vfd >= 0)
638 FileClose(v->mdfd_vfd);
639 /* Now free vector */
646 * mdprefetch() -- Initiate asynchronous read of the specified block of a relation
649 mdprefetch(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum)
655 v = _mdfd_getseg(reln, forknum, blocknum, false, EXTENSION_FAIL);
657 seekpos = (off_t) BLCKSZ *(blocknum % ((BlockNumber) RELSEG_SIZE));
659 Assert(seekpos < (off_t) BLCKSZ * RELSEG_SIZE);
661 (void) FilePrefetch(v->mdfd_vfd, seekpos, BLCKSZ);
662 #endif /* USE_PREFETCH */
667 * mdread() -- Read the specified block from a relation.
670 mdread(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum,
677 TRACE_POSTGRESQL_SMGR_MD_READ_START(forknum, blocknum,
678 reln->smgr_rnode.node.spcNode,
679 reln->smgr_rnode.node.dbNode,
680 reln->smgr_rnode.node.relNode,
681 reln->smgr_rnode.backend);
683 v = _mdfd_getseg(reln, forknum, blocknum, false, EXTENSION_FAIL);
685 seekpos = (off_t) BLCKSZ *(blocknum % ((BlockNumber) RELSEG_SIZE));
687 Assert(seekpos < (off_t) BLCKSZ * RELSEG_SIZE);
689 if (FileSeek(v->mdfd_vfd, seekpos, SEEK_SET) != seekpos)
691 (errcode_for_file_access(),
692 errmsg("could not seek to block %u in file \"%s\": %m",
693 blocknum, FilePathName(v->mdfd_vfd))));
695 nbytes = FileRead(v->mdfd_vfd, buffer, BLCKSZ);
697 TRACE_POSTGRESQL_SMGR_MD_READ_DONE(forknum, blocknum,
698 reln->smgr_rnode.node.spcNode,
699 reln->smgr_rnode.node.dbNode,
700 reln->smgr_rnode.node.relNode,
701 reln->smgr_rnode.backend,
705 if (nbytes != BLCKSZ)
709 (errcode_for_file_access(),
710 errmsg("could not read block %u in file \"%s\": %m",
711 blocknum, FilePathName(v->mdfd_vfd))));
714 * Short read: we are at or past EOF, or we read a partial block at
715 * EOF. Normally this is an error; upper levels should never try to
716 * read a nonexistent block. However, if zero_damaged_pages is ON or
717 * we are InRecovery, we should instead return zeroes without
718 * complaining. This allows, for example, the case of trying to
719 * update a block that was later truncated away.
721 if (zero_damaged_pages || InRecovery)
722 MemSet(buffer, 0, BLCKSZ);
725 (errcode(ERRCODE_DATA_CORRUPTED),
726 errmsg("could not read block %u in file \"%s\": read only %d of %d bytes",
727 blocknum, FilePathName(v->mdfd_vfd),
733 * mdwrite() -- Write the supplied block at the appropriate location.
735 * This is to be used only for updating already-existing blocks of a
736 * relation (ie, those before the current EOF). To extend a relation,
740 mdwrite(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum,
741 char *buffer, bool skipFsync)
747 /* This assert is too expensive to have on normally ... */
748 #ifdef CHECK_WRITE_VS_EXTEND
749 Assert(blocknum < mdnblocks(reln, forknum));
752 TRACE_POSTGRESQL_SMGR_MD_WRITE_START(forknum, blocknum,
753 reln->smgr_rnode.node.spcNode,
754 reln->smgr_rnode.node.dbNode,
755 reln->smgr_rnode.node.relNode,
756 reln->smgr_rnode.backend);
758 v = _mdfd_getseg(reln, forknum, blocknum, skipFsync, EXTENSION_FAIL);
760 seekpos = (off_t) BLCKSZ *(blocknum % ((BlockNumber) RELSEG_SIZE));
762 Assert(seekpos < (off_t) BLCKSZ * RELSEG_SIZE);
764 if (FileSeek(v->mdfd_vfd, seekpos, SEEK_SET) != seekpos)
766 (errcode_for_file_access(),
767 errmsg("could not seek to block %u in file \"%s\": %m",
768 blocknum, FilePathName(v->mdfd_vfd))));
770 nbytes = FileWrite(v->mdfd_vfd, buffer, BLCKSZ);
772 TRACE_POSTGRESQL_SMGR_MD_WRITE_DONE(forknum, blocknum,
773 reln->smgr_rnode.node.spcNode,
774 reln->smgr_rnode.node.dbNode,
775 reln->smgr_rnode.node.relNode,
776 reln->smgr_rnode.backend,
780 if (nbytes != BLCKSZ)
784 (errcode_for_file_access(),
785 errmsg("could not write block %u in file \"%s\": %m",
786 blocknum, FilePathName(v->mdfd_vfd))));
787 /* short write: complain appropriately */
789 (errcode(ERRCODE_DISK_FULL),
790 errmsg("could not write block %u in file \"%s\": wrote only %d of %d bytes",
792 FilePathName(v->mdfd_vfd),
794 errhint("Check free disk space.")));
797 if (!skipFsync && !SmgrIsTemp(reln))
798 register_dirty_segment(reln, forknum, v);
802 * mdnblocks() -- Get the number of blocks stored in a relation.
804 * Important side effect: all active segments of the relation are opened
805 * and added to the mdfd_chain list. If this routine has not been
806 * called, then only segments up to the last one actually touched
807 * are present in the chain.
810 mdnblocks(SMgrRelation reln, ForkNumber forknum)
812 MdfdVec *v = mdopen(reln, forknum, EXTENSION_FAIL);
814 BlockNumber segno = 0;
817 * Skip through any segments that aren't the last one, to avoid redundant
818 * seeks on them. We have previously verified that these segments are
819 * exactly RELSEG_SIZE long, and it's useless to recheck that each time.
821 * NOTE: this assumption could only be wrong if another backend has
822 * truncated the relation. We rely on higher code levels to handle that
823 * scenario by closing and re-opening the md fd, which is handled via
824 * relcache flush. (Since the checkpointer doesn't participate in
825 * relcache flush, it could have segment chain entries for inactive
826 * segments; that's OK because the checkpointer never needs to compute
829 while (v->mdfd_chain != NULL)
837 nblocks = _mdnblocks(reln, forknum, v);
838 if (nblocks > ((BlockNumber) RELSEG_SIZE))
839 elog(FATAL, "segment too big");
840 if (nblocks < ((BlockNumber) RELSEG_SIZE))
841 return (segno * ((BlockNumber) RELSEG_SIZE)) + nblocks;
844 * If segment is exactly RELSEG_SIZE, advance to next one.
848 if (v->mdfd_chain == NULL)
851 * Because we pass O_CREAT, we will create the next segment (with
852 * zero length) immediately, if the last segment is of length
853 * RELSEG_SIZE. While perhaps not strictly necessary, this keeps
856 v->mdfd_chain = _mdfd_openseg(reln, forknum, segno, O_CREAT);
857 if (v->mdfd_chain == NULL)
859 (errcode_for_file_access(),
860 errmsg("could not open file \"%s\": %m",
861 _mdfd_segpath(reln, forknum, segno))));
869 * mdtruncate() -- Truncate relation to specified number of blocks.
872 mdtruncate(SMgrRelation reln, ForkNumber forknum, BlockNumber nblocks)
876 BlockNumber priorblocks;
879 * NOTE: mdnblocks makes sure we have opened all active segments, so that
880 * truncation loop will get them all!
882 curnblk = mdnblocks(reln, forknum);
883 if (nblocks > curnblk)
885 /* Bogus request ... but no complaint if InRecovery */
889 (errmsg("could not truncate file \"%s\" to %u blocks: it's only %u blocks now",
890 relpath(reln->smgr_rnode, forknum),
893 if (nblocks == curnblk)
894 return; /* no work */
896 v = mdopen(reln, forknum, EXTENSION_FAIL);
903 if (priorblocks > nblocks)
906 * This segment is no longer active (and has already been unlinked
907 * from the mdfd_chain). We truncate the file, but do not delete
908 * it, for reasons explained in the header comments.
910 if (FileTruncate(v->mdfd_vfd, 0) < 0)
912 (errcode_for_file_access(),
913 errmsg("could not truncate file \"%s\": %m",
914 FilePathName(v->mdfd_vfd))));
916 if (!SmgrIsTemp(reln))
917 register_dirty_segment(reln, forknum, v);
919 Assert(ov != reln->md_fd[forknum]); /* we never drop the 1st
923 else if (priorblocks + ((BlockNumber) RELSEG_SIZE) > nblocks)
926 * This is the last segment we want to keep. Truncate the file to
927 * the right length, and clear chain link that points to any
928 * remaining segments (which we shall zap). NOTE: if nblocks is
929 * exactly a multiple K of RELSEG_SIZE, we will truncate the K+1st
930 * segment to 0 length but keep it. This adheres to the invariant
931 * given in the header comments.
933 BlockNumber lastsegblocks = nblocks - priorblocks;
935 if (FileTruncate(v->mdfd_vfd, (off_t) lastsegblocks * BLCKSZ) < 0)
937 (errcode_for_file_access(),
938 errmsg("could not truncate file \"%s\" to %u blocks: %m",
939 FilePathName(v->mdfd_vfd),
941 if (!SmgrIsTemp(reln))
942 register_dirty_segment(reln, forknum, v);
944 ov->mdfd_chain = NULL;
949 * We still need this segment and 0 or more blocks beyond it, so
950 * nothing to do here.
954 priorblocks += RELSEG_SIZE;
959 * mdimmedsync() -- Immediately sync a relation to stable storage.
961 * Note that only writes already issued are synced; this routine knows
962 * nothing of dirty buffers that may exist inside the buffer manager.
965 mdimmedsync(SMgrRelation reln, ForkNumber forknum)
970 * NOTE: mdnblocks makes sure we have opened all active segments, so that
971 * fsync loop will get them all!
973 mdnblocks(reln, forknum);
975 v = mdopen(reln, forknum, EXTENSION_FAIL);
979 if (FileSync(v->mdfd_vfd) < 0)
981 (errcode_for_file_access(),
982 errmsg("could not fsync file \"%s\": %m",
983 FilePathName(v->mdfd_vfd))));
989 * mdsync() -- Sync previous writes to stable storage.
994 static bool mdsync_in_progress = false;
996 HASH_SEQ_STATUS hstat;
997 PendingOperationEntry *entry;
1000 /* Statistics on sync times */
1002 instr_time sync_start,
1007 uint64 total_elapsed = 0;
1010 * This is only called during checkpoints, and checkpoints should only
1011 * occur in processes that have created a pendingOpsTable.
1013 if (!pendingOpsTable)
1014 elog(ERROR, "cannot sync without a pendingOpsTable");
1017 * If we are in the checkpointer, the sync had better include all fsync
1018 * requests that were queued by backends up to this point. The tightest
1019 * race condition that could occur is that a buffer that must be written
1020 * and fsync'd for the checkpoint could have been dumped by a backend just
1021 * before it was visited by BufferSync(). We know the backend will have
1022 * queued an fsync request before clearing the buffer's dirtybit, so we
1023 * are safe as long as we do an Absorb after completing BufferSync().
1025 AbsorbFsyncRequests();
1028 * To avoid excess fsync'ing (in the worst case, maybe a never-terminating
1029 * checkpoint), we want to ignore fsync requests that are entered into the
1030 * hashtable after this point --- they should be processed next time,
1031 * instead. We use mdsync_cycle_ctr to tell old entries apart from new
1032 * ones: new ones will have cycle_ctr equal to the incremented value of
1035 * In normal circumstances, all entries present in the table at this point
1036 * will have cycle_ctr exactly equal to the current (about to be old)
1037 * value of mdsync_cycle_ctr. However, if we fail partway through the
1038 * fsync'ing loop, then older values of cycle_ctr might remain when we
1039 * come back here to try again. Repeated checkpoint failures would
1040 * eventually wrap the counter around to the point where an old entry
1041 * might appear new, causing us to skip it, possibly allowing a checkpoint
1042 * to succeed that should not have. To forestall wraparound, any time the
1043 * previous mdsync() failed to complete, run through the table and
1044 * forcibly set cycle_ctr = mdsync_cycle_ctr.
1046 * Think not to merge this loop with the main loop, as the problem is
1047 * exactly that that loop may fail before having visited all the entries.
1048 * From a performance point of view it doesn't matter anyway, as this path
1049 * will never be taken in a system that's functioning normally.
1051 if (mdsync_in_progress)
1053 /* prior try failed, so update any stale cycle_ctr values */
1054 hash_seq_init(&hstat, pendingOpsTable);
1055 while ((entry = (PendingOperationEntry *) hash_seq_search(&hstat)) != NULL)
1057 entry->cycle_ctr = mdsync_cycle_ctr;
1061 /* Advance counter so that new hashtable entries are distinguishable */
1064 /* Set flag to detect failure if we don't reach the end of the loop */
1065 mdsync_in_progress = true;
1067 /* Now scan the hashtable for fsync requests to process */
1068 absorb_counter = FSYNCS_PER_ABSORB;
1069 hash_seq_init(&hstat, pendingOpsTable);
1070 while ((entry = (PendingOperationEntry *) hash_seq_search(&hstat)) != NULL)
1075 * If the entry is new then don't process it this time; it might
1076 * contain multiple fsync-request bits, but they are all new. Note
1077 * "continue" bypasses the hash-remove call at the bottom of the loop.
1079 if (entry->cycle_ctr == mdsync_cycle_ctr)
1082 /* Else assert we haven't missed it */
1083 Assert((CycleCtr) (entry->cycle_ctr + 1) == mdsync_cycle_ctr);
1086 * Scan over the forks and segments represented by the entry.
1088 * The bitmap manipulations are slightly tricky, because we can call
1089 * AbsorbFsyncRequests() inside the loop and that could result in
1090 * bms_add_member() modifying and even re-palloc'ing the bitmapsets.
1091 * This is okay because we unlink each bitmapset from the hashtable
1092 * entry before scanning it. That means that any incoming fsync
1093 * requests will be processed now if they reach the table before we
1094 * begin to scan their fork.
1096 for (forknum = 0; forknum <= MAX_FORKNUM; forknum++)
1098 Bitmapset *requests = entry->requests[forknum];
1101 entry->requests[forknum] = NULL;
1102 entry->canceled[forknum] = false;
1104 while ((segno = bms_first_member(requests)) >= 0)
1109 * If fsync is off then we don't have to bother opening the
1110 * file at all. (We delay checking until this point so that
1111 * changing fsync on the fly behaves sensibly.)
1117 * If in checkpointer, we want to absorb pending requests
1118 * every so often to prevent overflow of the fsync request
1119 * queue. It is unspecified whether newly-added entries will
1120 * be visited by hash_seq_search, but we don't care since we
1121 * don't need to process them anyway.
1123 if (--absorb_counter <= 0)
1125 AbsorbFsyncRequests();
1126 absorb_counter = FSYNCS_PER_ABSORB;
1130 * The fsync table could contain requests to fsync segments
1131 * that have been deleted (unlinked) by the time we get to
1132 * them. Rather than just hoping an ENOENT (or EACCES on
1133 * Windows) error can be ignored, what we do on error is
1134 * absorb pending requests and then retry. Since mdunlink()
1135 * queues a "cancel" message before actually unlinking, the
1136 * fsync request is guaranteed to be marked canceled after the
1137 * absorb if it really was this case. DROP DATABASE likewise
1138 * has to tell us to forget fsync requests before it starts
1141 for (failures = 0;; failures++) /* loop exits at "break" */
1149 * Find or create an smgr hash entry for this relation.
1150 * This may seem a bit unclean -- md calling smgr? But
1151 * it's really the best solution. It ensures that the
1152 * open file reference isn't permanently leaked if we get
1153 * an error here. (You may say "but an unreferenced
1154 * SMgrRelation is still a leak!" Not really, because the
1155 * only case in which a checkpoint is done by a process
1156 * that isn't about to shut down is in the checkpointer,
1157 * and it will periodically do smgrcloseall(). This fact
1158 * justifies our not closing the reln in the success path
1159 * either, which is a good thing since in non-checkpointer
1160 * cases we couldn't safely do that.)
1162 reln = smgropen(entry->rnode, InvalidBackendId);
1164 /* Attempt to open and fsync the target segment */
1165 seg = _mdfd_getseg(reln, forknum,
1166 (BlockNumber) segno * (BlockNumber) RELSEG_SIZE,
1167 false, EXTENSION_RETURN_NULL);
1169 INSTR_TIME_SET_CURRENT(sync_start);
1172 FileSync(seg->mdfd_vfd) >= 0)
1174 /* Success; update statistics about sync timing */
1175 INSTR_TIME_SET_CURRENT(sync_end);
1176 sync_diff = sync_end;
1177 INSTR_TIME_SUBTRACT(sync_diff, sync_start);
1178 elapsed = INSTR_TIME_GET_MICROSEC(sync_diff);
1179 if (elapsed > longest)
1181 total_elapsed += elapsed;
1183 if (log_checkpoints)
1184 elog(DEBUG1, "checkpoint sync: number=%d file=%s time=%.3f msec",
1186 FilePathName(seg->mdfd_vfd),
1187 (double) elapsed / 1000);
1189 break; /* out of retry loop */
1192 /* Compute file name for use in message */
1194 path = _mdfd_segpath(reln, forknum, (BlockNumber) segno);
1198 * It is possible that the relation has been dropped or
1199 * truncated since the fsync request was entered.
1200 * Therefore, allow ENOENT, but only if we didn't fail
1201 * already on this file. This applies both for
1202 * _mdfd_getseg() and for FileSync, since fd.c might have
1203 * closed the file behind our back.
1205 * XXX is there any point in allowing more than one retry?
1206 * Don't see one at the moment, but easy to change the
1209 if (!FILE_POSSIBLY_DELETED(errno) ||
1212 (errcode_for_file_access(),
1213 errmsg("could not fsync file \"%s\": %m",
1217 (errcode_for_file_access(),
1218 errmsg("could not fsync file \"%s\" but retrying: %m",
1223 * Absorb incoming requests and check to see if a cancel
1224 * arrived for this relation fork.
1226 AbsorbFsyncRequests();
1227 absorb_counter = FSYNCS_PER_ABSORB; /* might as well... */
1229 if (entry->canceled[forknum])
1231 } /* end retry loop */
1237 * We've finished everything that was requested before we started to
1238 * scan the entry. If no new requests have been inserted meanwhile,
1239 * remove the entry. Otherwise, update its cycle counter, as all the
1240 * requests now in it must have arrived during this cycle.
1242 for (forknum = 0; forknum <= MAX_FORKNUM; forknum++)
1244 if (entry->requests[forknum] != NULL)
1247 if (forknum <= MAX_FORKNUM)
1248 entry->cycle_ctr = mdsync_cycle_ctr;
1251 /* Okay to remove it */
1252 if (hash_search(pendingOpsTable, &entry->rnode,
1253 HASH_REMOVE, NULL) == NULL)
1254 elog(ERROR, "pendingOpsTable corrupted");
1256 } /* end loop over hashtable entries */
1258 /* Return sync performance metrics for report at checkpoint end */
1259 CheckpointStats.ckpt_sync_rels = processed;
1260 CheckpointStats.ckpt_longest_sync = longest;
1261 CheckpointStats.ckpt_agg_sync_time = total_elapsed;
1263 /* Flag successful completion of mdsync */
1264 mdsync_in_progress = false;
1268 * mdpreckpt() -- Do pre-checkpoint work
1270 * To distinguish unlink requests that arrived before this checkpoint
1271 * started from those that arrived during the checkpoint, we use a cycle
1272 * counter similar to the one we use for fsync requests. That cycle
1273 * counter is incremented here.
1275 * This must be called *before* the checkpoint REDO point is determined.
1276 * That ensures that we won't delete files too soon.
1278 * Note that we can't do anything here that depends on the assumption
1279 * that the checkpoint will be completed.
1285 * Any unlink requests arriving after this point will be assigned the next
1286 * cycle counter, and won't be unlinked until next checkpoint.
1292 * mdpostckpt() -- Do post-checkpoint work
1294 * Remove any lingering files that can now be safely removed.
1301 absorb_counter = UNLINKS_PER_ABSORB;
1302 while (pendingUnlinks != NIL)
1304 PendingUnlinkEntry *entry = (PendingUnlinkEntry *) linitial(pendingUnlinks);
1308 * New entries are appended to the end, so if the entry is new we've
1309 * reached the end of old entries.
1311 * Note: if just the right number of consecutive checkpoints fail, we
1312 * could be fooled here by cycle_ctr wraparound. However, the only
1313 * consequence is that we'd delay unlinking for one more checkpoint,
1314 * which is perfectly tolerable.
1316 if (entry->cycle_ctr == mdckpt_cycle_ctr)
1319 /* Unlink the file */
1320 path = relpathperm(entry->rnode, MAIN_FORKNUM);
1321 if (unlink(path) < 0)
1324 * There's a race condition, when the database is dropped at the
1325 * same time that we process the pending unlink requests. If the
1326 * DROP DATABASE deletes the file before we do, we will get ENOENT
1327 * here. rmtree() also has to ignore ENOENT errors, to deal with
1328 * the possibility that we delete the file first.
1330 if (errno != ENOENT)
1332 (errcode_for_file_access(),
1333 errmsg("could not remove file \"%s\": %m", path)));
1337 /* And remove the list entry */
1338 pendingUnlinks = list_delete_first(pendingUnlinks);
1342 * As in mdsync, we don't want to stop absorbing fsync requests for a
1343 * long time when there are many deletions to be done. We can safely
1344 * call AbsorbFsyncRequests() at this point in the loop (note it might
1345 * try to delete list entries).
1347 if (--absorb_counter <= 0)
1349 AbsorbFsyncRequests();
1350 absorb_counter = UNLINKS_PER_ABSORB;
1356 * register_dirty_segment() -- Mark a relation segment as needing fsync
1358 * If there is a local pending-ops table, just make an entry in it for
1359 * mdsync to process later. Otherwise, try to pass off the fsync request
1360 * to the checkpointer process. If that fails, just do the fsync
1361 * locally before returning (we hope this will not happen often enough
1362 * to be a performance problem).
1365 register_dirty_segment(SMgrRelation reln, ForkNumber forknum, MdfdVec *seg)
1367 /* Temp relations should never be fsync'd */
1368 Assert(!SmgrIsTemp(reln));
1370 if (pendingOpsTable)
1372 /* push it into local pending-ops table */
1373 RememberFsyncRequest(reln->smgr_rnode.node, forknum, seg->mdfd_segno);
1377 if (ForwardFsyncRequest(reln->smgr_rnode.node, forknum, seg->mdfd_segno))
1378 return; /* passed it off successfully */
1381 (errmsg("could not forward fsync request because request queue is full")));
1383 if (FileSync(seg->mdfd_vfd) < 0)
1385 (errcode_for_file_access(),
1386 errmsg("could not fsync file \"%s\": %m",
1387 FilePathName(seg->mdfd_vfd))));
1392 * register_unlink() -- Schedule a file to be deleted after next checkpoint
1394 * We don't bother passing in the fork number, because this is only used
1397 * As with register_dirty_segment, this could involve either a local or
1398 * a remote pending-ops table.
1401 register_unlink(RelFileNodeBackend rnode)
1403 /* Should never be used with temp relations */
1404 Assert(!RelFileNodeBackendIsTemp(rnode));
1406 if (pendingOpsTable)
1408 /* push it into local pending-ops table */
1409 RememberFsyncRequest(rnode.node, MAIN_FORKNUM,
1410 UNLINK_RELATION_REQUEST);
1415 * Notify the checkpointer about it. If we fail to queue the request
1416 * message, we have to sleep and try again, because we can't simply
1417 * delete the file now. Ugly, but hopefully won't happen often.
1419 * XXX should we just leave the file orphaned instead?
1421 Assert(IsUnderPostmaster);
1422 while (!ForwardFsyncRequest(rnode.node, MAIN_FORKNUM,
1423 UNLINK_RELATION_REQUEST))
1424 pg_usleep(10000L); /* 10 msec seems a good number */
1429 * RememberFsyncRequest() -- callback from checkpointer side of fsync request
1431 * We stuff fsync requests into the local hash table for execution
1432 * during the checkpointer's next checkpoint. UNLINK requests go into a
1433 * separate linked list, however, because they get processed separately.
1435 * The range of possible segment numbers is way less than the range of
1436 * BlockNumber, so we can reserve high values of segno for special purposes.
1438 * - FORGET_RELATION_FSYNC means to cancel pending fsyncs for a relation,
1439 * either for one fork, or all forks if forknum is InvalidForkNumber
1440 * - FORGET_DATABASE_FSYNC means to cancel pending fsyncs for a whole database
1441 * - UNLINK_RELATION_REQUEST is a request to delete the file after the next
1443 * Note also that we're assuming real segment numbers don't exceed INT_MAX.
1445 * (Handling FORGET_DATABASE_FSYNC requests is a tad slow because the hash
1446 * table has to be searched linearly, but dropping a database is a pretty
1447 * heavyweight operation anyhow, so we'll live with it.)
1450 RememberFsyncRequest(RelFileNode rnode, ForkNumber forknum, BlockNumber segno)
1452 Assert(pendingOpsTable);
1454 if (segno == FORGET_RELATION_FSYNC)
1456 /* Remove any pending requests for the relation (one or all forks) */
1457 PendingOperationEntry *entry;
1459 entry = (PendingOperationEntry *) hash_search(pendingOpsTable,
1466 * We can't just delete the entry since mdsync could have an
1467 * active hashtable scan. Instead we delete the bitmapsets; this
1468 * is safe because of the way mdsync is coded. We also set the
1469 * "canceled" flags so that mdsync can tell that a cancel arrived
1472 if (forknum == InvalidForkNumber)
1474 /* remove requests for all forks */
1475 for (forknum = 0; forknum <= MAX_FORKNUM; forknum++)
1477 bms_free(entry->requests[forknum]);
1478 entry->requests[forknum] = NULL;
1479 entry->canceled[forknum] = true;
1484 /* remove requests for single fork */
1485 bms_free(entry->requests[forknum]);
1486 entry->requests[forknum] = NULL;
1487 entry->canceled[forknum] = true;
1491 else if (segno == FORGET_DATABASE_FSYNC)
1493 /* Remove any pending requests for the entire database */
1494 HASH_SEQ_STATUS hstat;
1495 PendingOperationEntry *entry;
1500 /* Remove fsync requests */
1501 hash_seq_init(&hstat, pendingOpsTable);
1502 while ((entry = (PendingOperationEntry *) hash_seq_search(&hstat)) != NULL)
1504 if (entry->rnode.dbNode == rnode.dbNode)
1506 /* remove requests for all forks */
1507 for (forknum = 0; forknum <= MAX_FORKNUM; forknum++)
1509 bms_free(entry->requests[forknum]);
1510 entry->requests[forknum] = NULL;
1511 entry->canceled[forknum] = true;
1516 /* Remove unlink requests */
1518 for (cell = list_head(pendingUnlinks); cell; cell = next)
1520 PendingUnlinkEntry *entry = (PendingUnlinkEntry *) lfirst(cell);
1523 if (entry->rnode.dbNode == rnode.dbNode)
1525 pendingUnlinks = list_delete_cell(pendingUnlinks, cell, prev);
1532 else if (segno == UNLINK_RELATION_REQUEST)
1534 /* Unlink request: put it in the linked list */
1535 MemoryContext oldcxt = MemoryContextSwitchTo(pendingOpsCxt);
1536 PendingUnlinkEntry *entry;
1538 /* PendingUnlinkEntry doesn't store forknum, since it's always MAIN */
1539 Assert(forknum == MAIN_FORKNUM);
1541 entry = palloc(sizeof(PendingUnlinkEntry));
1542 entry->rnode = rnode;
1543 entry->cycle_ctr = mdckpt_cycle_ctr;
1545 pendingUnlinks = lappend(pendingUnlinks, entry);
1547 MemoryContextSwitchTo(oldcxt);
1551 /* Normal case: enter a request to fsync this segment */
1552 MemoryContext oldcxt = MemoryContextSwitchTo(pendingOpsCxt);
1553 PendingOperationEntry *entry;
1556 entry = (PendingOperationEntry *) hash_search(pendingOpsTable,
1560 /* if new entry, initialize it */
1563 entry->cycle_ctr = mdsync_cycle_ctr;
1564 MemSet(entry->requests, 0, sizeof(entry->requests));
1565 MemSet(entry->canceled, 0, sizeof(entry->canceled));
1569 * NB: it's intentional that we don't change cycle_ctr if the entry
1570 * already exists. The cycle_ctr must represent the oldest fsync
1571 * request that could be in the entry.
1574 entry->requests[forknum] = bms_add_member(entry->requests[forknum],
1577 MemoryContextSwitchTo(oldcxt);
1582 * ForgetRelationFsyncRequests -- forget any fsyncs for a relation fork
1584 * forknum == InvalidForkNumber means all forks, although this code doesn't
1585 * actually know that, since it's just forwarding the request elsewhere.
1588 ForgetRelationFsyncRequests(RelFileNode rnode, ForkNumber forknum)
1590 if (pendingOpsTable)
1592 /* standalone backend or startup process: fsync state is local */
1593 RememberFsyncRequest(rnode, forknum, FORGET_RELATION_FSYNC);
1595 else if (IsUnderPostmaster)
1598 * Notify the checkpointer about it. If we fail to queue the cancel
1599 * message, we have to sleep and try again ... ugly, but hopefully
1600 * won't happen often.
1602 * XXX should we CHECK_FOR_INTERRUPTS in this loop? Escaping with an
1603 * error would leave the no-longer-used file still present on disk,
1604 * which would be bad, so I'm inclined to assume that the checkpointer
1605 * will always empty the queue soon.
1607 while (!ForwardFsyncRequest(rnode, forknum, FORGET_RELATION_FSYNC))
1608 pg_usleep(10000L); /* 10 msec seems a good number */
1611 * Note we don't wait for the checkpointer to actually absorb the
1612 * cancel message; see mdsync() for the implications.
1618 * ForgetDatabaseFsyncRequests -- forget any fsyncs and unlinks for a DB
1621 ForgetDatabaseFsyncRequests(Oid dbid)
1625 rnode.dbNode = dbid;
1629 if (pendingOpsTable)
1631 /* standalone backend or startup process: fsync state is local */
1632 RememberFsyncRequest(rnode, InvalidForkNumber, FORGET_DATABASE_FSYNC);
1634 else if (IsUnderPostmaster)
1636 /* see notes in ForgetRelationFsyncRequests */
1637 while (!ForwardFsyncRequest(rnode, InvalidForkNumber,
1638 FORGET_DATABASE_FSYNC))
1639 pg_usleep(10000L); /* 10 msec seems a good number */
1645 * _fdvec_alloc() -- Make a MdfdVec object.
1650 return (MdfdVec *) MemoryContextAlloc(MdCxt, sizeof(MdfdVec));
1654 * Return the filename for the specified segment of the relation. The
1655 * returned string is palloc'd.
1658 _mdfd_segpath(SMgrRelation reln, ForkNumber forknum, BlockNumber segno)
1663 path = relpath(reln->smgr_rnode, forknum);
1667 fullpath = psprintf("%s.%u", path, segno);
1677 * Open the specified segment of the relation,
1678 * and make a MdfdVec object for it. Returns NULL on failure.
1681 _mdfd_openseg(SMgrRelation reln, ForkNumber forknum, BlockNumber segno,
1688 fullpath = _mdfd_segpath(reln, forknum, segno);
1691 fd = PathNameOpenFile(fullpath, O_RDWR | PG_BINARY | oflags, 0600);
1698 /* allocate an mdfdvec entry for it */
1701 /* fill the entry */
1703 v->mdfd_segno = segno;
1704 v->mdfd_chain = NULL;
1705 Assert(_mdnblocks(reln, forknum, v) <= ((BlockNumber) RELSEG_SIZE));
1712 * _mdfd_getseg() -- Find the segment of the relation holding the
1715 * If the segment doesn't exist, we ereport, return NULL, or create the
1716 * segment, according to "behavior". Note: skipFsync is only used in the
1717 * EXTENSION_CREATE case.
1720 _mdfd_getseg(SMgrRelation reln, ForkNumber forknum, BlockNumber blkno,
1721 bool skipFsync, ExtensionBehavior behavior)
1723 MdfdVec *v = mdopen(reln, forknum, behavior);
1724 BlockNumber targetseg;
1725 BlockNumber nextsegno;
1728 return NULL; /* only possible if EXTENSION_RETURN_NULL */
1730 targetseg = blkno / ((BlockNumber) RELSEG_SIZE);
1731 for (nextsegno = 1; nextsegno <= targetseg; nextsegno++)
1733 Assert(nextsegno == v->mdfd_segno + 1);
1735 if (v->mdfd_chain == NULL)
1738 * Normally we will create new segments only if authorized by the
1739 * caller (i.e., we are doing mdextend()). But when doing WAL
1740 * recovery, create segments anyway; this allows cases such as
1741 * replaying WAL data that has a write into a high-numbered
1742 * segment of a relation that was later deleted. We want to go
1743 * ahead and create the segments so we can finish out the replay.
1745 * We have to maintain the invariant that segments before the last
1746 * active segment are of size RELSEG_SIZE; therefore, pad them out
1747 * with zeroes if needed. (This only matters if caller is
1748 * extending the relation discontiguously, but that can happen in
1751 if (behavior == EXTENSION_CREATE || InRecovery)
1753 if (_mdnblocks(reln, forknum, v) < RELSEG_SIZE)
1755 char *zerobuf = palloc0(BLCKSZ);
1757 mdextend(reln, forknum,
1758 nextsegno * ((BlockNumber) RELSEG_SIZE) - 1,
1759 zerobuf, skipFsync);
1762 v->mdfd_chain = _mdfd_openseg(reln, forknum, +nextsegno, O_CREAT);
1766 /* We won't create segment if not existent */
1767 v->mdfd_chain = _mdfd_openseg(reln, forknum, nextsegno, 0);
1769 if (v->mdfd_chain == NULL)
1771 if (behavior == EXTENSION_RETURN_NULL &&
1772 FILE_POSSIBLY_DELETED(errno))
1775 (errcode_for_file_access(),
1776 errmsg("could not open file \"%s\" (target block %u): %m",
1777 _mdfd_segpath(reln, forknum, nextsegno),
1787 * Get number of blocks present in a single disk file
1790 _mdnblocks(SMgrRelation reln, ForkNumber forknum, MdfdVec *seg)
1794 len = FileSeek(seg->mdfd_vfd, 0L, SEEK_END);
1797 (errcode_for_file_access(),
1798 errmsg("could not seek to end of file \"%s\": %m",
1799 FilePathName(seg->mdfd_vfd))));
1800 /* note that this calculation will ignore any partial block at EOF */
1801 return (BlockNumber) (len / BLCKSZ);