Fix oversight in previous error-reporting patch; mustn't pfree path string
[PostgreSQL.git] / src / backend / storage / smgr / md.c
blobf2975c15aa6ef3d722b53ee0ec1256f6a984462f
1 /*-------------------------------------------------------------------------
3 * md.c
4 * This code manages relations that reside on magnetic disk.
6 * Portions Copyright (c) 1996-2008, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
10 * IDENTIFICATION
11 * $PostgreSQL$
13 *-------------------------------------------------------------------------
15 #include "postgres.h"
17 #include <unistd.h>
18 #include <fcntl.h>
19 #include <sys/file.h>
21 #include "catalog/catalog.h"
22 #include "miscadmin.h"
23 #include "postmaster/bgwriter.h"
24 #include "storage/fd.h"
25 #include "storage/bufmgr.h"
26 #include "storage/relfilenode.h"
27 #include "storage/smgr.h"
28 #include "utils/hsearch.h"
29 #include "utils/memutils.h"
32 /* interval for calling AbsorbFsyncRequests in mdsync */
33 #define FSYNCS_PER_ABSORB 10
35 /* special values for the segno arg to RememberFsyncRequest */
36 #define FORGET_RELATION_FSYNC (InvalidBlockNumber)
37 #define FORGET_DATABASE_FSYNC (InvalidBlockNumber-1)
38 #define UNLINK_RELATION_REQUEST (InvalidBlockNumber-2)
41 * On Windows, we have to interpret EACCES as possibly meaning the same as
42 * ENOENT, because if a file is unlinked-but-not-yet-gone on that platform,
43 * that's what you get. Ugh. This code is designed so that we don't
44 * actually believe these cases are okay without further evidence (namely,
45 * a pending fsync request getting revoked ... see mdsync).
47 #ifndef WIN32
48 #define FILE_POSSIBLY_DELETED(err) ((err) == ENOENT)
49 #else
50 #define FILE_POSSIBLY_DELETED(err) ((err) == ENOENT || (err) == EACCES)
51 #endif
54 * The magnetic disk storage manager keeps track of open file
55 * descriptors in its own descriptor pool. This is done to make it
56 * easier to support relations that are larger than the operating
57 * system's file size limit (often 2GBytes). In order to do that,
58 * we break relations up into "segment" files that are each shorter than
59 * the OS file size limit. The segment size is set by the RELSEG_SIZE
60 * configuration constant in pg_config.h.
62 * On disk, a relation must consist of consecutively numbered segment
63 * files in the pattern
64 * -- Zero or more full segments of exactly RELSEG_SIZE blocks each
65 * -- Exactly one partial segment of size 0 <= size < RELSEG_SIZE blocks
66 * -- Optionally, any number of inactive segments of size 0 blocks.
67 * The full and partial segments are collectively the "active" segments.
68 * Inactive segments are those that once contained data but are currently
69 * not needed because of an mdtruncate() operation. The reason for leaving
70 * them present at size zero, rather than unlinking them, is that other
71 * backends and/or the bgwriter might be holding open file references to
72 * such segments. If the relation expands again after mdtruncate(), such
73 * that a deactivated segment becomes active again, it is important that
74 * such file references still be valid --- else data might get written
75 * out to an unlinked old copy of a segment file that will eventually
76 * disappear.
78 * The file descriptor pointer (md_fd field) stored in the SMgrRelation
79 * cache is, therefore, just the head of a list of MdfdVec objects, one
80 * per segment. But note the md_fd pointer can be NULL, indicating
81 * relation not open.
83 * Also note that mdfd_chain == NULL does not necessarily mean the relation
84 * doesn't have another segment after this one; we may just not have
85 * opened the next segment yet. (We could not have "all segments are
86 * in the chain" as an invariant anyway, since another backend could
87 * extend the relation when we weren't looking.) We do not make chain
88 * entries for inactive segments, however; as soon as we find a partial
89 * segment, we assume that any subsequent segments are inactive.
91 * All MdfdVec objects are palloc'd in the MdCxt memory context.
94 typedef struct _MdfdVec
96 File mdfd_vfd; /* fd number in fd.c's pool */
97 BlockNumber mdfd_segno; /* segment number, from 0 */
98 struct _MdfdVec *mdfd_chain; /* next segment, or NULL */
99 } MdfdVec;
101 static MemoryContext MdCxt; /* context for all md.c allocations */
105 * In some contexts (currently, standalone backends and the bgwriter process)
106 * we keep track of pending fsync operations: we need to remember all relation
107 * segments that have been written since the last checkpoint, so that we can
108 * fsync them down to disk before completing the next checkpoint. This hash
109 * table remembers the pending operations. We use a hash table mostly as
110 * a convenient way of eliminating duplicate requests.
112 * We use a similar mechanism to remember no-longer-needed files that can
113 * be deleted after the next checkpoint, but we use a linked list instead of
114 * a hash table, because we don't expect there to be any duplicate requests.
116 * (Regular backends do not track pending operations locally, but forward
117 * them to the bgwriter.)
119 typedef struct
121 RelFileNode rnode; /* the targeted relation */
122 ForkNumber forknum;
123 BlockNumber segno; /* which segment */
124 } PendingOperationTag;
126 typedef uint16 CycleCtr; /* can be any convenient integer size */
128 typedef struct
130 PendingOperationTag tag; /* hash table key (must be first!) */
131 bool canceled; /* T => request canceled, not yet removed */
132 CycleCtr cycle_ctr; /* mdsync_cycle_ctr when request was made */
133 } PendingOperationEntry;
135 typedef struct
137 RelFileNode rnode; /* the dead relation to delete */
138 CycleCtr cycle_ctr; /* mdckpt_cycle_ctr when request was made */
139 } PendingUnlinkEntry;
141 static HTAB *pendingOpsTable = NULL;
142 static List *pendingUnlinks = NIL;
144 static CycleCtr mdsync_cycle_ctr = 0;
145 static CycleCtr mdckpt_cycle_ctr = 0;
148 typedef enum /* behavior for mdopen & _mdfd_getseg */
150 EXTENSION_FAIL, /* ereport if segment not present */
151 EXTENSION_RETURN_NULL, /* return NULL if not present */
152 EXTENSION_CREATE /* create new segments as needed */
153 } ExtensionBehavior;
155 /* local routines */
156 static MdfdVec *mdopen(SMgrRelation reln, ForkNumber forknum,
157 ExtensionBehavior behavior);
158 static void register_dirty_segment(SMgrRelation reln, ForkNumber forknum,
159 MdfdVec *seg);
160 static void register_unlink(RelFileNode rnode);
161 static MdfdVec *_fdvec_alloc(void);
162 static MdfdVec *_mdfd_openseg(SMgrRelation reln, ForkNumber forkno,
163 BlockNumber segno, int oflags);
164 static MdfdVec *_mdfd_getseg(SMgrRelation reln, ForkNumber forkno,
165 BlockNumber blkno, bool isTemp, ExtensionBehavior behavior);
166 static BlockNumber _mdnblocks(SMgrRelation reln, ForkNumber forknum,
167 MdfdVec *seg);
171 * mdinit() -- Initialize private state for magnetic disk storage manager.
173 void
174 mdinit(void)
176 MdCxt = AllocSetContextCreate(TopMemoryContext,
177 "MdSmgr",
178 ALLOCSET_DEFAULT_MINSIZE,
179 ALLOCSET_DEFAULT_INITSIZE,
180 ALLOCSET_DEFAULT_MAXSIZE);
183 * Create pending-operations hashtable if we need it. Currently, we need
184 * it if we are standalone (not under a postmaster) OR if we are a
185 * bootstrap-mode subprocess of a postmaster (that is, a startup or
186 * bgwriter process).
188 if (!IsUnderPostmaster || IsBootstrapProcessingMode())
190 HASHCTL hash_ctl;
192 MemSet(&hash_ctl, 0, sizeof(hash_ctl));
193 hash_ctl.keysize = sizeof(PendingOperationTag);
194 hash_ctl.entrysize = sizeof(PendingOperationEntry);
195 hash_ctl.hash = tag_hash;
196 hash_ctl.hcxt = MdCxt;
197 pendingOpsTable = hash_create("Pending Ops Table",
198 100L,
199 &hash_ctl,
200 HASH_ELEM | HASH_FUNCTION | HASH_CONTEXT);
201 pendingUnlinks = NIL;
206 * mdexists() -- Does the physical file exist?
208 * Note: this will return true for lingering files, with pending deletions
210 bool
211 mdexists(SMgrRelation reln, ForkNumber forkNum)
214 * Close it first, to ensure that we notice if the fork has been
215 * unlinked since we opened it.
217 mdclose(reln, forkNum);
219 return (mdopen(reln, forkNum, EXTENSION_RETURN_NULL) != NULL);
223 * mdcreate() -- Create a new relation on magnetic disk.
225 * If isRedo is true, it's okay for the relation to exist already.
227 void
228 mdcreate(SMgrRelation reln, ForkNumber forkNum, bool isRedo)
230 char *path;
231 File fd;
233 if (isRedo && reln->md_fd[forkNum] != NULL)
234 return; /* created and opened already... */
236 Assert(reln->md_fd[forkNum] == NULL);
238 path = relpath(reln->smgr_rnode, forkNum);
240 fd = PathNameOpenFile(path, O_RDWR | O_CREAT | O_EXCL | PG_BINARY, 0600);
242 if (fd < 0)
244 int save_errno = errno;
247 * During bootstrap, there are cases where a system relation will be
248 * accessed (by internal backend processes) before the bootstrap
249 * script nominally creates it. Therefore, allow the file to exist
250 * already, even if isRedo is not set. (See also mdopen)
252 if (isRedo || IsBootstrapProcessingMode())
253 fd = PathNameOpenFile(path, O_RDWR | PG_BINARY, 0600);
254 if (fd < 0)
256 /* be sure to report the error reported by create, not open */
257 errno = save_errno;
258 ereport(ERROR,
259 (errcode_for_file_access(),
260 errmsg("could not create relation %s: %m", path)));
264 pfree(path);
266 reln->md_fd[forkNum] = _fdvec_alloc();
268 reln->md_fd[forkNum]->mdfd_vfd = fd;
269 reln->md_fd[forkNum]->mdfd_segno = 0;
270 reln->md_fd[forkNum]->mdfd_chain = NULL;
274 * mdunlink() -- Unlink a relation.
276 * Note that we're passed a RelFileNode --- by the time this is called,
277 * there won't be an SMgrRelation hashtable entry anymore.
279 * Actually, we don't unlink the first segment file of the relation, but
280 * just truncate it to zero length, and record a request to unlink it after
281 * the next checkpoint. Additional segments can be unlinked immediately,
282 * however. Leaving the empty file in place prevents that relfilenode
283 * number from being reused. The scenario this protects us from is:
284 * 1. We delete a relation (and commit, and actually remove its file).
285 * 2. We create a new relation, which by chance gets the same relfilenode as
286 * the just-deleted one (OIDs must've wrapped around for that to happen).
287 * 3. We crash before another checkpoint occurs.
288 * During replay, we would delete the file and then recreate it, which is fine
289 * if the contents of the file were repopulated by subsequent WAL entries.
290 * But if we didn't WAL-log insertions, but instead relied on fsyncing the
291 * file after populating it (as for instance CLUSTER and CREATE INDEX do),
292 * the contents of the file would be lost forever. By leaving the empty file
293 * until after the next checkpoint, we prevent reassignment of the relfilenode
294 * number until it's safe, because relfilenode assignment skips over any
295 * existing file.
297 * If isRedo is true, it's okay for the relation to be already gone.
298 * Also, we should remove the file immediately instead of queuing a request
299 * for later, since during redo there's no possibility of creating a
300 * conflicting relation.
302 * Note: any failure should be reported as WARNING not ERROR, because
303 * we are usually not in a transaction anymore when this is called.
305 void
306 mdunlink(RelFileNode rnode, ForkNumber forkNum, bool isRedo)
308 char *path;
309 int ret;
312 * We have to clean out any pending fsync requests for the doomed
313 * relation, else the next mdsync() will fail.
315 ForgetRelationFsyncRequests(rnode, forkNum);
317 path = relpath(rnode, forkNum);
320 * Delete or truncate the first segment.
322 if (isRedo || forkNum != MAIN_FORKNUM)
323 ret = unlink(path);
324 else
326 /* truncate(2) would be easier here, but Windows hasn't got it */
327 int fd;
329 fd = BasicOpenFile(path, O_RDWR | PG_BINARY, 0);
330 if (fd >= 0)
332 int save_errno;
334 ret = ftruncate(fd, 0);
335 save_errno = errno;
336 close(fd);
337 errno = save_errno;
339 else
340 ret = -1;
342 if (ret < 0)
344 if (!isRedo || errno != ENOENT)
345 ereport(WARNING,
346 (errcode_for_file_access(),
347 errmsg("could not remove relation %s: %m", path)));
351 * Delete any additional segments.
353 else
355 char *segpath = (char *) palloc(strlen(path) + 12);
356 BlockNumber segno;
359 * Note that because we loop until getting ENOENT, we will correctly
360 * remove all inactive segments as well as active ones.
362 for (segno = 1;; segno++)
364 sprintf(segpath, "%s.%u", path, segno);
365 if (unlink(segpath) < 0)
367 /* ENOENT is expected after the last segment... */
368 if (errno != ENOENT)
369 ereport(WARNING,
370 (errcode_for_file_access(),
371 errmsg("could not remove segment %u of relation %s: %m",
372 segno, path)));
373 break;
376 pfree(segpath);
379 pfree(path);
381 /* Register request to unlink first segment later */
382 if (!isRedo && forkNum == MAIN_FORKNUM)
383 register_unlink(rnode);
387 * mdextend() -- Add a block to the specified relation.
389 * The semantics are nearly the same as mdwrite(): write at the
390 * specified position. However, this is to be used for the case of
391 * extending a relation (i.e., blocknum is at or beyond the current
392 * EOF). Note that we assume writing a block beyond current EOF
393 * causes intervening file space to become filled with zeroes.
395 void
396 mdextend(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum,
397 char *buffer, bool isTemp)
399 off_t seekpos;
400 int nbytes;
401 MdfdVec *v;
403 /* This assert is too expensive to have on normally ... */
404 #ifdef CHECK_WRITE_VS_EXTEND
405 Assert(blocknum >= mdnblocks(reln, forknum));
406 #endif
409 * If a relation manages to grow to 2^32-1 blocks, refuse to extend it any
410 * more --- we mustn't create a block whose number actually is
411 * InvalidBlockNumber.
413 if (blocknum == InvalidBlockNumber)
414 ereport(ERROR,
415 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
416 errmsg("cannot extend relation %s beyond %u blocks",
417 relpath(reln->smgr_rnode, forknum),
418 InvalidBlockNumber)));
420 v = _mdfd_getseg(reln, forknum, blocknum, isTemp, EXTENSION_CREATE);
422 seekpos = (off_t) BLCKSZ * (blocknum % ((BlockNumber) RELSEG_SIZE));
423 Assert(seekpos < (off_t) BLCKSZ * RELSEG_SIZE);
426 * Note: because caller usually obtained blocknum by calling mdnblocks,
427 * which did a seek(SEEK_END), this seek is often redundant and will be
428 * optimized away by fd.c. It's not redundant, however, if there is a
429 * partial page at the end of the file. In that case we want to try to
430 * overwrite the partial page with a full page. It's also not redundant
431 * if bufmgr.c had to dump another buffer of the same file to make room
432 * for the new page's buffer.
434 if (FileSeek(v->mdfd_vfd, seekpos, SEEK_SET) != seekpos)
435 ereport(ERROR,
436 (errcode_for_file_access(),
437 errmsg("could not seek to block %u of relation %s: %m",
438 blocknum,
439 relpath(reln->smgr_rnode, forknum))));
441 if ((nbytes = FileWrite(v->mdfd_vfd, buffer, BLCKSZ)) != BLCKSZ)
443 if (nbytes < 0)
444 ereport(ERROR,
445 (errcode_for_file_access(),
446 errmsg("could not extend relation %s: %m",
447 relpath(reln->smgr_rnode, forknum)),
448 errhint("Check free disk space.")));
449 /* short write: complain appropriately */
450 ereport(ERROR,
451 (errcode(ERRCODE_DISK_FULL),
452 errmsg("could not extend relation %s: wrote only %d of %d bytes at block %u",
453 relpath(reln->smgr_rnode, forknum),
454 nbytes, BLCKSZ, blocknum),
455 errhint("Check free disk space.")));
458 if (!isTemp)
459 register_dirty_segment(reln, forknum, v);
461 Assert(_mdnblocks(reln, forknum, v) <= ((BlockNumber) RELSEG_SIZE));
465 * mdopen() -- Open the specified relation.
467 * Note we only open the first segment, when there are multiple segments.
469 * If first segment is not present, either ereport or return NULL according
470 * to "behavior". We treat EXTENSION_CREATE the same as EXTENSION_FAIL;
471 * EXTENSION_CREATE means it's OK to extend an existing relation, not to
472 * invent one out of whole cloth.
474 static MdfdVec *
475 mdopen(SMgrRelation reln, ForkNumber forknum, ExtensionBehavior behavior)
477 MdfdVec *mdfd;
478 char *path;
479 File fd;
481 /* No work if already open */
482 if (reln->md_fd[forknum])
483 return reln->md_fd[forknum];
485 path = relpath(reln->smgr_rnode, forknum);
487 fd = PathNameOpenFile(path, O_RDWR | PG_BINARY, 0600);
489 if (fd < 0)
492 * During bootstrap, there are cases where a system relation will be
493 * accessed (by internal backend processes) before the bootstrap
494 * script nominally creates it. Therefore, accept mdopen() as a
495 * substitute for mdcreate() in bootstrap mode only. (See mdcreate)
497 if (IsBootstrapProcessingMode())
498 fd = PathNameOpenFile(path, O_RDWR | O_CREAT | O_EXCL | PG_BINARY, 0600);
499 if (fd < 0)
501 if (behavior == EXTENSION_RETURN_NULL &&
502 FILE_POSSIBLY_DELETED(errno))
504 pfree(path);
505 return NULL;
507 ereport(ERROR,
508 (errcode_for_file_access(),
509 errmsg("could not open relation %s: %m", path)));
513 pfree(path);
515 reln->md_fd[forknum] = mdfd = _fdvec_alloc();
517 mdfd->mdfd_vfd = fd;
518 mdfd->mdfd_segno = 0;
519 mdfd->mdfd_chain = NULL;
520 Assert(_mdnblocks(reln, forknum, mdfd) <= ((BlockNumber) RELSEG_SIZE));
522 return mdfd;
526 * mdclose() -- Close the specified relation, if it isn't closed already.
528 void
529 mdclose(SMgrRelation reln, ForkNumber forknum)
531 MdfdVec *v = reln->md_fd[forknum];
533 /* No work if already closed */
534 if (v == NULL)
535 return;
537 reln->md_fd[forknum] = NULL; /* prevent dangling pointer after error */
539 while (v != NULL)
541 MdfdVec *ov = v;
543 /* if not closed already */
544 if (v->mdfd_vfd >= 0)
545 FileClose(v->mdfd_vfd);
546 /* Now free vector */
547 v = v->mdfd_chain;
548 pfree(ov);
553 * mdread() -- Read the specified block from a relation.
555 void
556 mdread(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum,
557 char *buffer)
559 off_t seekpos;
560 int nbytes;
561 MdfdVec *v;
563 v = _mdfd_getseg(reln, forknum, blocknum, false, EXTENSION_FAIL);
565 seekpos = (off_t) BLCKSZ * (blocknum % ((BlockNumber) RELSEG_SIZE));
566 Assert(seekpos < (off_t) BLCKSZ * RELSEG_SIZE);
568 if (FileSeek(v->mdfd_vfd, seekpos, SEEK_SET) != seekpos)
569 ereport(ERROR,
570 (errcode_for_file_access(),
571 errmsg("could not seek to block %u of relation %s: %m",
572 blocknum, relpath(reln->smgr_rnode, forknum))));
574 if ((nbytes = FileRead(v->mdfd_vfd, buffer, BLCKSZ)) != BLCKSZ)
576 if (nbytes < 0)
577 ereport(ERROR,
578 (errcode_for_file_access(),
579 errmsg("could not read block %u of relation %s: %m",
580 blocknum, relpath(reln->smgr_rnode, forknum))));
583 * Short read: we are at or past EOF, or we read a partial block at
584 * EOF. Normally this is an error; upper levels should never try to
585 * read a nonexistent block. However, if zero_damaged_pages is ON or
586 * we are InRecovery, we should instead return zeroes without
587 * complaining. This allows, for example, the case of trying to
588 * update a block that was later truncated away.
590 if (zero_damaged_pages || InRecovery)
591 MemSet(buffer, 0, BLCKSZ);
592 else
593 ereport(ERROR,
594 (errcode(ERRCODE_DATA_CORRUPTED),
595 errmsg("could not read block %u of relation %s: read only %d of %d bytes",
596 blocknum, relpath(reln->smgr_rnode, forknum),
597 nbytes, BLCKSZ)));
602 * mdwrite() -- Write the supplied block at the appropriate location.
604 * This is to be used only for updating already-existing blocks of a
605 * relation (ie, those before the current EOF). To extend a relation,
606 * use mdextend().
608 void
609 mdwrite(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum,
610 char *buffer, bool isTemp)
612 off_t seekpos;
613 int nbytes;
614 MdfdVec *v;
616 /* This assert is too expensive to have on normally ... */
617 #ifdef CHECK_WRITE_VS_EXTEND
618 Assert(blocknum < mdnblocks(reln, forknum));
619 #endif
621 v = _mdfd_getseg(reln, forknum, blocknum, isTemp, EXTENSION_FAIL);
623 seekpos = (off_t) BLCKSZ * (blocknum % ((BlockNumber) RELSEG_SIZE));
624 Assert(seekpos < (off_t) BLCKSZ * RELSEG_SIZE);
626 if (FileSeek(v->mdfd_vfd, seekpos, SEEK_SET) != seekpos)
627 ereport(ERROR,
628 (errcode_for_file_access(),
629 errmsg("could not seek to block %u of relation %s: %m",
630 blocknum, relpath(reln->smgr_rnode, forknum))));
632 if ((nbytes = FileWrite(v->mdfd_vfd, buffer, BLCKSZ)) != BLCKSZ)
634 if (nbytes < 0)
635 ereport(ERROR,
636 (errcode_for_file_access(),
637 errmsg("could not write block %u of relation %s: %m",
638 blocknum, relpath(reln->smgr_rnode, forknum))));
639 /* short write: complain appropriately */
640 ereport(ERROR,
641 (errcode(ERRCODE_DISK_FULL),
642 errmsg("could not write block %u of relation %s: wrote only %d of %d bytes",
643 blocknum,
644 relpath(reln->smgr_rnode, forknum),
645 nbytes, BLCKSZ),
646 errhint("Check free disk space.")));
649 if (!isTemp)
650 register_dirty_segment(reln, forknum, v);
654 * mdnblocks() -- Get the number of blocks stored in a relation.
656 * Important side effect: all active segments of the relation are opened
657 * and added to the mdfd_chain list. If this routine has not been
658 * called, then only segments up to the last one actually touched
659 * are present in the chain.
661 BlockNumber
662 mdnblocks(SMgrRelation reln, ForkNumber forknum)
664 MdfdVec *v = mdopen(reln, forknum, EXTENSION_FAIL);
665 BlockNumber nblocks;
666 BlockNumber segno = 0;
669 * Skip through any segments that aren't the last one, to avoid redundant
670 * seeks on them. We have previously verified that these segments are
671 * exactly RELSEG_SIZE long, and it's useless to recheck that each time.
673 * NOTE: this assumption could only be wrong if another backend has
674 * truncated the relation. We rely on higher code levels to handle that
675 * scenario by closing and re-opening the md fd, which is handled via
676 * relcache flush. (Since the bgwriter doesn't participate in relcache
677 * flush, it could have segment chain entries for inactive segments;
678 * that's OK because the bgwriter never needs to compute relation size.)
680 while (v->mdfd_chain != NULL)
682 segno++;
683 v = v->mdfd_chain;
686 for (;;)
688 nblocks = _mdnblocks(reln, forknum, v);
689 if (nblocks > ((BlockNumber) RELSEG_SIZE))
690 elog(FATAL, "segment too big");
691 if (nblocks < ((BlockNumber) RELSEG_SIZE))
692 return (segno * ((BlockNumber) RELSEG_SIZE)) + nblocks;
695 * If segment is exactly RELSEG_SIZE, advance to next one.
697 segno++;
699 if (v->mdfd_chain == NULL)
702 * Because we pass O_CREAT, we will create the next segment (with
703 * zero length) immediately, if the last segment is of length
704 * RELSEG_SIZE. While perhaps not strictly necessary, this keeps
705 * the logic simple.
707 v->mdfd_chain = _mdfd_openseg(reln, forknum, segno, O_CREAT);
708 if (v->mdfd_chain == NULL)
709 ereport(ERROR,
710 (errcode_for_file_access(),
711 errmsg("could not open segment %u of relation %s: %m",
712 segno,
713 relpath(reln->smgr_rnode, forknum))));
716 v = v->mdfd_chain;
721 * mdtruncate() -- Truncate relation to specified number of blocks.
723 void
724 mdtruncate(SMgrRelation reln, ForkNumber forknum, BlockNumber nblocks,
725 bool isTemp)
727 MdfdVec *v;
728 BlockNumber curnblk;
729 BlockNumber priorblocks;
732 * NOTE: mdnblocks makes sure we have opened all active segments, so that
733 * truncation loop will get them all!
735 curnblk = mdnblocks(reln, forknum);
736 if (nblocks > curnblk)
738 /* Bogus request ... but no complaint if InRecovery */
739 if (InRecovery)
740 return;
741 ereport(ERROR,
742 (errmsg("could not truncate relation %s to %u blocks: it's only %u blocks now",
743 relpath(reln->smgr_rnode, forknum),
744 nblocks, curnblk)));
746 if (nblocks == curnblk)
747 return; /* no work */
749 v = mdopen(reln, forknum, EXTENSION_FAIL);
751 priorblocks = 0;
752 while (v != NULL)
754 MdfdVec *ov = v;
756 if (priorblocks > nblocks)
759 * This segment is no longer active (and has already been unlinked
760 * from the mdfd_chain). We truncate the file, but do not delete
761 * it, for reasons explained in the header comments.
763 if (FileTruncate(v->mdfd_vfd, 0) < 0)
764 ereport(ERROR,
765 (errcode_for_file_access(),
766 errmsg("could not truncate relation %s to %u blocks: %m",
767 relpath(reln->smgr_rnode, forknum),
768 nblocks)));
769 if (!isTemp)
770 register_dirty_segment(reln, forknum, v);
771 v = v->mdfd_chain;
772 Assert(ov != reln->md_fd[forknum]); /* we never drop the 1st segment */
773 pfree(ov);
775 else if (priorblocks + ((BlockNumber) RELSEG_SIZE) > nblocks)
778 * This is the last segment we want to keep. Truncate the file to
779 * the right length, and clear chain link that points to any
780 * remaining segments (which we shall zap). NOTE: if nblocks is
781 * exactly a multiple K of RELSEG_SIZE, we will truncate the K+1st
782 * segment to 0 length but keep it. This adheres to the invariant
783 * given in the header comments.
785 BlockNumber lastsegblocks = nblocks - priorblocks;
787 if (FileTruncate(v->mdfd_vfd, (off_t) lastsegblocks * BLCKSZ) < 0)
788 ereport(ERROR,
789 (errcode_for_file_access(),
790 errmsg("could not truncate relation %s to %u blocks: %m",
791 relpath(reln->smgr_rnode, forknum),
792 nblocks)));
793 if (!isTemp)
794 register_dirty_segment(reln, forknum, v);
795 v = v->mdfd_chain;
796 ov->mdfd_chain = NULL;
798 else
801 * We still need this segment and 0 or more blocks beyond it, so
802 * nothing to do here.
804 v = v->mdfd_chain;
806 priorblocks += RELSEG_SIZE;
811 * mdimmedsync() -- Immediately sync a relation to stable storage.
813 * Note that only writes already issued are synced; this routine knows
814 * nothing of dirty buffers that may exist inside the buffer manager.
816 void
817 mdimmedsync(SMgrRelation reln, ForkNumber forknum)
819 MdfdVec *v;
820 BlockNumber curnblk;
823 * NOTE: mdnblocks makes sure we have opened all active segments, so that
824 * fsync loop will get them all!
826 curnblk = mdnblocks(reln, forknum);
828 v = mdopen(reln, forknum, EXTENSION_FAIL);
830 while (v != NULL)
832 if (FileSync(v->mdfd_vfd) < 0)
833 ereport(ERROR,
834 (errcode_for_file_access(),
835 errmsg("could not fsync segment %u of relation %s: %m",
836 v->mdfd_segno,
837 relpath(reln->smgr_rnode, forknum))));
838 v = v->mdfd_chain;
843 * mdsync() -- Sync previous writes to stable storage.
845 void
846 mdsync(void)
848 static bool mdsync_in_progress = false;
850 HASH_SEQ_STATUS hstat;
851 PendingOperationEntry *entry;
852 int absorb_counter;
855 * This is only called during checkpoints, and checkpoints should only
856 * occur in processes that have created a pendingOpsTable.
858 if (!pendingOpsTable)
859 elog(ERROR, "cannot sync without a pendingOpsTable");
862 * If we are in the bgwriter, the sync had better include all fsync
863 * requests that were queued by backends up to this point. The tightest
864 * race condition that could occur is that a buffer that must be written
865 * and fsync'd for the checkpoint could have been dumped by a backend just
866 * before it was visited by BufferSync(). We know the backend will have
867 * queued an fsync request before clearing the buffer's dirtybit, so we
868 * are safe as long as we do an Absorb after completing BufferSync().
870 AbsorbFsyncRequests();
873 * To avoid excess fsync'ing (in the worst case, maybe a never-terminating
874 * checkpoint), we want to ignore fsync requests that are entered into the
875 * hashtable after this point --- they should be processed next time,
876 * instead. We use mdsync_cycle_ctr to tell old entries apart from new
877 * ones: new ones will have cycle_ctr equal to the incremented value of
878 * mdsync_cycle_ctr.
880 * In normal circumstances, all entries present in the table at this point
881 * will have cycle_ctr exactly equal to the current (about to be old)
882 * value of mdsync_cycle_ctr. However, if we fail partway through the
883 * fsync'ing loop, then older values of cycle_ctr might remain when we
884 * come back here to try again. Repeated checkpoint failures would
885 * eventually wrap the counter around to the point where an old entry
886 * might appear new, causing us to skip it, possibly allowing a checkpoint
887 * to succeed that should not have. To forestall wraparound, any time the
888 * previous mdsync() failed to complete, run through the table and
889 * forcibly set cycle_ctr = mdsync_cycle_ctr.
891 * Think not to merge this loop with the main loop, as the problem is
892 * exactly that that loop may fail before having visited all the entries.
893 * From a performance point of view it doesn't matter anyway, as this path
894 * will never be taken in a system that's functioning normally.
896 if (mdsync_in_progress)
898 /* prior try failed, so update any stale cycle_ctr values */
899 hash_seq_init(&hstat, pendingOpsTable);
900 while ((entry = (PendingOperationEntry *) hash_seq_search(&hstat)) != NULL)
902 entry->cycle_ctr = mdsync_cycle_ctr;
906 /* Advance counter so that new hashtable entries are distinguishable */
907 mdsync_cycle_ctr++;
909 /* Set flag to detect failure if we don't reach the end of the loop */
910 mdsync_in_progress = true;
912 /* Now scan the hashtable for fsync requests to process */
913 absorb_counter = FSYNCS_PER_ABSORB;
914 hash_seq_init(&hstat, pendingOpsTable);
915 while ((entry = (PendingOperationEntry *) hash_seq_search(&hstat)) != NULL)
918 * If the entry is new then don't process it this time. Note that
919 * "continue" bypasses the hash-remove call at the bottom of the loop.
921 if (entry->cycle_ctr == mdsync_cycle_ctr)
922 continue;
924 /* Else assert we haven't missed it */
925 Assert((CycleCtr) (entry->cycle_ctr + 1) == mdsync_cycle_ctr);
928 * If fsync is off then we don't have to bother opening the file at
929 * all. (We delay checking until this point so that changing fsync on
930 * the fly behaves sensibly.) Also, if the entry is marked canceled,
931 * fall through to delete it.
933 if (enableFsync && !entry->canceled)
935 int failures;
938 * If in bgwriter, we want to absorb pending requests every so
939 * often to prevent overflow of the fsync request queue. It is
940 * unspecified whether newly-added entries will be visited by
941 * hash_seq_search, but we don't care since we don't need to
942 * process them anyway.
944 if (--absorb_counter <= 0)
946 AbsorbFsyncRequests();
947 absorb_counter = FSYNCS_PER_ABSORB;
951 * The fsync table could contain requests to fsync segments that
952 * have been deleted (unlinked) by the time we get to them. Rather
953 * than just hoping an ENOENT (or EACCES on Windows) error can be
954 * ignored, what we do on error is absorb pending requests and
955 * then retry. Since mdunlink() queues a "revoke" message before
956 * actually unlinking, the fsync request is guaranteed to be
957 * marked canceled after the absorb if it really was this case.
958 * DROP DATABASE likewise has to tell us to forget fsync requests
959 * before it starts deletions.
961 for (failures = 0;; failures++) /* loop exits at "break" */
963 SMgrRelation reln;
964 MdfdVec *seg;
965 char *path;
968 * Find or create an smgr hash entry for this relation. This
969 * may seem a bit unclean -- md calling smgr? But it's really
970 * the best solution. It ensures that the open file reference
971 * isn't permanently leaked if we get an error here. (You may
972 * say "but an unreferenced SMgrRelation is still a leak!" Not
973 * really, because the only case in which a checkpoint is done
974 * by a process that isn't about to shut down is in the
975 * bgwriter, and it will periodically do smgrcloseall(). This
976 * fact justifies our not closing the reln in the success path
977 * either, which is a good thing since in non-bgwriter cases
978 * we couldn't safely do that.) Furthermore, in many cases
979 * the relation will have been dirtied through this same smgr
980 * relation, and so we can save a file open/close cycle.
982 reln = smgropen(entry->tag.rnode);
985 * It is possible that the relation has been dropped or
986 * truncated since the fsync request was entered. Therefore,
987 * allow ENOENT, but only if we didn't fail already on this
988 * file. This applies both during _mdfd_getseg() and during
989 * FileSync, since fd.c might have closed the file behind our
990 * back.
992 seg = _mdfd_getseg(reln, entry->tag.forknum,
993 entry->tag.segno * ((BlockNumber) RELSEG_SIZE),
994 false, EXTENSION_RETURN_NULL);
995 if (seg != NULL &&
996 FileSync(seg->mdfd_vfd) >= 0)
997 break; /* success; break out of retry loop */
1000 * XXX is there any point in allowing more than one retry?
1001 * Don't see one at the moment, but easy to change the test
1002 * here if so.
1004 path = relpath(entry->tag.rnode, entry->tag.forknum);
1005 if (!FILE_POSSIBLY_DELETED(errno) ||
1006 failures > 0)
1007 ereport(ERROR,
1008 (errcode_for_file_access(),
1009 errmsg("could not fsync segment %u of relation %s: %m",
1010 entry->tag.segno, path)));
1011 else
1012 ereport(DEBUG1,
1013 (errcode_for_file_access(),
1014 errmsg("could not fsync segment %u of relation %s but retrying: %m",
1015 entry->tag.segno, path)));
1016 pfree(path);
1019 * Absorb incoming requests and check to see if canceled.
1021 AbsorbFsyncRequests();
1022 absorb_counter = FSYNCS_PER_ABSORB; /* might as well... */
1024 if (entry->canceled)
1025 break;
1026 } /* end retry loop */
1030 * If we get here, either we fsync'd successfully, or we don't have to
1031 * because enableFsync is off, or the entry is (now) marked canceled.
1032 * Okay to delete it.
1034 if (hash_search(pendingOpsTable, &entry->tag,
1035 HASH_REMOVE, NULL) == NULL)
1036 elog(ERROR, "pendingOpsTable corrupted");
1037 } /* end loop over hashtable entries */
1039 /* Flag successful completion of mdsync */
1040 mdsync_in_progress = false;
1044 * mdpreckpt() -- Do pre-checkpoint work
1046 * To distinguish unlink requests that arrived before this checkpoint
1047 * started from those that arrived during the checkpoint, we use a cycle
1048 * counter similar to the one we use for fsync requests. That cycle
1049 * counter is incremented here.
1051 * This must be called *before* the checkpoint REDO point is determined.
1052 * That ensures that we won't delete files too soon.
1054 * Note that we can't do anything here that depends on the assumption
1055 * that the checkpoint will be completed.
1057 void
1058 mdpreckpt(void)
1060 ListCell *cell;
1063 * In case the prior checkpoint wasn't completed, stamp all entries in the
1064 * list with the current cycle counter. Anything that's in the list at
1065 * the start of checkpoint can surely be deleted after the checkpoint is
1066 * finished, regardless of when the request was made.
1068 foreach(cell, pendingUnlinks)
1070 PendingUnlinkEntry *entry = (PendingUnlinkEntry *) lfirst(cell);
1072 entry->cycle_ctr = mdckpt_cycle_ctr;
1076 * Any unlink requests arriving after this point will be assigned the next
1077 * cycle counter, and won't be unlinked until next checkpoint.
1079 mdckpt_cycle_ctr++;
1083 * mdpostckpt() -- Do post-checkpoint work
1085 * Remove any lingering files that can now be safely removed.
1087 void
1088 mdpostckpt(void)
1090 while (pendingUnlinks != NIL)
1092 PendingUnlinkEntry *entry = (PendingUnlinkEntry *) linitial(pendingUnlinks);
1093 char *path;
1096 * New entries are appended to the end, so if the entry is new we've
1097 * reached the end of old entries.
1099 if (entry->cycle_ctr == mdckpt_cycle_ctr)
1100 break;
1102 /* Else assert we haven't missed it */
1103 Assert((CycleCtr) (entry->cycle_ctr + 1) == mdckpt_cycle_ctr);
1105 /* Unlink the file */
1106 path = relpath(entry->rnode, MAIN_FORKNUM);
1107 if (unlink(path) < 0)
1110 * There's a race condition, when the database is dropped at the
1111 * same time that we process the pending unlink requests. If the
1112 * DROP DATABASE deletes the file before we do, we will get ENOENT
1113 * here. rmtree() also has to ignore ENOENT errors, to deal with
1114 * the possibility that we delete the file first.
1116 if (errno != ENOENT)
1117 ereport(WARNING,
1118 (errcode_for_file_access(),
1119 errmsg("could not remove relation %s: %m", path)));
1121 pfree(path);
1123 pendingUnlinks = list_delete_first(pendingUnlinks);
1124 pfree(entry);
1129 * register_dirty_segment() -- Mark a relation segment as needing fsync
1131 * If there is a local pending-ops table, just make an entry in it for
1132 * mdsync to process later. Otherwise, try to pass off the fsync request
1133 * to the background writer process. If that fails, just do the fsync
1134 * locally before returning (we expect this will not happen often enough
1135 * to be a performance problem).
1137 static void
1138 register_dirty_segment(SMgrRelation reln, ForkNumber forknum, MdfdVec *seg)
1140 if (pendingOpsTable)
1142 /* push it into local pending-ops table */
1143 RememberFsyncRequest(reln->smgr_rnode, forknum, seg->mdfd_segno);
1145 else
1147 if (ForwardFsyncRequest(reln->smgr_rnode, forknum, seg->mdfd_segno))
1148 return; /* passed it off successfully */
1150 if (FileSync(seg->mdfd_vfd) < 0)
1151 ereport(ERROR,
1152 (errcode_for_file_access(),
1153 errmsg("could not fsync segment %u of relation %s: %m",
1154 seg->mdfd_segno,
1155 relpath(reln->smgr_rnode, forknum))));
1160 * register_unlink() -- Schedule a file to be deleted after next checkpoint
1162 * As with register_dirty_segment, this could involve either a local or
1163 * a remote pending-ops table.
1165 static void
1166 register_unlink(RelFileNode rnode)
1168 if (pendingOpsTable)
1170 /* push it into local pending-ops table */
1171 RememberFsyncRequest(rnode, MAIN_FORKNUM, UNLINK_RELATION_REQUEST);
1173 else
1176 * Notify the bgwriter about it. If we fail to queue the request
1177 * message, we have to sleep and try again, because we can't simply
1178 * delete the file now. Ugly, but hopefully won't happen often.
1180 * XXX should we just leave the file orphaned instead?
1182 Assert(IsUnderPostmaster);
1183 while (!ForwardFsyncRequest(rnode, MAIN_FORKNUM,
1184 UNLINK_RELATION_REQUEST))
1185 pg_usleep(10000L); /* 10 msec seems a good number */
1190 * RememberFsyncRequest() -- callback from bgwriter side of fsync request
1192 * We stuff most fsync requests into the local hash table for execution
1193 * during the bgwriter's next checkpoint. UNLINK requests go into a
1194 * separate linked list, however, because they get processed separately.
1196 * The range of possible segment numbers is way less than the range of
1197 * BlockNumber, so we can reserve high values of segno for special purposes.
1198 * We define three:
1199 * - FORGET_RELATION_FSYNC means to cancel pending fsyncs for a relation
1200 * - FORGET_DATABASE_FSYNC means to cancel pending fsyncs for a whole database
1201 * - UNLINK_RELATION_REQUEST is a request to delete the file after the next
1202 * checkpoint.
1204 * (Handling the FORGET_* requests is a tad slow because the hash table has
1205 * to be searched linearly, but it doesn't seem worth rethinking the table
1206 * structure for them.)
1208 void
1209 RememberFsyncRequest(RelFileNode rnode, ForkNumber forknum, BlockNumber segno)
1211 Assert(pendingOpsTable);
1213 if (segno == FORGET_RELATION_FSYNC)
1215 /* Remove any pending requests for the entire relation */
1216 HASH_SEQ_STATUS hstat;
1217 PendingOperationEntry *entry;
1219 hash_seq_init(&hstat, pendingOpsTable);
1220 while ((entry = (PendingOperationEntry *) hash_seq_search(&hstat)) != NULL)
1222 if (RelFileNodeEquals(entry->tag.rnode, rnode) &&
1223 entry->tag.forknum == forknum)
1225 /* Okay, cancel this entry */
1226 entry->canceled = true;
1230 else if (segno == FORGET_DATABASE_FSYNC)
1232 /* Remove any pending requests for the entire database */
1233 HASH_SEQ_STATUS hstat;
1234 PendingOperationEntry *entry;
1235 ListCell *cell,
1236 *prev,
1237 *next;
1239 /* Remove fsync requests */
1240 hash_seq_init(&hstat, pendingOpsTable);
1241 while ((entry = (PendingOperationEntry *) hash_seq_search(&hstat)) != NULL)
1243 if (entry->tag.rnode.dbNode == rnode.dbNode)
1245 /* Okay, cancel this entry */
1246 entry->canceled = true;
1250 /* Remove unlink requests */
1251 prev = NULL;
1252 for (cell = list_head(pendingUnlinks); cell; cell = next)
1254 PendingUnlinkEntry *entry = (PendingUnlinkEntry *) lfirst(cell);
1256 next = lnext(cell);
1257 if (entry->rnode.dbNode == rnode.dbNode)
1259 pendingUnlinks = list_delete_cell(pendingUnlinks, cell, prev);
1260 pfree(entry);
1262 else
1263 prev = cell;
1266 else if (segno == UNLINK_RELATION_REQUEST)
1268 /* Unlink request: put it in the linked list */
1269 MemoryContext oldcxt = MemoryContextSwitchTo(MdCxt);
1270 PendingUnlinkEntry *entry;
1272 entry = palloc(sizeof(PendingUnlinkEntry));
1273 entry->rnode = rnode;
1274 entry->cycle_ctr = mdckpt_cycle_ctr;
1276 pendingUnlinks = lappend(pendingUnlinks, entry);
1278 MemoryContextSwitchTo(oldcxt);
1280 else
1282 /* Normal case: enter a request to fsync this segment */
1283 PendingOperationTag key;
1284 PendingOperationEntry *entry;
1285 bool found;
1287 /* ensure any pad bytes in the hash key are zeroed */
1288 MemSet(&key, 0, sizeof(key));
1289 key.rnode = rnode;
1290 key.forknum = forknum;
1291 key.segno = segno;
1293 entry = (PendingOperationEntry *) hash_search(pendingOpsTable,
1294 &key,
1295 HASH_ENTER,
1296 &found);
1297 /* if new or previously canceled entry, initialize it */
1298 if (!found || entry->canceled)
1300 entry->canceled = false;
1301 entry->cycle_ctr = mdsync_cycle_ctr;
1305 * NB: it's intentional that we don't change cycle_ctr if the entry
1306 * already exists. The fsync request must be treated as old, even
1307 * though the new request will be satisfied too by any subsequent
1308 * fsync.
1310 * However, if the entry is present but is marked canceled, we should
1311 * act just as though it wasn't there. The only case where this could
1312 * happen would be if a file had been deleted, we received but did not
1313 * yet act on the cancel request, and the same relfilenode was then
1314 * assigned to a new file. We mustn't lose the new request, but it
1315 * should be considered new not old.
1321 * ForgetRelationFsyncRequests -- forget any fsyncs for a rel
1323 void
1324 ForgetRelationFsyncRequests(RelFileNode rnode, ForkNumber forknum)
1326 if (pendingOpsTable)
1328 /* standalone backend or startup process: fsync state is local */
1329 RememberFsyncRequest(rnode, forknum, FORGET_RELATION_FSYNC);
1331 else if (IsUnderPostmaster)
1334 * Notify the bgwriter about it. If we fail to queue the revoke
1335 * message, we have to sleep and try again ... ugly, but hopefully
1336 * won't happen often.
1338 * XXX should we CHECK_FOR_INTERRUPTS in this loop? Escaping with an
1339 * error would leave the no-longer-used file still present on disk,
1340 * which would be bad, so I'm inclined to assume that the bgwriter
1341 * will always empty the queue soon.
1343 while (!ForwardFsyncRequest(rnode, forknum, FORGET_RELATION_FSYNC))
1344 pg_usleep(10000L); /* 10 msec seems a good number */
1347 * Note we don't wait for the bgwriter to actually absorb the revoke
1348 * message; see mdsync() for the implications.
1354 * ForgetDatabaseFsyncRequests -- forget any fsyncs and unlinks for a DB
1356 void
1357 ForgetDatabaseFsyncRequests(Oid dbid)
1359 RelFileNode rnode;
1361 rnode.dbNode = dbid;
1362 rnode.spcNode = 0;
1363 rnode.relNode = 0;
1365 if (pendingOpsTable)
1367 /* standalone backend or startup process: fsync state is local */
1368 RememberFsyncRequest(rnode, InvalidForkNumber, FORGET_DATABASE_FSYNC);
1370 else if (IsUnderPostmaster)
1372 /* see notes in ForgetRelationFsyncRequests */
1373 while (!ForwardFsyncRequest(rnode, InvalidForkNumber,
1374 FORGET_DATABASE_FSYNC))
1375 pg_usleep(10000L); /* 10 msec seems a good number */
1381 * _fdvec_alloc() -- Make a MdfdVec object.
1383 static MdfdVec *
1384 _fdvec_alloc(void)
1386 return (MdfdVec *) MemoryContextAlloc(MdCxt, sizeof(MdfdVec));
1390 * Open the specified segment of the relation,
1391 * and make a MdfdVec object for it. Returns NULL on failure.
1393 static MdfdVec *
1394 _mdfd_openseg(SMgrRelation reln, ForkNumber forknum, BlockNumber segno,
1395 int oflags)
1397 MdfdVec *v;
1398 int fd;
1399 char *path,
1400 *fullpath;
1402 path = relpath(reln->smgr_rnode, forknum);
1404 if (segno > 0)
1406 /* be sure we have enough space for the '.segno' */
1407 fullpath = (char *) palloc(strlen(path) + 12);
1408 sprintf(fullpath, "%s.%u", path, segno);
1409 pfree(path);
1411 else
1412 fullpath = path;
1414 /* open the file */
1415 fd = PathNameOpenFile(fullpath, O_RDWR | PG_BINARY | oflags, 0600);
1417 pfree(fullpath);
1419 if (fd < 0)
1420 return NULL;
1422 /* allocate an mdfdvec entry for it */
1423 v = _fdvec_alloc();
1425 /* fill the entry */
1426 v->mdfd_vfd = fd;
1427 v->mdfd_segno = segno;
1428 v->mdfd_chain = NULL;
1429 Assert(_mdnblocks(reln, forknum, v) <= ((BlockNumber) RELSEG_SIZE));
1431 /* all done */
1432 return v;
1436 * _mdfd_getseg() -- Find the segment of the relation holding the
1437 * specified block.
1439 * If the segment doesn't exist, we ereport, return NULL, or create the
1440 * segment, according to "behavior". Note: isTemp need only be correct
1441 * in the EXTENSION_CREATE case.
1443 static MdfdVec *
1444 _mdfd_getseg(SMgrRelation reln, ForkNumber forknum, BlockNumber blkno,
1445 bool isTemp, ExtensionBehavior behavior)
1447 MdfdVec *v = mdopen(reln, forknum, behavior);
1448 BlockNumber targetseg;
1449 BlockNumber nextsegno;
1451 if (!v)
1452 return NULL; /* only possible if EXTENSION_RETURN_NULL */
1454 targetseg = blkno / ((BlockNumber) RELSEG_SIZE);
1455 for (nextsegno = 1; nextsegno <= targetseg; nextsegno++)
1457 Assert(nextsegno == v->mdfd_segno + 1);
1459 if (v->mdfd_chain == NULL)
1462 * Normally we will create new segments only if authorized by the
1463 * caller (i.e., we are doing mdextend()). But when doing WAL
1464 * recovery, create segments anyway; this allows cases such as
1465 * replaying WAL data that has a write into a high-numbered
1466 * segment of a relation that was later deleted. We want to go
1467 * ahead and create the segments so we can finish out the replay.
1469 * We have to maintain the invariant that segments before the last
1470 * active segment are of size RELSEG_SIZE; therefore, pad them out
1471 * with zeroes if needed. (This only matters if caller is
1472 * extending the relation discontiguously, but that can happen in
1473 * hash indexes.)
1475 if (behavior == EXTENSION_CREATE || InRecovery)
1477 if (_mdnblocks(reln, forknum, v) < RELSEG_SIZE)
1479 char *zerobuf = palloc0(BLCKSZ);
1481 mdextend(reln, forknum,
1482 nextsegno * ((BlockNumber) RELSEG_SIZE) - 1,
1483 zerobuf, isTemp);
1484 pfree(zerobuf);
1486 v->mdfd_chain = _mdfd_openseg(reln, forknum, +nextsegno, O_CREAT);
1488 else
1490 /* We won't create segment if not existent */
1491 v->mdfd_chain = _mdfd_openseg(reln, forknum, nextsegno, 0);
1493 if (v->mdfd_chain == NULL)
1495 if (behavior == EXTENSION_RETURN_NULL &&
1496 FILE_POSSIBLY_DELETED(errno))
1497 return NULL;
1498 ereport(ERROR,
1499 (errcode_for_file_access(),
1500 errmsg("could not open segment %u of relation %s (target block %u): %m",
1501 nextsegno,
1502 relpath(reln->smgr_rnode, forknum),
1503 blkno)));
1506 v = v->mdfd_chain;
1508 return v;
1512 * Get number of blocks present in a single disk file
1514 static BlockNumber
1515 _mdnblocks(SMgrRelation reln, ForkNumber forknum, MdfdVec *seg)
1517 off_t len;
1519 len = FileSeek(seg->mdfd_vfd, 0L, SEEK_END);
1520 if (len < 0)
1521 ereport(ERROR,
1522 (errcode_for_file_access(),
1523 errmsg("could not seek to end of segment %u of relation %s: %m",
1524 seg->mdfd_segno, relpath(reln->smgr_rnode, forknum))));
1525 /* note that this calculation will ignore any partial block at EOF */
1526 return (BlockNumber) (len / BLCKSZ);