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-2018, 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"
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 * File descriptors are stored in the per-fork md_seg_fds arrays inside
96 * SMgrRelation. The length of these arrays is stored in md_num_open_segs.
97 * Note that a fork's md_num_open_segs having a specific value does not
98 * necessarily mean the relation doesn't have additional segments; we may
99 * just not have opened the next segment yet. (We could not have "all
100 * segments are in the array" as an invariant anyway, since another backend
101 * could extend the relation while we aren't looking.) We do not have
102 * entries for inactive segments, however; as soon as we find a partial
103 * segment, we assume that any subsequent segments are inactive.
105 * The entire MdfdVec array is palloc'd in the MdCxt memory context.
108 typedef struct _MdfdVec
110 File mdfd_vfd; /* fd number in fd.c's pool */
111 BlockNumber mdfd_segno; /* segment number, from 0 */
114 static MemoryContext MdCxt; /* context for all MdfdVec objects */
118 * In some contexts (currently, standalone backends and the checkpointer)
119 * we keep track of pending fsync operations: we need to remember all relation
120 * segments that have been written since the last checkpoint, so that we can
121 * fsync them down to disk before completing the next checkpoint. This hash
122 * table remembers the pending operations. We use a hash table mostly as
123 * a convenient way of merging duplicate requests.
125 * We use a similar mechanism to remember no-longer-needed files that can
126 * be deleted after the next checkpoint, but we use a linked list instead of
127 * a hash table, because we don't expect there to be any duplicate requests.
129 * These mechanisms are only used for non-temp relations; we never fsync
130 * temp rels, nor do we need to postpone their deletion (see comments in
133 * (Regular backends do not track pending operations locally, but forward
134 * them to the checkpointer.)
136 typedef uint16 CycleCtr; /* can be any convenient integer size */
140 RelFileNode rnode; /* hash table key (must be first!) */
141 CycleCtr cycle_ctr; /* mdsync_cycle_ctr of oldest request */
142 /* requests[f] has bit n set if we need to fsync segment n of fork f */
143 Bitmapset *requests[MAX_FORKNUM + 1];
144 /* canceled[f] is true if we canceled fsyncs for fork "recently" */
145 bool canceled[MAX_FORKNUM + 1];
146 } PendingOperationEntry;
150 RelFileNode rnode; /* the dead relation to delete */
151 CycleCtr cycle_ctr; /* mdckpt_cycle_ctr when request was made */
152 } PendingUnlinkEntry;
154 static HTAB *pendingOpsTable = NULL;
155 static List *pendingUnlinks = NIL;
156 static MemoryContext pendingOpsCxt; /* context for the above */
158 static CycleCtr mdsync_cycle_ctr = 0;
159 static CycleCtr mdckpt_cycle_ctr = 0;
162 /*** behavior for mdopen & _mdfd_getseg ***/
163 /* ereport if segment not present */
164 #define EXTENSION_FAIL (1 << 0)
165 /* return NULL if segment not present */
166 #define EXTENSION_RETURN_NULL (1 << 1)
167 /* create new segments as needed */
168 #define EXTENSION_CREATE (1 << 2)
169 /* create new segments if needed during recovery */
170 #define EXTENSION_CREATE_RECOVERY (1 << 3)
172 * Allow opening segments which are preceded by segments smaller than
173 * RELSEG_SIZE, e.g. inactive segments (see above). Note that this is breaks
174 * mdnblocks() and related functionality henceforth - which currently is ok,
175 * because this is only required in the checkpointer which never uses
178 #define EXTENSION_DONT_CHECK_SIZE (1 << 4)
182 static void mdunlinkfork(RelFileNodeBackend rnode, ForkNumber forkNum,
184 static MdfdVec *mdopen(SMgrRelation reln, ForkNumber forknum, int behavior);
185 static void register_dirty_segment(SMgrRelation reln, ForkNumber forknum,
187 static void register_unlink(RelFileNodeBackend rnode);
188 static void _fdvec_resize(SMgrRelation reln,
191 static char *_mdfd_segpath(SMgrRelation reln, ForkNumber forknum,
193 static MdfdVec *_mdfd_openseg(SMgrRelation reln, ForkNumber forkno,
194 BlockNumber segno, int oflags);
195 static MdfdVec *_mdfd_getseg(SMgrRelation reln, ForkNumber forkno,
196 BlockNumber blkno, bool skipFsync, int behavior);
197 static BlockNumber _mdnblocks(SMgrRelation reln, ForkNumber forknum,
202 * mdinit() -- Initialize private state for magnetic disk storage manager.
207 MdCxt = AllocSetContextCreate(TopMemoryContext,
209 ALLOCSET_DEFAULT_SIZES);
212 * Create pending-operations hashtable if we need it. Currently, we need
213 * it if we are standalone (not under a postmaster) or if we are a startup
214 * or checkpointer auxiliary process.
216 if (!IsUnderPostmaster || AmStartupProcess() || AmCheckpointerProcess())
221 * XXX: The checkpointer needs to add entries to the pending ops table
222 * when absorbing fsync requests. That is done within a critical
223 * section, which isn't usually allowed, but we make an exception. It
224 * means that there's a theoretical possibility that you run out of
225 * memory while absorbing fsync requests, which leads to a PANIC.
226 * Fortunately the hash table is small so that's unlikely to happen in
229 pendingOpsCxt = AllocSetContextCreate(MdCxt,
230 "Pending ops context",
231 ALLOCSET_DEFAULT_SIZES);
232 MemoryContextAllowInCriticalSection(pendingOpsCxt, true);
234 MemSet(&hash_ctl, 0, sizeof(hash_ctl));
235 hash_ctl.keysize = sizeof(RelFileNode);
236 hash_ctl.entrysize = sizeof(PendingOperationEntry);
237 hash_ctl.hcxt = pendingOpsCxt;
238 pendingOpsTable = hash_create("Pending Ops Table",
241 HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
242 pendingUnlinks = NIL;
247 * In archive recovery, we rely on checkpointer to do fsyncs, but we will have
248 * already created the pendingOpsTable during initialization of the startup
249 * process. Calling this function drops the local pendingOpsTable so that
250 * subsequent requests will be forwarded to checkpointer.
253 SetForwardFsyncRequests(void)
255 /* Perform any pending fsyncs we may have queued up, then drop table */
259 hash_destroy(pendingOpsTable);
261 pendingOpsTable = NULL;
264 * We should not have any pending unlink requests, since mdunlink doesn't
265 * queue unlink requests when isRedo.
267 Assert(pendingUnlinks == NIL);
271 * mdexists() -- Does the physical file exist?
273 * Note: this will return true for lingering files, with pending deletions
276 mdexists(SMgrRelation reln, ForkNumber forkNum)
279 * Close it first, to ensure that we notice if the fork has been unlinked
280 * since we opened it.
282 mdclose(reln, forkNum);
284 return (mdopen(reln, forkNum, EXTENSION_RETURN_NULL) != NULL);
288 * mdcreate() -- Create a new relation on magnetic disk.
290 * If isRedo is true, it's okay for the relation to exist already.
293 mdcreate(SMgrRelation reln, ForkNumber forkNum, bool isRedo)
299 if (isRedo && reln->md_num_open_segs[forkNum] > 0)
300 return; /* created and opened already... */
302 Assert(reln->md_num_open_segs[forkNum] == 0);
304 path = relpath(reln->smgr_rnode, forkNum);
306 fd = PathNameOpenFile(path, O_RDWR | O_CREAT | O_EXCL | PG_BINARY);
310 int save_errno = errno;
313 * During bootstrap, there are cases where a system relation will be
314 * accessed (by internal backend processes) before the bootstrap
315 * script nominally creates it. Therefore, allow the file to exist
316 * already, even if isRedo is not set. (See also mdopen)
318 if (isRedo || IsBootstrapProcessingMode())
319 fd = PathNameOpenFile(path, O_RDWR | PG_BINARY);
322 /* be sure to report the error reported by create, not open */
325 (errcode_for_file_access(),
326 errmsg("could not create file \"%s\": %m", path)));
332 _fdvec_resize(reln, forkNum, 1);
333 mdfd = &reln->md_seg_fds[forkNum][0];
335 mdfd->mdfd_segno = 0;
339 * mdunlink() -- Unlink a relation.
341 * Note that we're passed a RelFileNodeBackend --- by the time this is called,
342 * there won't be an SMgrRelation hashtable entry anymore.
344 * forkNum can be a fork number to delete a specific fork, or InvalidForkNumber
345 * to delete all forks.
347 * For regular relations, we don't unlink the first segment file of the rel,
348 * but just truncate it to zero length, and record a request to unlink it after
349 * the next checkpoint. Additional segments can be unlinked immediately,
350 * however. Leaving the empty file in place prevents that relfilenode
351 * number from being reused. The scenario this protects us from is:
352 * 1. We delete a relation (and commit, and actually remove its file).
353 * 2. We create a new relation, which by chance gets the same relfilenode as
354 * the just-deleted one (OIDs must've wrapped around for that to happen).
355 * 3. We crash before another checkpoint occurs.
356 * During replay, we would delete the file and then recreate it, which is fine
357 * if the contents of the file were repopulated by subsequent WAL entries.
358 * But if we didn't WAL-log insertions, but instead relied on fsyncing the
359 * file after populating it (as for instance CLUSTER and CREATE INDEX do),
360 * the contents of the file would be lost forever. By leaving the empty file
361 * until after the next checkpoint, we prevent reassignment of the relfilenode
362 * number until it's safe, because relfilenode assignment skips over any
365 * We do not need to go through this dance for temp relations, though, because
366 * we never make WAL entries for temp rels, and so a temp rel poses no threat
367 * to the health of a regular rel that has taken over its relfilenode number.
368 * The fact that temp rels and regular rels have different file naming
369 * patterns provides additional safety.
371 * All the above applies only to the relation's main fork; other forks can
372 * just be removed immediately, since they are not needed to prevent the
373 * relfilenode number from being recycled. Also, we do not carefully
374 * track whether other forks have been created or not, but just attempt to
375 * unlink them unconditionally; so we should never complain about ENOENT.
377 * If isRedo is true, it's unsurprising for the relation to be already gone.
378 * Also, we should remove the file immediately instead of queuing a request
379 * for later, since during redo there's no possibility of creating a
380 * conflicting relation.
382 * Note: any failure should be reported as WARNING not ERROR, because
383 * we are usually not in a transaction anymore when this is called.
386 mdunlink(RelFileNodeBackend rnode, ForkNumber forkNum, bool isRedo)
389 * We have to clean out any pending fsync requests for the doomed
390 * relation, else the next mdsync() will fail. There can't be any such
391 * requests for a temp relation, though. We can send just one request
392 * even when deleting multiple forks, since the fsync queuing code accepts
393 * the "InvalidForkNumber = all forks" convention.
395 if (!RelFileNodeBackendIsTemp(rnode))
396 ForgetRelationFsyncRequests(rnode.node, forkNum);
398 /* Now do the per-fork work */
399 if (forkNum == InvalidForkNumber)
401 for (forkNum = 0; forkNum <= MAX_FORKNUM; forkNum++)
402 mdunlinkfork(rnode, forkNum, isRedo);
405 mdunlinkfork(rnode, forkNum, isRedo);
409 mdunlinkfork(RelFileNodeBackend rnode, ForkNumber forkNum, bool isRedo)
414 path = relpath(rnode, forkNum);
417 * Delete or truncate the first segment.
419 if (isRedo || forkNum != MAIN_FORKNUM || RelFileNodeBackendIsTemp(rnode))
422 if (ret < 0 && errno != ENOENT)
424 (errcode_for_file_access(),
425 errmsg("could not remove file \"%s\": %m", path)));
429 /* truncate(2) would be easier here, but Windows hasn't got it */
432 fd = OpenTransientFile(path, O_RDWR | PG_BINARY);
437 ret = ftruncate(fd, 0);
439 CloseTransientFile(fd);
444 if (ret < 0 && errno != ENOENT)
446 (errcode_for_file_access(),
447 errmsg("could not truncate file \"%s\": %m", path)));
449 /* Register request to unlink first segment later */
450 register_unlink(rnode);
454 * Delete any additional segments.
458 char *segpath = (char *) palloc(strlen(path) + 12);
462 * Note that because we loop until getting ENOENT, we will correctly
463 * remove all inactive segments as well as active ones.
465 for (segno = 1;; segno++)
467 sprintf(segpath, "%s.%u", path, segno);
468 if (unlink(segpath) < 0)
470 /* ENOENT is expected after the last segment... */
473 (errcode_for_file_access(),
474 errmsg("could not remove file \"%s\": %m", segpath)));
485 * mdextend() -- Add a block to the specified relation.
487 * The semantics are nearly the same as mdwrite(): write at the
488 * specified position. However, this is to be used for the case of
489 * extending a relation (i.e., blocknum is at or beyond the current
490 * EOF). Note that we assume writing a block beyond current EOF
491 * causes intervening file space to become filled with zeroes.
494 mdextend(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum,
495 char *buffer, bool skipFsync)
501 /* This assert is too expensive to have on normally ... */
502 #ifdef CHECK_WRITE_VS_EXTEND
503 Assert(blocknum >= mdnblocks(reln, forknum));
507 * If a relation manages to grow to 2^32-1 blocks, refuse to extend it any
508 * more --- we mustn't create a block whose number actually is
509 * InvalidBlockNumber.
511 if (blocknum == InvalidBlockNumber)
513 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
514 errmsg("cannot extend file \"%s\" beyond %u blocks",
515 relpath(reln->smgr_rnode, forknum),
516 InvalidBlockNumber)));
518 v = _mdfd_getseg(reln, forknum, blocknum, skipFsync, EXTENSION_CREATE);
520 seekpos = (off_t) BLCKSZ * (blocknum % ((BlockNumber) RELSEG_SIZE));
522 Assert(seekpos < (off_t) BLCKSZ * RELSEG_SIZE);
525 * Note: because caller usually obtained blocknum by calling mdnblocks,
526 * which did a seek(SEEK_END), this seek is often redundant and will be
527 * optimized away by fd.c. It's not redundant, however, if there is a
528 * partial page at the end of the file. In that case we want to try to
529 * overwrite the partial page with a full page. It's also not redundant
530 * if bufmgr.c had to dump another buffer of the same file to make room
531 * for the new page's buffer.
533 if (FileSeek(v->mdfd_vfd, seekpos, SEEK_SET) != seekpos)
535 (errcode_for_file_access(),
536 errmsg("could not seek to block %u in file \"%s\": %m",
537 blocknum, FilePathName(v->mdfd_vfd))));
539 if ((nbytes = FileWrite(v->mdfd_vfd, buffer, BLCKSZ, WAIT_EVENT_DATA_FILE_EXTEND)) != BLCKSZ)
543 (errcode_for_file_access(),
544 errmsg("could not extend file \"%s\": %m",
545 FilePathName(v->mdfd_vfd)),
546 errhint("Check free disk space.")));
547 /* short write: complain appropriately */
549 (errcode(ERRCODE_DISK_FULL),
550 errmsg("could not extend file \"%s\": wrote only %d of %d bytes at block %u",
551 FilePathName(v->mdfd_vfd),
552 nbytes, BLCKSZ, blocknum),
553 errhint("Check free disk space.")));
556 if (!skipFsync && !SmgrIsTemp(reln))
557 register_dirty_segment(reln, forknum, v);
559 Assert(_mdnblocks(reln, forknum, v) <= ((BlockNumber) RELSEG_SIZE));
563 * mdopen() -- Open the specified relation.
565 * Note we only open the first segment, when there are multiple segments.
567 * If first segment is not present, either ereport or return NULL according
568 * to "behavior". We treat EXTENSION_CREATE the same as EXTENSION_FAIL;
569 * EXTENSION_CREATE means it's OK to extend an existing relation, not to
570 * invent one out of whole cloth.
573 mdopen(SMgrRelation reln, ForkNumber forknum, int behavior)
579 /* No work if already open */
580 if (reln->md_num_open_segs[forknum] > 0)
581 return &reln->md_seg_fds[forknum][0];
583 path = relpath(reln->smgr_rnode, forknum);
585 fd = PathNameOpenFile(path, O_RDWR | PG_BINARY);
590 * During bootstrap, there are cases where a system relation will be
591 * accessed (by internal backend processes) before the bootstrap
592 * script nominally creates it. Therefore, accept mdopen() as a
593 * substitute for mdcreate() in bootstrap mode only. (See mdcreate)
595 if (IsBootstrapProcessingMode())
596 fd = PathNameOpenFile(path, O_RDWR | O_CREAT | O_EXCL | PG_BINARY);
599 if ((behavior & EXTENSION_RETURN_NULL) &&
600 FILE_POSSIBLY_DELETED(errno))
606 (errcode_for_file_access(),
607 errmsg("could not open file \"%s\": %m", path)));
613 _fdvec_resize(reln, forknum, 1);
614 mdfd = &reln->md_seg_fds[forknum][0];
616 mdfd->mdfd_segno = 0;
618 Assert(_mdnblocks(reln, forknum, mdfd) <= ((BlockNumber) RELSEG_SIZE));
624 * mdclose() -- Close the specified relation, if it isn't closed already.
627 mdclose(SMgrRelation reln, ForkNumber forknum)
629 int nopensegs = reln->md_num_open_segs[forknum];
631 /* No work if already closed */
635 /* close segments starting from the end */
636 while (nopensegs > 0)
638 MdfdVec *v = &reln->md_seg_fds[forknum][nopensegs - 1];
640 /* if not closed already */
641 if (v->mdfd_vfd >= 0)
643 FileClose(v->mdfd_vfd);
650 /* resize just once, avoids pointless reallocations */
651 _fdvec_resize(reln, forknum, 0);
655 * mdprefetch() -- Initiate asynchronous read of the specified block of a relation
658 mdprefetch(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum)
664 v = _mdfd_getseg(reln, forknum, blocknum, false, EXTENSION_FAIL);
666 seekpos = (off_t) BLCKSZ * (blocknum % ((BlockNumber) RELSEG_SIZE));
668 Assert(seekpos < (off_t) BLCKSZ * RELSEG_SIZE);
670 (void) FilePrefetch(v->mdfd_vfd, seekpos, BLCKSZ, WAIT_EVENT_DATA_FILE_PREFETCH);
671 #endif /* USE_PREFETCH */
675 * mdwriteback() -- Tell the kernel to write pages back to storage.
677 * This accepts a range of blocks because flushing several pages at once is
678 * considerably more efficient than doing so individually.
681 mdwriteback(SMgrRelation reln, ForkNumber forknum,
682 BlockNumber blocknum, BlockNumber nblocks)
685 * Issue flush requests in as few requests as possible; have to split at
686 * segment boundaries though, since those are actually separate files.
690 BlockNumber nflush = nblocks;
696 v = _mdfd_getseg(reln, forknum, blocknum, true /* not used */ ,
697 EXTENSION_RETURN_NULL);
700 * We might be flushing buffers of already removed relations, that's
701 * ok, just ignore that case.
706 /* compute offset inside the current segment */
707 segnum_start = blocknum / RELSEG_SIZE;
709 /* compute number of desired writes within the current segment */
710 segnum_end = (blocknum + nblocks - 1) / RELSEG_SIZE;
711 if (segnum_start != segnum_end)
712 nflush = RELSEG_SIZE - (blocknum % ((BlockNumber) RELSEG_SIZE));
715 Assert(nflush <= nblocks);
717 seekpos = (off_t) BLCKSZ * (blocknum % ((BlockNumber) RELSEG_SIZE));
719 FileWriteback(v->mdfd_vfd, seekpos, (off_t) BLCKSZ * nflush, WAIT_EVENT_DATA_FILE_FLUSH);
727 * mdread() -- Read the specified block from a relation.
730 mdread(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum,
737 TRACE_POSTGRESQL_SMGR_MD_READ_START(forknum, blocknum,
738 reln->smgr_rnode.node.spcNode,
739 reln->smgr_rnode.node.dbNode,
740 reln->smgr_rnode.node.relNode,
741 reln->smgr_rnode.backend);
743 v = _mdfd_getseg(reln, forknum, blocknum, false,
744 EXTENSION_FAIL | EXTENSION_CREATE_RECOVERY);
746 seekpos = (off_t) BLCKSZ * (blocknum % ((BlockNumber) RELSEG_SIZE));
748 Assert(seekpos < (off_t) BLCKSZ * RELSEG_SIZE);
750 if (FileSeek(v->mdfd_vfd, seekpos, SEEK_SET) != seekpos)
752 (errcode_for_file_access(),
753 errmsg("could not seek to block %u in file \"%s\": %m",
754 blocknum, FilePathName(v->mdfd_vfd))));
756 nbytes = FileRead(v->mdfd_vfd, buffer, BLCKSZ, WAIT_EVENT_DATA_FILE_READ);
758 TRACE_POSTGRESQL_SMGR_MD_READ_DONE(forknum, blocknum,
759 reln->smgr_rnode.node.spcNode,
760 reln->smgr_rnode.node.dbNode,
761 reln->smgr_rnode.node.relNode,
762 reln->smgr_rnode.backend,
766 if (nbytes != BLCKSZ)
770 (errcode_for_file_access(),
771 errmsg("could not read block %u in file \"%s\": %m",
772 blocknum, FilePathName(v->mdfd_vfd))));
775 * Short read: we are at or past EOF, or we read a partial block at
776 * EOF. Normally this is an error; upper levels should never try to
777 * read a nonexistent block. However, if zero_damaged_pages is ON or
778 * we are InRecovery, we should instead return zeroes without
779 * complaining. This allows, for example, the case of trying to
780 * update a block that was later truncated away.
782 if (zero_damaged_pages || InRecovery)
783 MemSet(buffer, 0, BLCKSZ);
786 (errcode(ERRCODE_DATA_CORRUPTED),
787 errmsg("could not read block %u in file \"%s\": read only %d of %d bytes",
788 blocknum, FilePathName(v->mdfd_vfd),
794 * mdwrite() -- Write the supplied block at the appropriate location.
796 * This is to be used only for updating already-existing blocks of a
797 * relation (ie, those before the current EOF). To extend a relation,
801 mdwrite(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum,
802 char *buffer, bool skipFsync)
808 /* This assert is too expensive to have on normally ... */
809 #ifdef CHECK_WRITE_VS_EXTEND
810 Assert(blocknum < mdnblocks(reln, forknum));
813 TRACE_POSTGRESQL_SMGR_MD_WRITE_START(forknum, blocknum,
814 reln->smgr_rnode.node.spcNode,
815 reln->smgr_rnode.node.dbNode,
816 reln->smgr_rnode.node.relNode,
817 reln->smgr_rnode.backend);
819 v = _mdfd_getseg(reln, forknum, blocknum, skipFsync,
820 EXTENSION_FAIL | EXTENSION_CREATE_RECOVERY);
822 seekpos = (off_t) BLCKSZ * (blocknum % ((BlockNumber) RELSEG_SIZE));
824 Assert(seekpos < (off_t) BLCKSZ * RELSEG_SIZE);
826 if (FileSeek(v->mdfd_vfd, seekpos, SEEK_SET) != seekpos)
828 (errcode_for_file_access(),
829 errmsg("could not seek to block %u in file \"%s\": %m",
830 blocknum, FilePathName(v->mdfd_vfd))));
832 nbytes = FileWrite(v->mdfd_vfd, buffer, BLCKSZ, WAIT_EVENT_DATA_FILE_WRITE);
834 TRACE_POSTGRESQL_SMGR_MD_WRITE_DONE(forknum, blocknum,
835 reln->smgr_rnode.node.spcNode,
836 reln->smgr_rnode.node.dbNode,
837 reln->smgr_rnode.node.relNode,
838 reln->smgr_rnode.backend,
842 if (nbytes != BLCKSZ)
846 (errcode_for_file_access(),
847 errmsg("could not write block %u in file \"%s\": %m",
848 blocknum, FilePathName(v->mdfd_vfd))));
849 /* short write: complain appropriately */
851 (errcode(ERRCODE_DISK_FULL),
852 errmsg("could not write block %u in file \"%s\": wrote only %d of %d bytes",
854 FilePathName(v->mdfd_vfd),
856 errhint("Check free disk space.")));
859 if (!skipFsync && !SmgrIsTemp(reln))
860 register_dirty_segment(reln, forknum, v);
864 * mdnblocks() -- Get the number of blocks stored in a relation.
866 * Important side effect: all active segments of the relation are opened
867 * and added to the mdfd_seg_fds array. If this routine has not been
868 * called, then only segments up to the last one actually touched
869 * are present in the array.
872 mdnblocks(SMgrRelation reln, ForkNumber forknum)
874 MdfdVec *v = mdopen(reln, forknum, EXTENSION_FAIL);
876 BlockNumber segno = 0;
878 /* mdopen has opened the first segment */
879 Assert(reln->md_num_open_segs[forknum] > 0);
882 * Start from the last open segments, to avoid redundant seeks. We have
883 * previously verified that these segments are exactly RELSEG_SIZE long,
884 * and it's useless to recheck that each time.
886 * NOTE: this assumption could only be wrong if another backend has
887 * truncated the relation. We rely on higher code levels to handle that
888 * scenario by closing and re-opening the md fd, which is handled via
889 * relcache flush. (Since the checkpointer doesn't participate in
890 * relcache flush, it could have segment entries for inactive segments;
891 * that's OK because the checkpointer never needs to compute relation
894 segno = reln->md_num_open_segs[forknum] - 1;
895 v = &reln->md_seg_fds[forknum][segno];
899 nblocks = _mdnblocks(reln, forknum, v);
900 if (nblocks > ((BlockNumber) RELSEG_SIZE))
901 elog(FATAL, "segment too big");
902 if (nblocks < ((BlockNumber) RELSEG_SIZE))
903 return (segno * ((BlockNumber) RELSEG_SIZE)) + nblocks;
906 * If segment is exactly RELSEG_SIZE, advance to next one.
911 * We used to pass O_CREAT here, but that's has the disadvantage that
912 * it might create a segment which has vanished through some operating
913 * system misadventure. In such a case, creating the segment here
914 * undermines _mdfd_getseg's attempts to notice and report an error
915 * upon access to a missing segment.
917 v = _mdfd_openseg(reln, forknum, segno, 0);
919 return segno * ((BlockNumber) RELSEG_SIZE);
924 * mdtruncate() -- Truncate relation to specified number of blocks.
927 mdtruncate(SMgrRelation reln, ForkNumber forknum, BlockNumber nblocks)
930 BlockNumber priorblocks;
934 * NOTE: mdnblocks makes sure we have opened all active segments, so that
935 * truncation loop will get them all!
937 curnblk = mdnblocks(reln, forknum);
938 if (nblocks > curnblk)
940 /* Bogus request ... but no complaint if InRecovery */
944 (errmsg("could not truncate file \"%s\" to %u blocks: it's only %u blocks now",
945 relpath(reln->smgr_rnode, forknum),
948 if (nblocks == curnblk)
949 return; /* no work */
952 * Truncate segments, starting at the last one. Starting at the end makes
953 * managing the memory for the fd array easier, should there be errors.
955 curopensegs = reln->md_num_open_segs[forknum];
956 while (curopensegs > 0)
960 priorblocks = (curopensegs - 1) * RELSEG_SIZE;
962 v = &reln->md_seg_fds[forknum][curopensegs - 1];
964 if (priorblocks > nblocks)
967 * This segment is no longer active. We truncate the file, but do
968 * not delete it, for reasons explained in the header comments.
970 if (FileTruncate(v->mdfd_vfd, 0, WAIT_EVENT_DATA_FILE_TRUNCATE) < 0)
972 (errcode_for_file_access(),
973 errmsg("could not truncate file \"%s\": %m",
974 FilePathName(v->mdfd_vfd))));
976 if (!SmgrIsTemp(reln))
977 register_dirty_segment(reln, forknum, v);
979 /* we never drop the 1st segment */
980 Assert(v != &reln->md_seg_fds[forknum][0]);
982 FileClose(v->mdfd_vfd);
983 _fdvec_resize(reln, forknum, curopensegs - 1);
985 else if (priorblocks + ((BlockNumber) RELSEG_SIZE) > nblocks)
988 * This is the last segment we want to keep. Truncate the file to
989 * the right length. NOTE: if nblocks is exactly a multiple K of
990 * RELSEG_SIZE, we will truncate the K+1st segment to 0 length but
991 * keep it. This adheres to the invariant given in the header
994 BlockNumber lastsegblocks = nblocks - priorblocks;
996 if (FileTruncate(v->mdfd_vfd, (off_t) lastsegblocks * BLCKSZ, WAIT_EVENT_DATA_FILE_TRUNCATE) < 0)
998 (errcode_for_file_access(),
999 errmsg("could not truncate file \"%s\" to %u blocks: %m",
1000 FilePathName(v->mdfd_vfd),
1002 if (!SmgrIsTemp(reln))
1003 register_dirty_segment(reln, forknum, v);
1008 * We still need this segment, so nothing to do for this and any
1018 * mdimmedsync() -- Immediately sync a relation to stable storage.
1020 * Note that only writes already issued are synced; this routine knows
1021 * nothing of dirty buffers that may exist inside the buffer manager.
1024 mdimmedsync(SMgrRelation reln, ForkNumber forknum)
1029 * NOTE: mdnblocks makes sure we have opened all active segments, so that
1030 * fsync loop will get them all!
1032 mdnblocks(reln, forknum);
1034 segno = reln->md_num_open_segs[forknum];
1038 MdfdVec *v = &reln->md_seg_fds[forknum][segno - 1];
1040 if (FileSync(v->mdfd_vfd, WAIT_EVENT_DATA_FILE_IMMEDIATE_SYNC) < 0)
1042 (errcode_for_file_access(),
1043 errmsg("could not fsync file \"%s\": %m",
1044 FilePathName(v->mdfd_vfd))));
1050 * mdsync() -- Sync previous writes to stable storage.
1055 static bool mdsync_in_progress = false;
1057 HASH_SEQ_STATUS hstat;
1058 PendingOperationEntry *entry;
1061 /* Statistics on sync times */
1063 instr_time sync_start,
1068 uint64 total_elapsed = 0;
1071 * This is only called during checkpoints, and checkpoints should only
1072 * occur in processes that have created a pendingOpsTable.
1074 if (!pendingOpsTable)
1075 elog(ERROR, "cannot sync without a pendingOpsTable");
1078 * If we are in the checkpointer, the sync had better include all fsync
1079 * requests that were queued by backends up to this point. The tightest
1080 * race condition that could occur is that a buffer that must be written
1081 * and fsync'd for the checkpoint could have been dumped by a backend just
1082 * before it was visited by BufferSync(). We know the backend will have
1083 * queued an fsync request before clearing the buffer's dirtybit, so we
1084 * are safe as long as we do an Absorb after completing BufferSync().
1086 AbsorbFsyncRequests();
1089 * To avoid excess fsync'ing (in the worst case, maybe a never-terminating
1090 * checkpoint), we want to ignore fsync requests that are entered into the
1091 * hashtable after this point --- they should be processed next time,
1092 * instead. We use mdsync_cycle_ctr to tell old entries apart from new
1093 * ones: new ones will have cycle_ctr equal to the incremented value of
1096 * In normal circumstances, all entries present in the table at this point
1097 * will have cycle_ctr exactly equal to the current (about to be old)
1098 * value of mdsync_cycle_ctr. However, if we fail partway through the
1099 * fsync'ing loop, then older values of cycle_ctr might remain when we
1100 * come back here to try again. Repeated checkpoint failures would
1101 * eventually wrap the counter around to the point where an old entry
1102 * might appear new, causing us to skip it, possibly allowing a checkpoint
1103 * to succeed that should not have. To forestall wraparound, any time the
1104 * previous mdsync() failed to complete, run through the table and
1105 * forcibly set cycle_ctr = mdsync_cycle_ctr.
1107 * Think not to merge this loop with the main loop, as the problem is
1108 * exactly that that loop may fail before having visited all the entries.
1109 * From a performance point of view it doesn't matter anyway, as this path
1110 * will never be taken in a system that's functioning normally.
1112 if (mdsync_in_progress)
1114 /* prior try failed, so update any stale cycle_ctr values */
1115 hash_seq_init(&hstat, pendingOpsTable);
1116 while ((entry = (PendingOperationEntry *) hash_seq_search(&hstat)) != NULL)
1118 entry->cycle_ctr = mdsync_cycle_ctr;
1122 /* Advance counter so that new hashtable entries are distinguishable */
1125 /* Set flag to detect failure if we don't reach the end of the loop */
1126 mdsync_in_progress = true;
1128 /* Now scan the hashtable for fsync requests to process */
1129 absorb_counter = FSYNCS_PER_ABSORB;
1130 hash_seq_init(&hstat, pendingOpsTable);
1131 while ((entry = (PendingOperationEntry *) hash_seq_search(&hstat)) != NULL)
1136 * If the entry is new then don't process it this time; it might
1137 * contain multiple fsync-request bits, but they are all new. Note
1138 * "continue" bypasses the hash-remove call at the bottom of the loop.
1140 if (entry->cycle_ctr == mdsync_cycle_ctr)
1143 /* Else assert we haven't missed it */
1144 Assert((CycleCtr) (entry->cycle_ctr + 1) == mdsync_cycle_ctr);
1147 * Scan over the forks and segments represented by the entry.
1149 * The bitmap manipulations are slightly tricky, because we can call
1150 * AbsorbFsyncRequests() inside the loop and that could result in
1151 * bms_add_member() modifying and even re-palloc'ing the bitmapsets.
1152 * This is okay because we unlink each bitmapset from the hashtable
1153 * entry before scanning it. That means that any incoming fsync
1154 * requests will be processed now if they reach the table before we
1155 * begin to scan their fork.
1157 for (forknum = 0; forknum <= MAX_FORKNUM; forknum++)
1159 Bitmapset *requests = entry->requests[forknum];
1162 entry->requests[forknum] = NULL;
1163 entry->canceled[forknum] = false;
1165 while ((segno = bms_first_member(requests)) >= 0)
1170 * If fsync is off then we don't have to bother opening the
1171 * file at all. (We delay checking until this point so that
1172 * changing fsync on the fly behaves sensibly.)
1178 * If in checkpointer, we want to absorb pending requests
1179 * every so often to prevent overflow of the fsync request
1180 * queue. It is unspecified whether newly-added entries will
1181 * be visited by hash_seq_search, but we don't care since we
1182 * don't need to process them anyway.
1184 if (--absorb_counter <= 0)
1186 AbsorbFsyncRequests();
1187 absorb_counter = FSYNCS_PER_ABSORB;
1191 * The fsync table could contain requests to fsync segments
1192 * that have been deleted (unlinked) by the time we get to
1193 * them. Rather than just hoping an ENOENT (or EACCES on
1194 * Windows) error can be ignored, what we do on error is
1195 * absorb pending requests and then retry. Since mdunlink()
1196 * queues a "cancel" message before actually unlinking, the
1197 * fsync request is guaranteed to be marked canceled after the
1198 * absorb if it really was this case. DROP DATABASE likewise
1199 * has to tell us to forget fsync requests before it starts
1202 for (failures = 0;; failures++) /* loop exits at "break" */
1210 * Find or create an smgr hash entry for this relation.
1211 * This may seem a bit unclean -- md calling smgr? But
1212 * it's really the best solution. It ensures that the
1213 * open file reference isn't permanently leaked if we get
1214 * an error here. (You may say "but an unreferenced
1215 * SMgrRelation is still a leak!" Not really, because the
1216 * only case in which a checkpoint is done by a process
1217 * that isn't about to shut down is in the checkpointer,
1218 * and it will periodically do smgrcloseall(). This fact
1219 * justifies our not closing the reln in the success path
1220 * either, which is a good thing since in non-checkpointer
1221 * cases we couldn't safely do that.)
1223 reln = smgropen(entry->rnode, InvalidBackendId);
1225 /* Attempt to open and fsync the target segment */
1226 seg = _mdfd_getseg(reln, forknum,
1227 (BlockNumber) segno * (BlockNumber) RELSEG_SIZE,
1229 EXTENSION_RETURN_NULL
1230 | EXTENSION_DONT_CHECK_SIZE);
1232 INSTR_TIME_SET_CURRENT(sync_start);
1235 FileSync(seg->mdfd_vfd, WAIT_EVENT_DATA_FILE_SYNC) >= 0)
1237 /* Success; update statistics about sync timing */
1238 INSTR_TIME_SET_CURRENT(sync_end);
1239 sync_diff = sync_end;
1240 INSTR_TIME_SUBTRACT(sync_diff, sync_start);
1241 elapsed = INSTR_TIME_GET_MICROSEC(sync_diff);
1242 if (elapsed > longest)
1244 total_elapsed += elapsed;
1246 if (log_checkpoints)
1247 elog(DEBUG1, "checkpoint sync: number=%d file=%s time=%.3f msec",
1249 FilePathName(seg->mdfd_vfd),
1250 (double) elapsed / 1000);
1252 break; /* out of retry loop */
1255 /* Compute file name for use in message */
1257 path = _mdfd_segpath(reln, forknum, (BlockNumber) segno);
1261 * It is possible that the relation has been dropped or
1262 * truncated since the fsync request was entered.
1263 * Therefore, allow ENOENT, but only if we didn't fail
1264 * already on this file. This applies both for
1265 * _mdfd_getseg() and for FileSync, since fd.c might have
1266 * closed the file behind our back.
1268 * XXX is there any point in allowing more than one retry?
1269 * Don't see one at the moment, but easy to change the
1272 if (!FILE_POSSIBLY_DELETED(errno) ||
1275 (errcode_for_file_access(),
1276 errmsg("could not fsync file \"%s\": %m",
1280 (errcode_for_file_access(),
1281 errmsg("could not fsync file \"%s\" but retrying: %m",
1286 * Absorb incoming requests and check to see if a cancel
1287 * arrived for this relation fork.
1289 AbsorbFsyncRequests();
1290 absorb_counter = FSYNCS_PER_ABSORB; /* might as well... */
1292 if (entry->canceled[forknum])
1294 } /* end retry loop */
1300 * We've finished everything that was requested before we started to
1301 * scan the entry. If no new requests have been inserted meanwhile,
1302 * remove the entry. Otherwise, update its cycle counter, as all the
1303 * requests now in it must have arrived during this cycle.
1305 for (forknum = 0; forknum <= MAX_FORKNUM; forknum++)
1307 if (entry->requests[forknum] != NULL)
1310 if (forknum <= MAX_FORKNUM)
1311 entry->cycle_ctr = mdsync_cycle_ctr;
1314 /* Okay to remove it */
1315 if (hash_search(pendingOpsTable, &entry->rnode,
1316 HASH_REMOVE, NULL) == NULL)
1317 elog(ERROR, "pendingOpsTable corrupted");
1319 } /* end loop over hashtable entries */
1321 /* Return sync performance metrics for report at checkpoint end */
1322 CheckpointStats.ckpt_sync_rels = processed;
1323 CheckpointStats.ckpt_longest_sync = longest;
1324 CheckpointStats.ckpt_agg_sync_time = total_elapsed;
1326 /* Flag successful completion of mdsync */
1327 mdsync_in_progress = false;
1331 * mdpreckpt() -- Do pre-checkpoint work
1333 * To distinguish unlink requests that arrived before this checkpoint
1334 * started from those that arrived during the checkpoint, we use a cycle
1335 * counter similar to the one we use for fsync requests. That cycle
1336 * counter is incremented here.
1338 * This must be called *before* the checkpoint REDO point is determined.
1339 * That ensures that we won't delete files too soon.
1341 * Note that we can't do anything here that depends on the assumption
1342 * that the checkpoint will be completed.
1348 * Any unlink requests arriving after this point will be assigned the next
1349 * cycle counter, and won't be unlinked until next checkpoint.
1355 * mdpostckpt() -- Do post-checkpoint work
1357 * Remove any lingering files that can now be safely removed.
1364 absorb_counter = UNLINKS_PER_ABSORB;
1365 while (pendingUnlinks != NIL)
1367 PendingUnlinkEntry *entry = (PendingUnlinkEntry *) linitial(pendingUnlinks);
1371 * New entries are appended to the end, so if the entry is new we've
1372 * reached the end of old entries.
1374 * Note: if just the right number of consecutive checkpoints fail, we
1375 * could be fooled here by cycle_ctr wraparound. However, the only
1376 * consequence is that we'd delay unlinking for one more checkpoint,
1377 * which is perfectly tolerable.
1379 if (entry->cycle_ctr == mdckpt_cycle_ctr)
1382 /* Unlink the file */
1383 path = relpathperm(entry->rnode, MAIN_FORKNUM);
1384 if (unlink(path) < 0)
1387 * There's a race condition, when the database is dropped at the
1388 * same time that we process the pending unlink requests. If the
1389 * DROP DATABASE deletes the file before we do, we will get ENOENT
1390 * here. rmtree() also has to ignore ENOENT errors, to deal with
1391 * the possibility that we delete the file first.
1393 if (errno != ENOENT)
1395 (errcode_for_file_access(),
1396 errmsg("could not remove file \"%s\": %m", path)));
1400 /* And remove the list entry */
1401 pendingUnlinks = list_delete_first(pendingUnlinks);
1405 * As in mdsync, we don't want to stop absorbing fsync requests for a
1406 * long time when there are many deletions to be done. We can safely
1407 * call AbsorbFsyncRequests() at this point in the loop (note it might
1408 * try to delete list entries).
1410 if (--absorb_counter <= 0)
1412 AbsorbFsyncRequests();
1413 absorb_counter = UNLINKS_PER_ABSORB;
1419 * register_dirty_segment() -- Mark a relation segment as needing fsync
1421 * If there is a local pending-ops table, just make an entry in it for
1422 * mdsync to process later. Otherwise, try to pass off the fsync request
1423 * to the checkpointer process. If that fails, just do the fsync
1424 * locally before returning (we hope this will not happen often enough
1425 * to be a performance problem).
1428 register_dirty_segment(SMgrRelation reln, ForkNumber forknum, MdfdVec *seg)
1430 /* Temp relations should never be fsync'd */
1431 Assert(!SmgrIsTemp(reln));
1433 if (pendingOpsTable)
1435 /* push it into local pending-ops table */
1436 RememberFsyncRequest(reln->smgr_rnode.node, forknum, seg->mdfd_segno);
1440 if (ForwardFsyncRequest(reln->smgr_rnode.node, forknum, seg->mdfd_segno))
1441 return; /* passed it off successfully */
1444 (errmsg("could not forward fsync request because request queue is full")));
1446 if (FileSync(seg->mdfd_vfd, WAIT_EVENT_DATA_FILE_SYNC) < 0)
1448 (errcode_for_file_access(),
1449 errmsg("could not fsync file \"%s\": %m",
1450 FilePathName(seg->mdfd_vfd))));
1455 * register_unlink() -- Schedule a file to be deleted after next checkpoint
1457 * We don't bother passing in the fork number, because this is only used
1460 * As with register_dirty_segment, this could involve either a local or
1461 * a remote pending-ops table.
1464 register_unlink(RelFileNodeBackend rnode)
1466 /* Should never be used with temp relations */
1467 Assert(!RelFileNodeBackendIsTemp(rnode));
1469 if (pendingOpsTable)
1471 /* push it into local pending-ops table */
1472 RememberFsyncRequest(rnode.node, MAIN_FORKNUM,
1473 UNLINK_RELATION_REQUEST);
1478 * Notify the checkpointer about it. If we fail to queue the request
1479 * message, we have to sleep and try again, because we can't simply
1480 * delete the file now. Ugly, but hopefully won't happen often.
1482 * XXX should we just leave the file orphaned instead?
1484 Assert(IsUnderPostmaster);
1485 while (!ForwardFsyncRequest(rnode.node, MAIN_FORKNUM,
1486 UNLINK_RELATION_REQUEST))
1487 pg_usleep(10000L); /* 10 msec seems a good number */
1492 * RememberFsyncRequest() -- callback from checkpointer side of fsync request
1494 * We stuff fsync requests into the local hash table for execution
1495 * during the checkpointer's next checkpoint. UNLINK requests go into a
1496 * separate linked list, however, because they get processed separately.
1498 * The range of possible segment numbers is way less than the range of
1499 * BlockNumber, so we can reserve high values of segno for special purposes.
1501 * - FORGET_RELATION_FSYNC means to cancel pending fsyncs for a relation,
1502 * either for one fork, or all forks if forknum is InvalidForkNumber
1503 * - FORGET_DATABASE_FSYNC means to cancel pending fsyncs for a whole database
1504 * - UNLINK_RELATION_REQUEST is a request to delete the file after the next
1506 * Note also that we're assuming real segment numbers don't exceed INT_MAX.
1508 * (Handling FORGET_DATABASE_FSYNC requests is a tad slow because the hash
1509 * table has to be searched linearly, but dropping a database is a pretty
1510 * heavyweight operation anyhow, so we'll live with it.)
1513 RememberFsyncRequest(RelFileNode rnode, ForkNumber forknum, BlockNumber segno)
1515 Assert(pendingOpsTable);
1517 if (segno == FORGET_RELATION_FSYNC)
1519 /* Remove any pending requests for the relation (one or all forks) */
1520 PendingOperationEntry *entry;
1522 entry = (PendingOperationEntry *) hash_search(pendingOpsTable,
1529 * We can't just delete the entry since mdsync could have an
1530 * active hashtable scan. Instead we delete the bitmapsets; this
1531 * is safe because of the way mdsync is coded. We also set the
1532 * "canceled" flags so that mdsync can tell that a cancel arrived
1535 if (forknum == InvalidForkNumber)
1537 /* remove requests for all forks */
1538 for (forknum = 0; forknum <= MAX_FORKNUM; forknum++)
1540 bms_free(entry->requests[forknum]);
1541 entry->requests[forknum] = NULL;
1542 entry->canceled[forknum] = true;
1547 /* remove requests for single fork */
1548 bms_free(entry->requests[forknum]);
1549 entry->requests[forknum] = NULL;
1550 entry->canceled[forknum] = true;
1554 else if (segno == FORGET_DATABASE_FSYNC)
1556 /* Remove any pending requests for the entire database */
1557 HASH_SEQ_STATUS hstat;
1558 PendingOperationEntry *entry;
1563 /* Remove fsync requests */
1564 hash_seq_init(&hstat, pendingOpsTable);
1565 while ((entry = (PendingOperationEntry *) hash_seq_search(&hstat)) != NULL)
1567 if (entry->rnode.dbNode == rnode.dbNode)
1569 /* remove requests for all forks */
1570 for (forknum = 0; forknum <= MAX_FORKNUM; forknum++)
1572 bms_free(entry->requests[forknum]);
1573 entry->requests[forknum] = NULL;
1574 entry->canceled[forknum] = true;
1579 /* Remove unlink requests */
1581 for (cell = list_head(pendingUnlinks); cell; cell = next)
1583 PendingUnlinkEntry *entry = (PendingUnlinkEntry *) lfirst(cell);
1586 if (entry->rnode.dbNode == rnode.dbNode)
1588 pendingUnlinks = list_delete_cell(pendingUnlinks, cell, prev);
1595 else if (segno == UNLINK_RELATION_REQUEST)
1597 /* Unlink request: put it in the linked list */
1598 MemoryContext oldcxt = MemoryContextSwitchTo(pendingOpsCxt);
1599 PendingUnlinkEntry *entry;
1601 /* PendingUnlinkEntry doesn't store forknum, since it's always MAIN */
1602 Assert(forknum == MAIN_FORKNUM);
1604 entry = palloc(sizeof(PendingUnlinkEntry));
1605 entry->rnode = rnode;
1606 entry->cycle_ctr = mdckpt_cycle_ctr;
1608 pendingUnlinks = lappend(pendingUnlinks, entry);
1610 MemoryContextSwitchTo(oldcxt);
1614 /* Normal case: enter a request to fsync this segment */
1615 MemoryContext oldcxt = MemoryContextSwitchTo(pendingOpsCxt);
1616 PendingOperationEntry *entry;
1619 entry = (PendingOperationEntry *) hash_search(pendingOpsTable,
1623 /* if new entry, initialize it */
1626 entry->cycle_ctr = mdsync_cycle_ctr;
1627 MemSet(entry->requests, 0, sizeof(entry->requests));
1628 MemSet(entry->canceled, 0, sizeof(entry->canceled));
1632 * NB: it's intentional that we don't change cycle_ctr if the entry
1633 * already exists. The cycle_ctr must represent the oldest fsync
1634 * request that could be in the entry.
1637 entry->requests[forknum] = bms_add_member(entry->requests[forknum],
1640 MemoryContextSwitchTo(oldcxt);
1645 * ForgetRelationFsyncRequests -- forget any fsyncs for a relation fork
1647 * forknum == InvalidForkNumber means all forks, although this code doesn't
1648 * actually know that, since it's just forwarding the request elsewhere.
1651 ForgetRelationFsyncRequests(RelFileNode rnode, ForkNumber forknum)
1653 if (pendingOpsTable)
1655 /* standalone backend or startup process: fsync state is local */
1656 RememberFsyncRequest(rnode, forknum, FORGET_RELATION_FSYNC);
1658 else if (IsUnderPostmaster)
1661 * Notify the checkpointer about it. If we fail to queue the cancel
1662 * message, we have to sleep and try again ... ugly, but hopefully
1663 * won't happen often.
1665 * XXX should we CHECK_FOR_INTERRUPTS in this loop? Escaping with an
1666 * error would leave the no-longer-used file still present on disk,
1667 * which would be bad, so I'm inclined to assume that the checkpointer
1668 * will always empty the queue soon.
1670 while (!ForwardFsyncRequest(rnode, forknum, FORGET_RELATION_FSYNC))
1671 pg_usleep(10000L); /* 10 msec seems a good number */
1674 * Note we don't wait for the checkpointer to actually absorb the
1675 * cancel message; see mdsync() for the implications.
1681 * ForgetDatabaseFsyncRequests -- forget any fsyncs and unlinks for a DB
1684 ForgetDatabaseFsyncRequests(Oid dbid)
1688 rnode.dbNode = dbid;
1692 if (pendingOpsTable)
1694 /* standalone backend or startup process: fsync state is local */
1695 RememberFsyncRequest(rnode, InvalidForkNumber, FORGET_DATABASE_FSYNC);
1697 else if (IsUnderPostmaster)
1699 /* see notes in ForgetRelationFsyncRequests */
1700 while (!ForwardFsyncRequest(rnode, InvalidForkNumber,
1701 FORGET_DATABASE_FSYNC))
1702 pg_usleep(10000L); /* 10 msec seems a good number */
1708 * _fdvec_resize() -- Resize the fork's open segments array
1711 _fdvec_resize(SMgrRelation reln,
1717 if (reln->md_num_open_segs[forknum] > 0)
1719 pfree(reln->md_seg_fds[forknum]);
1720 reln->md_seg_fds[forknum] = NULL;
1723 else if (reln->md_num_open_segs[forknum] == 0)
1725 reln->md_seg_fds[forknum] =
1726 MemoryContextAlloc(MdCxt, sizeof(MdfdVec) * nseg);
1731 * It doesn't seem worthwhile complicating the code by having a more
1732 * aggressive growth strategy here; the number of segments doesn't
1733 * grow that fast, and the memory context internally will sometimes
1734 * avoid doing an actual reallocation.
1736 reln->md_seg_fds[forknum] =
1737 repalloc(reln->md_seg_fds[forknum],
1738 sizeof(MdfdVec) * nseg);
1741 reln->md_num_open_segs[forknum] = nseg;
1745 * Return the filename for the specified segment of the relation. The
1746 * returned string is palloc'd.
1749 _mdfd_segpath(SMgrRelation reln, ForkNumber forknum, BlockNumber segno)
1754 path = relpath(reln->smgr_rnode, forknum);
1758 fullpath = psprintf("%s.%u", path, segno);
1768 * Open the specified segment of the relation,
1769 * and make a MdfdVec object for it. Returns NULL on failure.
1772 _mdfd_openseg(SMgrRelation reln, ForkNumber forknum, BlockNumber segno,
1779 fullpath = _mdfd_segpath(reln, forknum, segno);
1782 fd = PathNameOpenFile(fullpath, O_RDWR | PG_BINARY | oflags);
1789 if (segno <= reln->md_num_open_segs[forknum])
1790 _fdvec_resize(reln, forknum, segno + 1);
1792 /* fill the entry */
1793 v = &reln->md_seg_fds[forknum][segno];
1795 v->mdfd_segno = segno;
1797 Assert(_mdnblocks(reln, forknum, v) <= ((BlockNumber) RELSEG_SIZE));
1804 * _mdfd_getseg() -- Find the segment of the relation holding the
1807 * If the segment doesn't exist, we ereport, return NULL, or create the
1808 * segment, according to "behavior". Note: skipFsync is only used in the
1809 * EXTENSION_CREATE case.
1812 _mdfd_getseg(SMgrRelation reln, ForkNumber forknum, BlockNumber blkno,
1813 bool skipFsync, int behavior)
1816 BlockNumber targetseg;
1817 BlockNumber nextsegno;
1819 /* some way to handle non-existent segments needs to be specified */
1821 (EXTENSION_FAIL | EXTENSION_CREATE | EXTENSION_RETURN_NULL));
1823 targetseg = blkno / ((BlockNumber) RELSEG_SIZE);
1825 /* if an existing and opened segment, we're done */
1826 if (targetseg < reln->md_num_open_segs[forknum])
1828 v = &reln->md_seg_fds[forknum][targetseg];
1833 * The target segment is not yet open. Iterate over all the segments
1834 * between the last opened and the target segment. This way missing
1835 * segments either raise an error, or get created (according to
1836 * 'behavior'). Start with either the last opened, or the first segment if
1837 * none was opened before.
1839 if (reln->md_num_open_segs[forknum] > 0)
1840 v = &reln->md_seg_fds[forknum][reln->md_num_open_segs[forknum] - 1];
1843 v = mdopen(reln, forknum, behavior);
1845 return NULL; /* if behavior & EXTENSION_RETURN_NULL */
1848 for (nextsegno = reln->md_num_open_segs[forknum];
1849 nextsegno <= targetseg; nextsegno++)
1851 BlockNumber nblocks = _mdnblocks(reln, forknum, v);
1854 Assert(nextsegno == v->mdfd_segno + 1);
1856 if (nblocks > ((BlockNumber) RELSEG_SIZE))
1857 elog(FATAL, "segment too big");
1859 if ((behavior & EXTENSION_CREATE) ||
1860 (InRecovery && (behavior & EXTENSION_CREATE_RECOVERY)))
1863 * Normally we will create new segments only if authorized by the
1864 * caller (i.e., we are doing mdextend()). But when doing WAL
1865 * recovery, create segments anyway; this allows cases such as
1866 * replaying WAL data that has a write into a high-numbered
1867 * segment of a relation that was later deleted. We want to go
1868 * ahead and create the segments so we can finish out the replay.
1869 * However if the caller has specified
1870 * EXTENSION_REALLY_RETURN_NULL, then extension is not desired
1871 * even in recovery; we won't reach this point in that case.
1873 * We have to maintain the invariant that segments before the last
1874 * active segment are of size RELSEG_SIZE; therefore, if
1875 * extending, pad them out with zeroes if needed. (This only
1876 * matters if in recovery, or if the caller is extending the
1877 * relation discontiguously, but that can happen in hash indexes.)
1879 if (nblocks < ((BlockNumber) RELSEG_SIZE))
1881 char *zerobuf = palloc0(BLCKSZ);
1883 mdextend(reln, forknum,
1884 nextsegno * ((BlockNumber) RELSEG_SIZE) - 1,
1885 zerobuf, skipFsync);
1890 else if (!(behavior & EXTENSION_DONT_CHECK_SIZE) &&
1891 nblocks < ((BlockNumber) RELSEG_SIZE))
1894 * When not extending (or explicitly including truncated
1895 * segments), only open the next segment if the current one is
1896 * exactly RELSEG_SIZE. If not (this branch), either return NULL
1899 if (behavior & EXTENSION_RETURN_NULL)
1902 * Some callers discern between reasons for _mdfd_getseg()
1903 * returning NULL based on errno. As there's no failing
1904 * syscall involved in this case, explicitly set errno to
1905 * ENOENT, as that seems the closest interpretation.
1912 (errcode_for_file_access(),
1913 errmsg("could not open file \"%s\" (target block %u): previous segment is only %u blocks",
1914 _mdfd_segpath(reln, forknum, nextsegno),
1918 v = _mdfd_openseg(reln, forknum, nextsegno, flags);
1922 if ((behavior & EXTENSION_RETURN_NULL) &&
1923 FILE_POSSIBLY_DELETED(errno))
1926 (errcode_for_file_access(),
1927 errmsg("could not open file \"%s\" (target block %u): %m",
1928 _mdfd_segpath(reln, forknum, nextsegno),
1937 * Get number of blocks present in a single disk file
1940 _mdnblocks(SMgrRelation reln, ForkNumber forknum, MdfdVec *seg)
1944 len = FileSeek(seg->mdfd_vfd, 0L, SEEK_END);
1947 (errcode_for_file_access(),
1948 errmsg("could not seek to end of file \"%s\": %m",
1949 FilePathName(seg->mdfd_vfd))));
1950 /* note that this calculation will ignore any partial block at EOF */
1951 return (BlockNumber) (len / BLCKSZ);