]> granicus.if.org Git - postgresql/blob - src/backend/storage/smgr/md.c
Instrument checkpoint sync calls.
[postgresql] / src / backend / storage / smgr / md.c
1 /*-------------------------------------------------------------------------
2  *
3  * md.c
4  *        This code manages relations that reside on magnetic disk.
5  *
6  * Portions Copyright (c) 1996-2010, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  *        src/backend/storage/smgr/md.c
12  *
13  *-------------------------------------------------------------------------
14  */
15 #include "postgres.h"
16
17 #include <unistd.h>
18 #include <fcntl.h>
19 #include <sys/file.h>
20
21 #include "catalog/catalog.h"
22 #include "miscadmin.h"
23 #include "portability/instr_time.h"
24 #include "postmaster/bgwriter.h"
25 #include "storage/fd.h"
26 #include "storage/bufmgr.h"
27 #include "storage/relfilenode.h"
28 #include "storage/smgr.h"
29 #include "utils/hsearch.h"
30 #include "utils/memutils.h"
31 #include "pg_trace.h"
32
33
34 /* interval for calling AbsorbFsyncRequests in mdsync */
35 #define FSYNCS_PER_ABSORB               10
36
37 /* special values for the segno arg to RememberFsyncRequest */
38 #define FORGET_RELATION_FSYNC   (InvalidBlockNumber)
39 #define FORGET_DATABASE_FSYNC   (InvalidBlockNumber-1)
40 #define UNLINK_RELATION_REQUEST (InvalidBlockNumber-2)
41
42 /*
43  * On Windows, we have to interpret EACCES as possibly meaning the same as
44  * ENOENT, because if a file is unlinked-but-not-yet-gone on that platform,
45  * that's what you get.  Ugh.  This code is designed so that we don't
46  * actually believe these cases are okay without further evidence (namely,
47  * a pending fsync request getting revoked ... see mdsync).
48  */
49 #ifndef WIN32
50 #define FILE_POSSIBLY_DELETED(err)      ((err) == ENOENT)
51 #else
52 #define FILE_POSSIBLY_DELETED(err)      ((err) == ENOENT || (err) == EACCES)
53 #endif
54
55 /*
56  *      The magnetic disk storage manager keeps track of open file
57  *      descriptors in its own descriptor pool.  This is done to make it
58  *      easier to support relations that are larger than the operating
59  *      system's file size limit (often 2GBytes).  In order to do that,
60  *      we break relations up into "segment" files that are each shorter than
61  *      the OS file size limit.  The segment size is set by the RELSEG_SIZE
62  *      configuration constant in pg_config.h.
63  *
64  *      On disk, a relation must consist of consecutively numbered segment
65  *      files in the pattern
66  *              -- Zero or more full segments of exactly RELSEG_SIZE blocks each
67  *              -- Exactly one partial segment of size 0 <= size < RELSEG_SIZE blocks
68  *              -- Optionally, any number of inactive segments of size 0 blocks.
69  *      The full and partial segments are collectively the "active" segments.
70  *      Inactive segments are those that once contained data but are currently
71  *      not needed because of an mdtruncate() operation.  The reason for leaving
72  *      them present at size zero, rather than unlinking them, is that other
73  *      backends and/or the bgwriter might be holding open file references to
74  *      such segments.  If the relation expands again after mdtruncate(), such
75  *      that a deactivated segment becomes active again, it is important that
76  *      such file references still be valid --- else data might get written
77  *      out to an unlinked old copy of a segment file that will eventually
78  *      disappear.
79  *
80  *      The file descriptor pointer (md_fd field) stored in the SMgrRelation
81  *      cache is, therefore, just the head of a list of MdfdVec objects, one
82  *      per segment.  But note the md_fd pointer can be NULL, indicating
83  *      relation not open.
84  *
85  *      Also note that mdfd_chain == NULL does not necessarily mean the relation
86  *      doesn't have another segment after this one; we may just not have
87  *      opened the next segment yet.  (We could not have "all segments are
88  *      in the chain" as an invariant anyway, since another backend could
89  *      extend the relation when we weren't looking.)  We do not make chain
90  *      entries for inactive segments, however; as soon as we find a partial
91  *      segment, we assume that any subsequent segments are inactive.
92  *
93  *      All MdfdVec objects are palloc'd in the MdCxt memory context.
94  */
95
96 typedef struct _MdfdVec
97 {
98         File            mdfd_vfd;               /* fd number in fd.c's pool */
99         BlockNumber mdfd_segno;         /* segment number, from 0 */
100         struct _MdfdVec *mdfd_chain;    /* next segment, or NULL */
101 } MdfdVec;
102
103 static MemoryContext MdCxt;             /* context for all md.c allocations */
104
105
106 /*
107  * In some contexts (currently, standalone backends and the bgwriter process)
108  * we keep track of pending fsync operations: we need to remember all relation
109  * segments that have been written since the last checkpoint, so that we can
110  * fsync them down to disk before completing the next checkpoint.  This hash
111  * table remembers the pending operations.      We use a hash table mostly as
112  * a convenient way of eliminating duplicate requests.
113  *
114  * We use a similar mechanism to remember no-longer-needed files that can
115  * be deleted after the next checkpoint, but we use a linked list instead of
116  * a hash table, because we don't expect there to be any duplicate requests.
117  *
118  * (Regular backends do not track pending operations locally, but forward
119  * them to the bgwriter.)
120  */
121 typedef struct
122 {
123         RelFileNodeBackend rnode;       /* the targeted relation */
124         ForkNumber      forknum;
125         BlockNumber segno;                      /* which segment */
126 } PendingOperationTag;
127
128 typedef uint16 CycleCtr;                /* can be any convenient integer size */
129
130 typedef struct
131 {
132         PendingOperationTag tag;        /* hash table key (must be first!) */
133         bool            canceled;               /* T => request canceled, not yet removed */
134         CycleCtr        cycle_ctr;              /* mdsync_cycle_ctr when request was made */
135 } PendingOperationEntry;
136
137 typedef struct
138 {
139         RelFileNodeBackend rnode;       /* the dead relation to delete */
140         CycleCtr        cycle_ctr;              /* mdckpt_cycle_ctr when request was made */
141 } PendingUnlinkEntry;
142
143 static HTAB *pendingOpsTable = NULL;
144 static List *pendingUnlinks = NIL;
145
146 static CycleCtr mdsync_cycle_ctr = 0;
147 static CycleCtr mdckpt_cycle_ctr = 0;
148
149
150 typedef enum                                    /* behavior for mdopen & _mdfd_getseg */
151 {
152         EXTENSION_FAIL,                         /* ereport if segment not present */
153         EXTENSION_RETURN_NULL,          /* return NULL if not present */
154         EXTENSION_CREATE                        /* create new segments as needed */
155 } ExtensionBehavior;
156
157 /* local routines */
158 static MdfdVec *mdopen(SMgrRelation reln, ForkNumber forknum,
159            ExtensionBehavior behavior);
160 static void register_dirty_segment(SMgrRelation reln, ForkNumber forknum,
161                                            MdfdVec *seg);
162 static void register_unlink(RelFileNodeBackend rnode);
163 static MdfdVec *_fdvec_alloc(void);
164 static char *_mdfd_segpath(SMgrRelation reln, ForkNumber forknum,
165                           BlockNumber segno);
166 static MdfdVec *_mdfd_openseg(SMgrRelation reln, ForkNumber forkno,
167                           BlockNumber segno, int oflags);
168 static MdfdVec *_mdfd_getseg(SMgrRelation reln, ForkNumber forkno,
169                          BlockNumber blkno, bool skipFsync, ExtensionBehavior behavior);
170 static BlockNumber _mdnblocks(SMgrRelation reln, ForkNumber forknum,
171                    MdfdVec *seg);
172
173
174 /*
175  *      mdinit() -- Initialize private state for magnetic disk storage manager.
176  */
177 void
178 mdinit(void)
179 {
180         MdCxt = AllocSetContextCreate(TopMemoryContext,
181                                                                   "MdSmgr",
182                                                                   ALLOCSET_DEFAULT_MINSIZE,
183                                                                   ALLOCSET_DEFAULT_INITSIZE,
184                                                                   ALLOCSET_DEFAULT_MAXSIZE);
185
186         /*
187          * Create pending-operations hashtable if we need it.  Currently, we need
188          * it if we are standalone (not under a postmaster) OR if we are a
189          * bootstrap-mode subprocess of a postmaster (that is, a startup or
190          * bgwriter process).
191          */
192         if (!IsUnderPostmaster || IsBootstrapProcessingMode())
193         {
194                 HASHCTL         hash_ctl;
195
196                 MemSet(&hash_ctl, 0, sizeof(hash_ctl));
197                 hash_ctl.keysize = sizeof(PendingOperationTag);
198                 hash_ctl.entrysize = sizeof(PendingOperationEntry);
199                 hash_ctl.hash = tag_hash;
200                 hash_ctl.hcxt = MdCxt;
201                 pendingOpsTable = hash_create("Pending Ops Table",
202                                                                           100L,
203                                                                           &hash_ctl,
204                                                                    HASH_ELEM | HASH_FUNCTION | HASH_CONTEXT);
205                 pendingUnlinks = NIL;
206         }
207 }
208
209 /*
210  * In archive recovery, we rely on bgwriter to do fsyncs, but we will have
211  * already created the pendingOpsTable during initialization of the startup
212  * process.  Calling this function drops the local pendingOpsTable so that
213  * subsequent requests will be forwarded to bgwriter.
214  */
215 void
216 SetForwardFsyncRequests(void)
217 {
218         /* Perform any pending ops we may have queued up */
219         if (pendingOpsTable)
220                 mdsync();
221         pendingOpsTable = NULL;
222 }
223
224 /*
225  *      mdexists() -- Does the physical file exist?
226  *
227  * Note: this will return true for lingering files, with pending deletions
228  */
229 bool
230 mdexists(SMgrRelation reln, ForkNumber forkNum)
231 {
232         /*
233          * Close it first, to ensure that we notice if the fork has been unlinked
234          * since we opened it.
235          */
236         mdclose(reln, forkNum);
237
238         return (mdopen(reln, forkNum, EXTENSION_RETURN_NULL) != NULL);
239 }
240
241 /*
242  *      mdcreate() -- Create a new relation on magnetic disk.
243  *
244  * If isRedo is true, it's okay for the relation to exist already.
245  */
246 void
247 mdcreate(SMgrRelation reln, ForkNumber forkNum, bool isRedo)
248 {
249         char       *path;
250         File            fd;
251
252         if (isRedo && reln->md_fd[forkNum] != NULL)
253                 return;                                 /* created and opened already... */
254
255         Assert(reln->md_fd[forkNum] == NULL);
256
257         path = relpath(reln->smgr_rnode, forkNum);
258
259         fd = PathNameOpenFile(path, O_RDWR | O_CREAT | O_EXCL | PG_BINARY, 0600);
260
261         if (fd < 0)
262         {
263                 int                     save_errno = errno;
264
265                 /*
266                  * During bootstrap, there are cases where a system relation will be
267                  * accessed (by internal backend processes) before the bootstrap
268                  * script nominally creates it.  Therefore, allow the file to exist
269                  * already, even if isRedo is not set.  (See also mdopen)
270                  */
271                 if (isRedo || IsBootstrapProcessingMode())
272                         fd = PathNameOpenFile(path, O_RDWR | PG_BINARY, 0600);
273                 if (fd < 0)
274                 {
275                         /* be sure to report the error reported by create, not open */
276                         errno = save_errno;
277                         ereport(ERROR,
278                                         (errcode_for_file_access(),
279                                          errmsg("could not create file \"%s\": %m", path)));
280                 }
281         }
282
283         pfree(path);
284
285         reln->md_fd[forkNum] = _fdvec_alloc();
286
287         reln->md_fd[forkNum]->mdfd_vfd = fd;
288         reln->md_fd[forkNum]->mdfd_segno = 0;
289         reln->md_fd[forkNum]->mdfd_chain = NULL;
290 }
291
292 /*
293  *      mdunlink() -- Unlink a relation.
294  *
295  * Note that we're passed a RelFileNode --- by the time this is called,
296  * there won't be an SMgrRelation hashtable entry anymore.
297  *
298  * Actually, we don't unlink the first segment file of the relation, but
299  * just truncate it to zero length, and record a request to unlink it after
300  * the next checkpoint.  Additional segments can be unlinked immediately,
301  * however.  Leaving the empty file in place prevents that relfilenode
302  * number from being reused.  The scenario this protects us from is:
303  * 1. We delete a relation (and commit, and actually remove its file).
304  * 2. We create a new relation, which by chance gets the same relfilenode as
305  *        the just-deleted one (OIDs must've wrapped around for that to happen).
306  * 3. We crash before another checkpoint occurs.
307  * During replay, we would delete the file and then recreate it, which is fine
308  * if the contents of the file were repopulated by subsequent WAL entries.
309  * But if we didn't WAL-log insertions, but instead relied on fsyncing the
310  * file after populating it (as for instance CLUSTER and CREATE INDEX do),
311  * the contents of the file would be lost forever.      By leaving the empty file
312  * until after the next checkpoint, we prevent reassignment of the relfilenode
313  * number until it's safe, because relfilenode assignment skips over any
314  * existing file.
315  *
316  * If isRedo is true, it's okay for the relation to be already gone.
317  * Also, we should remove the file immediately instead of queuing a request
318  * for later, since during redo there's no possibility of creating a
319  * conflicting relation.
320  *
321  * Note: any failure should be reported as WARNING not ERROR, because
322  * we are usually not in a transaction anymore when this is called.
323  */
324 void
325 mdunlink(RelFileNodeBackend rnode, ForkNumber forkNum, bool isRedo)
326 {
327         char       *path;
328         int                     ret;
329
330         /*
331          * We have to clean out any pending fsync requests for the doomed
332          * relation, else the next mdsync() will fail.
333          */
334         ForgetRelationFsyncRequests(rnode, forkNum);
335
336         path = relpath(rnode, forkNum);
337
338         /*
339          * Delete or truncate the first segment.
340          */
341         if (isRedo || forkNum != MAIN_FORKNUM)
342         {
343                 ret = unlink(path);
344                 if (ret < 0)
345                 {
346                         if (!isRedo || errno != ENOENT)
347                                 ereport(WARNING,
348                                                 (errcode_for_file_access(),
349                                                  errmsg("could not remove file \"%s\": %m", path)));
350                 }
351         }
352         else
353         {
354                 /* truncate(2) would be easier here, but Windows hasn't got it */
355                 int                     fd;
356
357                 fd = BasicOpenFile(path, O_RDWR | PG_BINARY, 0);
358                 if (fd >= 0)
359                 {
360                         int                     save_errno;
361
362                         ret = ftruncate(fd, 0);
363                         save_errno = errno;
364                         close(fd);
365                         errno = save_errno;
366                 }
367                 else
368                         ret = -1;
369                 if (ret < 0 && errno != ENOENT)
370                         ereport(WARNING,
371                                         (errcode_for_file_access(),
372                                          errmsg("could not truncate file \"%s\": %m", path)));
373         }
374
375         /*
376          * Delete any additional segments.
377          */
378         if (ret >= 0)
379         {
380                 char       *segpath = (char *) palloc(strlen(path) + 12);
381                 BlockNumber segno;
382
383                 /*
384                  * Note that because we loop until getting ENOENT, we will correctly
385                  * remove all inactive segments as well as active ones.
386                  */
387                 for (segno = 1;; segno++)
388                 {
389                         sprintf(segpath, "%s.%u", path, segno);
390                         if (unlink(segpath) < 0)
391                         {
392                                 /* ENOENT is expected after the last segment... */
393                                 if (errno != ENOENT)
394                                         ereport(WARNING,
395                                                         (errcode_for_file_access(),
396                                            errmsg("could not remove file \"%s\": %m", segpath)));
397                                 break;
398                         }
399                 }
400                 pfree(segpath);
401         }
402
403         pfree(path);
404
405         /* Register request to unlink first segment later */
406         if (!isRedo && forkNum == MAIN_FORKNUM)
407                 register_unlink(rnode);
408 }
409
410 /*
411  *      mdextend() -- Add a block to the specified relation.
412  *
413  *              The semantics are nearly the same as mdwrite(): write at the
414  *              specified position.  However, this is to be used for the case of
415  *              extending a relation (i.e., blocknum is at or beyond the current
416  *              EOF).  Note that we assume writing a block beyond current EOF
417  *              causes intervening file space to become filled with zeroes.
418  */
419 void
420 mdextend(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum,
421                  char *buffer, bool skipFsync)
422 {
423         off_t           seekpos;
424         int                     nbytes;
425         MdfdVec    *v;
426
427         /* This assert is too expensive to have on normally ... */
428 #ifdef CHECK_WRITE_VS_EXTEND
429         Assert(blocknum >= mdnblocks(reln, forknum));
430 #endif
431
432         /*
433          * If a relation manages to grow to 2^32-1 blocks, refuse to extend it any
434          * more --- we mustn't create a block whose number actually is
435          * InvalidBlockNumber.
436          */
437         if (blocknum == InvalidBlockNumber)
438                 ereport(ERROR,
439                                 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
440                                  errmsg("cannot extend file \"%s\" beyond %u blocks",
441                                                 relpath(reln->smgr_rnode, forknum),
442                                                 InvalidBlockNumber)));
443
444         v = _mdfd_getseg(reln, forknum, blocknum, skipFsync, EXTENSION_CREATE);
445
446         seekpos = (off_t) BLCKSZ *(blocknum % ((BlockNumber) RELSEG_SIZE));
447
448         Assert(seekpos < (off_t) BLCKSZ * RELSEG_SIZE);
449
450         /*
451          * Note: because caller usually obtained blocknum by calling mdnblocks,
452          * which did a seek(SEEK_END), this seek is often redundant and will be
453          * optimized away by fd.c.      It's not redundant, however, if there is a
454          * partial page at the end of the file. In that case we want to try to
455          * overwrite the partial page with a full page.  It's also not redundant
456          * if bufmgr.c had to dump another buffer of the same file to make room
457          * for the new page's buffer.
458          */
459         if (FileSeek(v->mdfd_vfd, seekpos, SEEK_SET) != seekpos)
460                 ereport(ERROR,
461                                 (errcode_for_file_access(),
462                                  errmsg("could not seek to block %u in file \"%s\": %m",
463                                                 blocknum, FilePathName(v->mdfd_vfd))));
464
465         if ((nbytes = FileWrite(v->mdfd_vfd, buffer, BLCKSZ)) != BLCKSZ)
466         {
467                 if (nbytes < 0)
468                         ereport(ERROR,
469                                         (errcode_for_file_access(),
470                                          errmsg("could not extend file \"%s\": %m",
471                                                         FilePathName(v->mdfd_vfd)),
472                                          errhint("Check free disk space.")));
473                 /* short write: complain appropriately */
474                 ereport(ERROR,
475                                 (errcode(ERRCODE_DISK_FULL),
476                                  errmsg("could not extend file \"%s\": wrote only %d of %d bytes at block %u",
477                                                 FilePathName(v->mdfd_vfd),
478                                                 nbytes, BLCKSZ, blocknum),
479                                  errhint("Check free disk space.")));
480         }
481
482         if (!skipFsync && !SmgrIsTemp(reln))
483                 register_dirty_segment(reln, forknum, v);
484
485         Assert(_mdnblocks(reln, forknum, v) <= ((BlockNumber) RELSEG_SIZE));
486 }
487
488 /*
489  *      mdopen() -- Open the specified relation.
490  *
491  * Note we only open the first segment, when there are multiple segments.
492  *
493  * If first segment is not present, either ereport or return NULL according
494  * to "behavior".  We treat EXTENSION_CREATE the same as EXTENSION_FAIL;
495  * EXTENSION_CREATE means it's OK to extend an existing relation, not to
496  * invent one out of whole cloth.
497  */
498 static MdfdVec *
499 mdopen(SMgrRelation reln, ForkNumber forknum, ExtensionBehavior behavior)
500 {
501         MdfdVec    *mdfd;
502         char       *path;
503         File            fd;
504
505         /* No work if already open */
506         if (reln->md_fd[forknum])
507                 return reln->md_fd[forknum];
508
509         path = relpath(reln->smgr_rnode, forknum);
510
511         fd = PathNameOpenFile(path, O_RDWR | PG_BINARY, 0600);
512
513         if (fd < 0)
514         {
515                 /*
516                  * During bootstrap, there are cases where a system relation will be
517                  * accessed (by internal backend processes) before the bootstrap
518                  * script nominally creates it.  Therefore, accept mdopen() as a
519                  * substitute for mdcreate() in bootstrap mode only. (See mdcreate)
520                  */
521                 if (IsBootstrapProcessingMode())
522                         fd = PathNameOpenFile(path, O_RDWR | O_CREAT | O_EXCL | PG_BINARY, 0600);
523                 if (fd < 0)
524                 {
525                         if (behavior == EXTENSION_RETURN_NULL &&
526                                 FILE_POSSIBLY_DELETED(errno))
527                         {
528                                 pfree(path);
529                                 return NULL;
530                         }
531                         ereport(ERROR,
532                                         (errcode_for_file_access(),
533                                          errmsg("could not open file \"%s\": %m", path)));
534                 }
535         }
536
537         pfree(path);
538
539         reln->md_fd[forknum] = mdfd = _fdvec_alloc();
540
541         mdfd->mdfd_vfd = fd;
542         mdfd->mdfd_segno = 0;
543         mdfd->mdfd_chain = NULL;
544         Assert(_mdnblocks(reln, forknum, mdfd) <= ((BlockNumber) RELSEG_SIZE));
545
546         return mdfd;
547 }
548
549 /*
550  *      mdclose() -- Close the specified relation, if it isn't closed already.
551  */
552 void
553 mdclose(SMgrRelation reln, ForkNumber forknum)
554 {
555         MdfdVec    *v = reln->md_fd[forknum];
556
557         /* No work if already closed */
558         if (v == NULL)
559                 return;
560
561         reln->md_fd[forknum] = NULL;    /* prevent dangling pointer after error */
562
563         while (v != NULL)
564         {
565                 MdfdVec    *ov = v;
566
567                 /* if not closed already */
568                 if (v->mdfd_vfd >= 0)
569                         FileClose(v->mdfd_vfd);
570                 /* Now free vector */
571                 v = v->mdfd_chain;
572                 pfree(ov);
573         }
574 }
575
576 /*
577  *      mdprefetch() -- Initiate asynchronous read of the specified block of a relation
578  */
579 void
580 mdprefetch(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum)
581 {
582 #ifdef USE_PREFETCH
583         off_t           seekpos;
584         MdfdVec    *v;
585
586         v = _mdfd_getseg(reln, forknum, blocknum, false, EXTENSION_FAIL);
587
588         seekpos = (off_t) BLCKSZ *(blocknum % ((BlockNumber) RELSEG_SIZE));
589
590         Assert(seekpos < (off_t) BLCKSZ * RELSEG_SIZE);
591
592         (void) FilePrefetch(v->mdfd_vfd, seekpos, BLCKSZ);
593 #endif   /* USE_PREFETCH */
594 }
595
596
597 /*
598  *      mdread() -- Read the specified block from a relation.
599  */
600 void
601 mdread(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum,
602            char *buffer)
603 {
604         off_t           seekpos;
605         int                     nbytes;
606         MdfdVec    *v;
607
608         TRACE_POSTGRESQL_SMGR_MD_READ_START(forknum, blocknum,
609                                                                                 reln->smgr_rnode.node.spcNode,
610                                                                                 reln->smgr_rnode.node.dbNode,
611                                                                                 reln->smgr_rnode.node.relNode,
612                                                                                 reln->smgr_rnode.backend);
613
614         v = _mdfd_getseg(reln, forknum, blocknum, false, EXTENSION_FAIL);
615
616         seekpos = (off_t) BLCKSZ *(blocknum % ((BlockNumber) RELSEG_SIZE));
617
618         Assert(seekpos < (off_t) BLCKSZ * RELSEG_SIZE);
619
620         if (FileSeek(v->mdfd_vfd, seekpos, SEEK_SET) != seekpos)
621                 ereport(ERROR,
622                                 (errcode_for_file_access(),
623                                  errmsg("could not seek to block %u in file \"%s\": %m",
624                                                 blocknum, FilePathName(v->mdfd_vfd))));
625
626         nbytes = FileRead(v->mdfd_vfd, buffer, BLCKSZ);
627
628         TRACE_POSTGRESQL_SMGR_MD_READ_DONE(forknum, blocknum,
629                                                                            reln->smgr_rnode.node.spcNode,
630                                                                            reln->smgr_rnode.node.dbNode,
631                                                                            reln->smgr_rnode.node.relNode,
632                                                                            reln->smgr_rnode.backend,
633                                                                            nbytes,
634                                                                            BLCKSZ);
635
636         if (nbytes != BLCKSZ)
637         {
638                 if (nbytes < 0)
639                         ereport(ERROR,
640                                         (errcode_for_file_access(),
641                                          errmsg("could not read block %u in file \"%s\": %m",
642                                                         blocknum, FilePathName(v->mdfd_vfd))));
643
644                 /*
645                  * Short read: we are at or past EOF, or we read a partial block at
646                  * EOF.  Normally this is an error; upper levels should never try to
647                  * read a nonexistent block.  However, if zero_damaged_pages is ON or
648                  * we are InRecovery, we should instead return zeroes without
649                  * complaining.  This allows, for example, the case of trying to
650                  * update a block that was later truncated away.
651                  */
652                 if (zero_damaged_pages || InRecovery)
653                         MemSet(buffer, 0, BLCKSZ);
654                 else
655                         ereport(ERROR,
656                                         (errcode(ERRCODE_DATA_CORRUPTED),
657                                          errmsg("could not read block %u in file \"%s\": read only %d of %d bytes",
658                                                         blocknum, FilePathName(v->mdfd_vfd),
659                                                         nbytes, BLCKSZ)));
660         }
661 }
662
663 /*
664  *      mdwrite() -- Write the supplied block at the appropriate location.
665  *
666  *              This is to be used only for updating already-existing blocks of a
667  *              relation (ie, those before the current EOF).  To extend a relation,
668  *              use mdextend().
669  */
670 void
671 mdwrite(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum,
672                 char *buffer, bool skipFsync)
673 {
674         off_t           seekpos;
675         int                     nbytes;
676         MdfdVec    *v;
677
678         /* This assert is too expensive to have on normally ... */
679 #ifdef CHECK_WRITE_VS_EXTEND
680         Assert(blocknum < mdnblocks(reln, forknum));
681 #endif
682
683         TRACE_POSTGRESQL_SMGR_MD_WRITE_START(forknum, blocknum,
684                                                                                  reln->smgr_rnode.node.spcNode,
685                                                                                  reln->smgr_rnode.node.dbNode,
686                                                                                  reln->smgr_rnode.node.relNode,
687                                                                                  reln->smgr_rnode.backend);
688
689         v = _mdfd_getseg(reln, forknum, blocknum, skipFsync, EXTENSION_FAIL);
690
691         seekpos = (off_t) BLCKSZ *(blocknum % ((BlockNumber) RELSEG_SIZE));
692
693         Assert(seekpos < (off_t) BLCKSZ * RELSEG_SIZE);
694
695         if (FileSeek(v->mdfd_vfd, seekpos, SEEK_SET) != seekpos)
696                 ereport(ERROR,
697                                 (errcode_for_file_access(),
698                                  errmsg("could not seek to block %u in file \"%s\": %m",
699                                                 blocknum, FilePathName(v->mdfd_vfd))));
700
701         nbytes = FileWrite(v->mdfd_vfd, buffer, BLCKSZ);
702
703         TRACE_POSTGRESQL_SMGR_MD_WRITE_DONE(forknum, blocknum,
704                                                                                 reln->smgr_rnode.node.spcNode,
705                                                                                 reln->smgr_rnode.node.dbNode,
706                                                                                 reln->smgr_rnode.node.relNode,
707                                                                                 reln->smgr_rnode.backend,
708                                                                                 nbytes,
709                                                                                 BLCKSZ);
710
711         if (nbytes != BLCKSZ)
712         {
713                 if (nbytes < 0)
714                         ereport(ERROR,
715                                         (errcode_for_file_access(),
716                                          errmsg("could not write block %u in file \"%s\": %m",
717                                                         blocknum, FilePathName(v->mdfd_vfd))));
718                 /* short write: complain appropriately */
719                 ereport(ERROR,
720                                 (errcode(ERRCODE_DISK_FULL),
721                                  errmsg("could not write block %u in file \"%s\": wrote only %d of %d bytes",
722                                                 blocknum,
723                                                 FilePathName(v->mdfd_vfd),
724                                                 nbytes, BLCKSZ),
725                                  errhint("Check free disk space.")));
726         }
727
728         if (!skipFsync && !SmgrIsTemp(reln))
729                 register_dirty_segment(reln, forknum, v);
730 }
731
732 /*
733  *      mdnblocks() -- Get the number of blocks stored in a relation.
734  *
735  *              Important side effect: all active segments of the relation are opened
736  *              and added to the mdfd_chain list.  If this routine has not been
737  *              called, then only segments up to the last one actually touched
738  *              are present in the chain.
739  */
740 BlockNumber
741 mdnblocks(SMgrRelation reln, ForkNumber forknum)
742 {
743         MdfdVec    *v = mdopen(reln, forknum, EXTENSION_FAIL);
744         BlockNumber nblocks;
745         BlockNumber segno = 0;
746
747         /*
748          * Skip through any segments that aren't the last one, to avoid redundant
749          * seeks on them.  We have previously verified that these segments are
750          * exactly RELSEG_SIZE long, and it's useless to recheck that each time.
751          *
752          * NOTE: this assumption could only be wrong if another backend has
753          * truncated the relation.      We rely on higher code levels to handle that
754          * scenario by closing and re-opening the md fd, which is handled via
755          * relcache flush.      (Since the bgwriter doesn't participate in relcache
756          * flush, it could have segment chain entries for inactive segments;
757          * that's OK because the bgwriter never needs to compute relation size.)
758          */
759         while (v->mdfd_chain != NULL)
760         {
761                 segno++;
762                 v = v->mdfd_chain;
763         }
764
765         for (;;)
766         {
767                 nblocks = _mdnblocks(reln, forknum, v);
768                 if (nblocks > ((BlockNumber) RELSEG_SIZE))
769                         elog(FATAL, "segment too big");
770                 if (nblocks < ((BlockNumber) RELSEG_SIZE))
771                         return (segno * ((BlockNumber) RELSEG_SIZE)) + nblocks;
772
773                 /*
774                  * If segment is exactly RELSEG_SIZE, advance to next one.
775                  */
776                 segno++;
777
778                 if (v->mdfd_chain == NULL)
779                 {
780                         /*
781                          * Because we pass O_CREAT, we will create the next segment (with
782                          * zero length) immediately, if the last segment is of length
783                          * RELSEG_SIZE.  While perhaps not strictly necessary, this keeps
784                          * the logic simple.
785                          */
786                         v->mdfd_chain = _mdfd_openseg(reln, forknum, segno, O_CREAT);
787                         if (v->mdfd_chain == NULL)
788                                 ereport(ERROR,
789                                                 (errcode_for_file_access(),
790                                                  errmsg("could not open file \"%s\": %m",
791                                                                 _mdfd_segpath(reln, forknum, segno))));
792                 }
793
794                 v = v->mdfd_chain;
795         }
796 }
797
798 /*
799  *      mdtruncate() -- Truncate relation to specified number of blocks.
800  */
801 void
802 mdtruncate(SMgrRelation reln, ForkNumber forknum, BlockNumber nblocks)
803 {
804         MdfdVec    *v;
805         BlockNumber curnblk;
806         BlockNumber priorblocks;
807
808         /*
809          * NOTE: mdnblocks makes sure we have opened all active segments, so that
810          * truncation loop will get them all!
811          */
812         curnblk = mdnblocks(reln, forknum);
813         if (nblocks > curnblk)
814         {
815                 /* Bogus request ... but no complaint if InRecovery */
816                 if (InRecovery)
817                         return;
818                 ereport(ERROR,
819                                 (errmsg("could not truncate file \"%s\" to %u blocks: it's only %u blocks now",
820                                                 relpath(reln->smgr_rnode, forknum),
821                                                 nblocks, curnblk)));
822         }
823         if (nblocks == curnblk)
824                 return;                                 /* no work */
825
826         v = mdopen(reln, forknum, EXTENSION_FAIL);
827
828         priorblocks = 0;
829         while (v != NULL)
830         {
831                 MdfdVec    *ov = v;
832
833                 if (priorblocks > nblocks)
834                 {
835                         /*
836                          * This segment is no longer active (and has already been unlinked
837                          * from the mdfd_chain). We truncate the file, but do not delete
838                          * it, for reasons explained in the header comments.
839                          */
840                         if (FileTruncate(v->mdfd_vfd, 0) < 0)
841                                 ereport(ERROR,
842                                                 (errcode_for_file_access(),
843                                                  errmsg("could not truncate file \"%s\": %m",
844                                                                 FilePathName(v->mdfd_vfd))));
845
846                         if (!SmgrIsTemp(reln))
847                                 register_dirty_segment(reln, forknum, v);
848                         v = v->mdfd_chain;
849                         Assert(ov != reln->md_fd[forknum]); /* we never drop the 1st
850                                                                                                  * segment */
851                         pfree(ov);
852                 }
853                 else if (priorblocks + ((BlockNumber) RELSEG_SIZE) > nblocks)
854                 {
855                         /*
856                          * This is the last segment we want to keep. Truncate the file to
857                          * the right length, and clear chain link that points to any
858                          * remaining segments (which we shall zap). NOTE: if nblocks is
859                          * exactly a multiple K of RELSEG_SIZE, we will truncate the K+1st
860                          * segment to 0 length but keep it. This adheres to the invariant
861                          * given in the header comments.
862                          */
863                         BlockNumber lastsegblocks = nblocks - priorblocks;
864
865                         if (FileTruncate(v->mdfd_vfd, (off_t) lastsegblocks * BLCKSZ) < 0)
866                                 ereport(ERROR,
867                                                 (errcode_for_file_access(),
868                                         errmsg("could not truncate file \"%s\" to %u blocks: %m",
869                                                    FilePathName(v->mdfd_vfd),
870                                                    nblocks)));
871                         if (!SmgrIsTemp(reln))
872                                 register_dirty_segment(reln, forknum, v);
873                         v = v->mdfd_chain;
874                         ov->mdfd_chain = NULL;
875                 }
876                 else
877                 {
878                         /*
879                          * We still need this segment and 0 or more blocks beyond it, so
880                          * nothing to do here.
881                          */
882                         v = v->mdfd_chain;
883                 }
884                 priorblocks += RELSEG_SIZE;
885         }
886 }
887
888 /*
889  *      mdimmedsync() -- Immediately sync a relation to stable storage.
890  *
891  * Note that only writes already issued are synced; this routine knows
892  * nothing of dirty buffers that may exist inside the buffer manager.
893  */
894 void
895 mdimmedsync(SMgrRelation reln, ForkNumber forknum)
896 {
897         MdfdVec    *v;
898         BlockNumber curnblk;
899
900         /*
901          * NOTE: mdnblocks makes sure we have opened all active segments, so that
902          * fsync loop will get them all!
903          */
904         curnblk = mdnblocks(reln, forknum);
905
906         v = mdopen(reln, forknum, EXTENSION_FAIL);
907
908         while (v != NULL)
909         {
910                 if (FileSync(v->mdfd_vfd) < 0)
911                         ereport(ERROR,
912                                         (errcode_for_file_access(),
913                                          errmsg("could not fsync file \"%s\": %m",
914                                                         FilePathName(v->mdfd_vfd))));
915                 v = v->mdfd_chain;
916         }
917 }
918
919 /*
920  *      mdsync() -- Sync previous writes to stable storage.
921  */
922 void
923 mdsync(void)
924 {
925         static bool mdsync_in_progress = false;
926
927         HASH_SEQ_STATUS hstat;
928         PendingOperationEntry *entry;
929         int                     absorb_counter;
930
931         /* Statistics on sync times */
932         int                     processed = 0;
933         instr_time      sync_start,
934                                 sync_end,
935                                 sync_diff; 
936         uint64          elapsed;
937         uint64          longest = 0;
938         uint64          total_elapsed = 0;
939
940         /*
941          * This is only called during checkpoints, and checkpoints should only
942          * occur in processes that have created a pendingOpsTable.
943          */
944         if (!pendingOpsTable)
945                 elog(ERROR, "cannot sync without a pendingOpsTable");
946
947         /*
948          * If we are in the bgwriter, the sync had better include all fsync
949          * requests that were queued by backends up to this point.      The tightest
950          * race condition that could occur is that a buffer that must be written
951          * and fsync'd for the checkpoint could have been dumped by a backend just
952          * before it was visited by BufferSync().  We know the backend will have
953          * queued an fsync request before clearing the buffer's dirtybit, so we
954          * are safe as long as we do an Absorb after completing BufferSync().
955          */
956         AbsorbFsyncRequests();
957
958         /*
959          * To avoid excess fsync'ing (in the worst case, maybe a never-terminating
960          * checkpoint), we want to ignore fsync requests that are entered into the
961          * hashtable after this point --- they should be processed next time,
962          * instead.  We use mdsync_cycle_ctr to tell old entries apart from new
963          * ones: new ones will have cycle_ctr equal to the incremented value of
964          * mdsync_cycle_ctr.
965          *
966          * In normal circumstances, all entries present in the table at this point
967          * will have cycle_ctr exactly equal to the current (about to be old)
968          * value of mdsync_cycle_ctr.  However, if we fail partway through the
969          * fsync'ing loop, then older values of cycle_ctr might remain when we
970          * come back here to try again.  Repeated checkpoint failures would
971          * eventually wrap the counter around to the point where an old entry
972          * might appear new, causing us to skip it, possibly allowing a checkpoint
973          * to succeed that should not have.  To forestall wraparound, any time the
974          * previous mdsync() failed to complete, run through the table and
975          * forcibly set cycle_ctr = mdsync_cycle_ctr.
976          *
977          * Think not to merge this loop with the main loop, as the problem is
978          * exactly that that loop may fail before having visited all the entries.
979          * From a performance point of view it doesn't matter anyway, as this path
980          * will never be taken in a system that's functioning normally.
981          */
982         if (mdsync_in_progress)
983         {
984                 /* prior try failed, so update any stale cycle_ctr values */
985                 hash_seq_init(&hstat, pendingOpsTable);
986                 while ((entry = (PendingOperationEntry *) hash_seq_search(&hstat)) != NULL)
987                 {
988                         entry->cycle_ctr = mdsync_cycle_ctr;
989                 }
990         }
991
992         /* Advance counter so that new hashtable entries are distinguishable */
993         mdsync_cycle_ctr++;
994
995         /* Set flag to detect failure if we don't reach the end of the loop */
996         mdsync_in_progress = true;
997
998         /* Now scan the hashtable for fsync requests to process */
999         absorb_counter = FSYNCS_PER_ABSORB;
1000         hash_seq_init(&hstat, pendingOpsTable);
1001         while ((entry = (PendingOperationEntry *) hash_seq_search(&hstat)) != NULL)
1002         {
1003                 /*
1004                  * If the entry is new then don't process it this time.  Note that
1005                  * "continue" bypasses the hash-remove call at the bottom of the loop.
1006                  */
1007                 if (entry->cycle_ctr == mdsync_cycle_ctr)
1008                         continue;
1009
1010                 /* Else assert we haven't missed it */
1011                 Assert((CycleCtr) (entry->cycle_ctr + 1) == mdsync_cycle_ctr);
1012
1013                 /*
1014                  * If fsync is off then we don't have to bother opening the file at
1015                  * all.  (We delay checking until this point so that changing fsync on
1016                  * the fly behaves sensibly.)  Also, if the entry is marked canceled,
1017                  * fall through to delete it.
1018                  */
1019                 if (enableFsync && !entry->canceled)
1020                 {
1021                         int                     failures;
1022
1023                         /*
1024                          * If in bgwriter, we want to absorb pending requests every so
1025                          * often to prevent overflow of the fsync request queue.  It is
1026                          * unspecified whether newly-added entries will be visited by
1027                          * hash_seq_search, but we don't care since we don't need to
1028                          * process them anyway.
1029                          */
1030                         if (--absorb_counter <= 0)
1031                         {
1032                                 AbsorbFsyncRequests();
1033                                 absorb_counter = FSYNCS_PER_ABSORB;
1034                         }
1035
1036                         /*
1037                          * The fsync table could contain requests to fsync segments that
1038                          * have been deleted (unlinked) by the time we get to them. Rather
1039                          * than just hoping an ENOENT (or EACCES on Windows) error can be
1040                          * ignored, what we do on error is absorb pending requests and
1041                          * then retry.  Since mdunlink() queues a "revoke" message before
1042                          * actually unlinking, the fsync request is guaranteed to be
1043                          * marked canceled after the absorb if it really was this case.
1044                          * DROP DATABASE likewise has to tell us to forget fsync requests
1045                          * before it starts deletions.
1046                          */
1047                         for (failures = 0;; failures++)         /* loop exits at "break" */
1048                         {
1049                                 SMgrRelation reln;
1050                                 MdfdVec    *seg;
1051                                 char       *path;
1052
1053                                 /*
1054                                  * Find or create an smgr hash entry for this relation. This
1055                                  * may seem a bit unclean -- md calling smgr?  But it's really
1056                                  * the best solution.  It ensures that the open file reference
1057                                  * isn't permanently leaked if we get an error here. (You may
1058                                  * say "but an unreferenced SMgrRelation is still a leak!" Not
1059                                  * really, because the only case in which a checkpoint is done
1060                                  * by a process that isn't about to shut down is in the
1061                                  * bgwriter, and it will periodically do smgrcloseall(). This
1062                                  * fact justifies our not closing the reln in the success path
1063                                  * either, which is a good thing since in non-bgwriter cases
1064                                  * we couldn't safely do that.)  Furthermore, in many cases
1065                                  * the relation will have been dirtied through this same smgr
1066                                  * relation, and so we can save a file open/close cycle.
1067                                  */
1068                                 reln = smgropen(entry->tag.rnode.node,
1069                                                                 entry->tag.rnode.backend);
1070
1071                                 /*
1072                                  * It is possible that the relation has been dropped or
1073                                  * truncated since the fsync request was entered.  Therefore,
1074                                  * allow ENOENT, but only if we didn't fail already on this
1075                                  * file.  This applies both during _mdfd_getseg() and during
1076                                  * FileSync, since fd.c might have closed the file behind our
1077                                  * back.
1078                                  */
1079                                 seg = _mdfd_getseg(reln, entry->tag.forknum,
1080                                                           entry->tag.segno * ((BlockNumber) RELSEG_SIZE),
1081                                                                    false, EXTENSION_RETURN_NULL);
1082
1083                                 if (log_checkpoints)
1084                                         INSTR_TIME_SET_CURRENT(sync_start);
1085                                 else
1086                                         INSTR_TIME_SET_ZERO(sync_start);
1087
1088                                 if (seg != NULL &&
1089                                         FileSync(seg->mdfd_vfd) >= 0)
1090                                 {
1091                                         if (log_checkpoints && (! INSTR_TIME_IS_ZERO(sync_start)))
1092                                         {
1093                                                 INSTR_TIME_SET_CURRENT(sync_end);
1094                                                 sync_diff = sync_end;
1095                                                 INSTR_TIME_SUBTRACT(sync_diff, sync_start);
1096                                                 elapsed = INSTR_TIME_GET_MICROSEC(sync_diff);
1097                                                 if (elapsed > longest)
1098                                                         longest = elapsed;
1099                                                 total_elapsed += elapsed;
1100                                                 processed++;
1101                                                 elog(DEBUG1, "checkpoint sync: number=%d file=%s time=%.3f msec", 
1102                                                         processed, FilePathName(seg->mdfd_vfd), (double) elapsed / 1000);
1103                                         }
1104
1105                                         break;          /* success; break out of retry loop */
1106                                 }
1107
1108                                 /*
1109                                  * XXX is there any point in allowing more than one retry?
1110                                  * Don't see one at the moment, but easy to change the test
1111                                  * here if so.
1112                                  */
1113                                 path = _mdfd_segpath(reln, entry->tag.forknum,
1114                                                                          entry->tag.segno);
1115                                 if (!FILE_POSSIBLY_DELETED(errno) ||
1116                                         failures > 0)
1117                                         ereport(ERROR,
1118                                                         (errcode_for_file_access(),
1119                                                    errmsg("could not fsync file \"%s\": %m", path)));
1120                                 else
1121                                         ereport(DEBUG1,
1122                                                         (errcode_for_file_access(),
1123                                            errmsg("could not fsync file \"%s\" but retrying: %m",
1124                                                           path)));
1125                                 pfree(path);
1126
1127                                 /*
1128                                  * Absorb incoming requests and check to see if canceled.
1129                                  */
1130                                 AbsorbFsyncRequests();
1131                                 absorb_counter = FSYNCS_PER_ABSORB;             /* might as well... */
1132
1133                                 if (entry->canceled)
1134                                         break;
1135                         }                                       /* end retry loop */
1136                 }
1137
1138                 /*
1139                  * If we get here, either we fsync'd successfully, or we don't have to
1140                  * because enableFsync is off, or the entry is (now) marked canceled.
1141                  * Okay to delete it.
1142                  */
1143                 if (hash_search(pendingOpsTable, &entry->tag,
1144                                                 HASH_REMOVE, NULL) == NULL)
1145                         elog(ERROR, "pendingOpsTable corrupted");
1146         }                                                       /* end loop over hashtable entries */
1147
1148         /* Return sync performance metrics for report at checkpoint end */
1149         CheckpointStats.ckpt_sync_rels = processed;
1150         CheckpointStats.ckpt_longest_sync = longest;
1151         CheckpointStats.ckpt_agg_sync_time = total_elapsed;
1152
1153         /* Flag successful completion of mdsync */
1154         mdsync_in_progress = false;
1155 }
1156
1157 /*
1158  * mdpreckpt() -- Do pre-checkpoint work
1159  *
1160  * To distinguish unlink requests that arrived before this checkpoint
1161  * started from those that arrived during the checkpoint, we use a cycle
1162  * counter similar to the one we use for fsync requests. That cycle
1163  * counter is incremented here.
1164  *
1165  * This must be called *before* the checkpoint REDO point is determined.
1166  * That ensures that we won't delete files too soon.
1167  *
1168  * Note that we can't do anything here that depends on the assumption
1169  * that the checkpoint will be completed.
1170  */
1171 void
1172 mdpreckpt(void)
1173 {
1174         ListCell   *cell;
1175
1176         /*
1177          * In case the prior checkpoint wasn't completed, stamp all entries in the
1178          * list with the current cycle counter.  Anything that's in the list at
1179          * the start of checkpoint can surely be deleted after the checkpoint is
1180          * finished, regardless of when the request was made.
1181          */
1182         foreach(cell, pendingUnlinks)
1183         {
1184                 PendingUnlinkEntry *entry = (PendingUnlinkEntry *) lfirst(cell);
1185
1186                 entry->cycle_ctr = mdckpt_cycle_ctr;
1187         }
1188
1189         /*
1190          * Any unlink requests arriving after this point will be assigned the next
1191          * cycle counter, and won't be unlinked until next checkpoint.
1192          */
1193         mdckpt_cycle_ctr++;
1194 }
1195
1196 /*
1197  * mdpostckpt() -- Do post-checkpoint work
1198  *
1199  * Remove any lingering files that can now be safely removed.
1200  */
1201 void
1202 mdpostckpt(void)
1203 {
1204         while (pendingUnlinks != NIL)
1205         {
1206                 PendingUnlinkEntry *entry = (PendingUnlinkEntry *) linitial(pendingUnlinks);
1207                 char       *path;
1208
1209                 /*
1210                  * New entries are appended to the end, so if the entry is new we've
1211                  * reached the end of old entries.
1212                  */
1213                 if (entry->cycle_ctr == mdckpt_cycle_ctr)
1214                         break;
1215
1216                 /* Else assert we haven't missed it */
1217                 Assert((CycleCtr) (entry->cycle_ctr + 1) == mdckpt_cycle_ctr);
1218
1219                 /* Unlink the file */
1220                 path = relpath(entry->rnode, MAIN_FORKNUM);
1221                 if (unlink(path) < 0)
1222                 {
1223                         /*
1224                          * There's a race condition, when the database is dropped at the
1225                          * same time that we process the pending unlink requests. If the
1226                          * DROP DATABASE deletes the file before we do, we will get ENOENT
1227                          * here. rmtree() also has to ignore ENOENT errors, to deal with
1228                          * the possibility that we delete the file first.
1229                          */
1230                         if (errno != ENOENT)
1231                                 ereport(WARNING,
1232                                                 (errcode_for_file_access(),
1233                                                  errmsg("could not remove file \"%s\": %m", path)));
1234                 }
1235                 pfree(path);
1236
1237                 pendingUnlinks = list_delete_first(pendingUnlinks);
1238                 pfree(entry);
1239         }
1240 }
1241
1242 /*
1243  * register_dirty_segment() -- Mark a relation segment as needing fsync
1244  *
1245  * If there is a local pending-ops table, just make an entry in it for
1246  * mdsync to process later.  Otherwise, try to pass off the fsync request
1247  * to the background writer process.  If that fails, just do the fsync
1248  * locally before returning (we expect this will not happen often enough
1249  * to be a performance problem).
1250  */
1251 static void
1252 register_dirty_segment(SMgrRelation reln, ForkNumber forknum, MdfdVec *seg)
1253 {
1254         if (pendingOpsTable)
1255         {
1256                 /* push it into local pending-ops table */
1257                 RememberFsyncRequest(reln->smgr_rnode, forknum, seg->mdfd_segno);
1258         }
1259         else
1260         {
1261                 if (ForwardFsyncRequest(reln->smgr_rnode, forknum, seg->mdfd_segno))
1262                         return;                         /* passed it off successfully */
1263
1264                 ereport(DEBUG1,
1265                         (errmsg("could not forward fsync request because request queue is full")));
1266
1267                 if (FileSync(seg->mdfd_vfd) < 0)
1268                         ereport(ERROR,
1269                                         (errcode_for_file_access(),
1270                                          errmsg("could not fsync file \"%s\": %m",
1271                                                         FilePathName(seg->mdfd_vfd))));
1272         }
1273 }
1274
1275 /*
1276  * register_unlink() -- Schedule a file to be deleted after next checkpoint
1277  *
1278  * As with register_dirty_segment, this could involve either a local or
1279  * a remote pending-ops table.
1280  */
1281 static void
1282 register_unlink(RelFileNodeBackend rnode)
1283 {
1284         if (pendingOpsTable)
1285         {
1286                 /* push it into local pending-ops table */
1287                 RememberFsyncRequest(rnode, MAIN_FORKNUM, UNLINK_RELATION_REQUEST);
1288         }
1289         else
1290         {
1291                 /*
1292                  * Notify the bgwriter about it.  If we fail to queue the request
1293                  * message, we have to sleep and try again, because we can't simply
1294                  * delete the file now.  Ugly, but hopefully won't happen often.
1295                  *
1296                  * XXX should we just leave the file orphaned instead?
1297                  */
1298                 Assert(IsUnderPostmaster);
1299                 while (!ForwardFsyncRequest(rnode, MAIN_FORKNUM,
1300                                                                         UNLINK_RELATION_REQUEST))
1301                         pg_usleep(10000L);      /* 10 msec seems a good number */
1302         }
1303 }
1304
1305 /*
1306  * RememberFsyncRequest() -- callback from bgwriter side of fsync request
1307  *
1308  * We stuff most fsync requests into the local hash table for execution
1309  * during the bgwriter's next checkpoint.  UNLINK requests go into a
1310  * separate linked list, however, because they get processed separately.
1311  *
1312  * The range of possible segment numbers is way less than the range of
1313  * BlockNumber, so we can reserve high values of segno for special purposes.
1314  * We define three:
1315  * - FORGET_RELATION_FSYNC means to cancel pending fsyncs for a relation
1316  * - FORGET_DATABASE_FSYNC means to cancel pending fsyncs for a whole database
1317  * - UNLINK_RELATION_REQUEST is a request to delete the file after the next
1318  *       checkpoint.
1319  *
1320  * (Handling the FORGET_* requests is a tad slow because the hash table has
1321  * to be searched linearly, but it doesn't seem worth rethinking the table
1322  * structure for them.)
1323  */
1324 void
1325 RememberFsyncRequest(RelFileNodeBackend rnode, ForkNumber forknum,
1326                                          BlockNumber segno)
1327 {
1328         Assert(pendingOpsTable);
1329
1330         if (segno == FORGET_RELATION_FSYNC)
1331         {
1332                 /* Remove any pending requests for the entire relation */
1333                 HASH_SEQ_STATUS hstat;
1334                 PendingOperationEntry *entry;
1335
1336                 hash_seq_init(&hstat, pendingOpsTable);
1337                 while ((entry = (PendingOperationEntry *) hash_seq_search(&hstat)) != NULL)
1338                 {
1339                         if (RelFileNodeBackendEquals(entry->tag.rnode, rnode) &&
1340                                 entry->tag.forknum == forknum)
1341                         {
1342                                 /* Okay, cancel this entry */
1343                                 entry->canceled = true;
1344                         }
1345                 }
1346         }
1347         else if (segno == FORGET_DATABASE_FSYNC)
1348         {
1349                 /* Remove any pending requests for the entire database */
1350                 HASH_SEQ_STATUS hstat;
1351                 PendingOperationEntry *entry;
1352                 ListCell   *cell,
1353                                    *prev,
1354                                    *next;
1355
1356                 /* Remove fsync requests */
1357                 hash_seq_init(&hstat, pendingOpsTable);
1358                 while ((entry = (PendingOperationEntry *) hash_seq_search(&hstat)) != NULL)
1359                 {
1360                         if (entry->tag.rnode.node.dbNode == rnode.node.dbNode)
1361                         {
1362                                 /* Okay, cancel this entry */
1363                                 entry->canceled = true;
1364                         }
1365                 }
1366
1367                 /* Remove unlink requests */
1368                 prev = NULL;
1369                 for (cell = list_head(pendingUnlinks); cell; cell = next)
1370                 {
1371                         PendingUnlinkEntry *entry = (PendingUnlinkEntry *) lfirst(cell);
1372
1373                         next = lnext(cell);
1374                         if (entry->rnode.node.dbNode == rnode.node.dbNode)
1375                         {
1376                                 pendingUnlinks = list_delete_cell(pendingUnlinks, cell, prev);
1377                                 pfree(entry);
1378                         }
1379                         else
1380                                 prev = cell;
1381                 }
1382         }
1383         else if (segno == UNLINK_RELATION_REQUEST)
1384         {
1385                 /* Unlink request: put it in the linked list */
1386                 MemoryContext oldcxt = MemoryContextSwitchTo(MdCxt);
1387                 PendingUnlinkEntry *entry;
1388
1389                 entry = palloc(sizeof(PendingUnlinkEntry));
1390                 entry->rnode = rnode;
1391                 entry->cycle_ctr = mdckpt_cycle_ctr;
1392
1393                 pendingUnlinks = lappend(pendingUnlinks, entry);
1394
1395                 MemoryContextSwitchTo(oldcxt);
1396         }
1397         else
1398         {
1399                 /* Normal case: enter a request to fsync this segment */
1400                 PendingOperationTag key;
1401                 PendingOperationEntry *entry;
1402                 bool            found;
1403
1404                 /* ensure any pad bytes in the hash key are zeroed */
1405                 MemSet(&key, 0, sizeof(key));
1406                 key.rnode = rnode;
1407                 key.forknum = forknum;
1408                 key.segno = segno;
1409
1410                 entry = (PendingOperationEntry *) hash_search(pendingOpsTable,
1411                                                                                                           &key,
1412                                                                                                           HASH_ENTER,
1413                                                                                                           &found);
1414                 /* if new or previously canceled entry, initialize it */
1415                 if (!found || entry->canceled)
1416                 {
1417                         entry->canceled = false;
1418                         entry->cycle_ctr = mdsync_cycle_ctr;
1419                 }
1420
1421                 /*
1422                  * NB: it's intentional that we don't change cycle_ctr if the entry
1423                  * already exists.      The fsync request must be treated as old, even
1424                  * though the new request will be satisfied too by any subsequent
1425                  * fsync.
1426                  *
1427                  * However, if the entry is present but is marked canceled, we should
1428                  * act just as though it wasn't there.  The only case where this could
1429                  * happen would be if a file had been deleted, we received but did not
1430                  * yet act on the cancel request, and the same relfilenode was then
1431                  * assigned to a new file.      We mustn't lose the new request, but it
1432                  * should be considered new not old.
1433                  */
1434         }
1435 }
1436
1437 /*
1438  * ForgetRelationFsyncRequests -- forget any fsyncs for a rel
1439  */
1440 void
1441 ForgetRelationFsyncRequests(RelFileNodeBackend rnode, ForkNumber forknum)
1442 {
1443         if (pendingOpsTable)
1444         {
1445                 /* standalone backend or startup process: fsync state is local */
1446                 RememberFsyncRequest(rnode, forknum, FORGET_RELATION_FSYNC);
1447         }
1448         else if (IsUnderPostmaster)
1449         {
1450                 /*
1451                  * Notify the bgwriter about it.  If we fail to queue the revoke
1452                  * message, we have to sleep and try again ... ugly, but hopefully
1453                  * won't happen often.
1454                  *
1455                  * XXX should we CHECK_FOR_INTERRUPTS in this loop?  Escaping with an
1456                  * error would leave the no-longer-used file still present on disk,
1457                  * which would be bad, so I'm inclined to assume that the bgwriter
1458                  * will always empty the queue soon.
1459                  */
1460                 while (!ForwardFsyncRequest(rnode, forknum, FORGET_RELATION_FSYNC))
1461                         pg_usleep(10000L);      /* 10 msec seems a good number */
1462
1463                 /*
1464                  * Note we don't wait for the bgwriter to actually absorb the revoke
1465                  * message; see mdsync() for the implications.
1466                  */
1467         }
1468 }
1469
1470 /*
1471  * ForgetDatabaseFsyncRequests -- forget any fsyncs and unlinks for a DB
1472  */
1473 void
1474 ForgetDatabaseFsyncRequests(Oid dbid)
1475 {
1476         RelFileNodeBackend rnode;
1477
1478         rnode.node.dbNode = dbid;
1479         rnode.node.spcNode = 0;
1480         rnode.node.relNode = 0;
1481         rnode.backend = InvalidBackendId;
1482
1483         if (pendingOpsTable)
1484         {
1485                 /* standalone backend or startup process: fsync state is local */
1486                 RememberFsyncRequest(rnode, InvalidForkNumber, FORGET_DATABASE_FSYNC);
1487         }
1488         else if (IsUnderPostmaster)
1489         {
1490                 /* see notes in ForgetRelationFsyncRequests */
1491                 while (!ForwardFsyncRequest(rnode, InvalidForkNumber,
1492                                                                         FORGET_DATABASE_FSYNC))
1493                         pg_usleep(10000L);      /* 10 msec seems a good number */
1494         }
1495 }
1496
1497
1498 /*
1499  *      _fdvec_alloc() -- Make a MdfdVec object.
1500  */
1501 static MdfdVec *
1502 _fdvec_alloc(void)
1503 {
1504         return (MdfdVec *) MemoryContextAlloc(MdCxt, sizeof(MdfdVec));
1505 }
1506
1507 /*
1508  * Return the filename for the specified segment of the relation. The
1509  * returned string is palloc'd.
1510  */
1511 static char *
1512 _mdfd_segpath(SMgrRelation reln, ForkNumber forknum, BlockNumber segno)
1513 {
1514         char       *path,
1515                            *fullpath;
1516
1517         path = relpath(reln->smgr_rnode, forknum);
1518
1519         if (segno > 0)
1520         {
1521                 /* be sure we have enough space for the '.segno' */
1522                 fullpath = (char *) palloc(strlen(path) + 12);
1523                 sprintf(fullpath, "%s.%u", path, segno);
1524                 pfree(path);
1525         }
1526         else
1527                 fullpath = path;
1528
1529         return fullpath;
1530 }
1531
1532 /*
1533  * Open the specified segment of the relation,
1534  * and make a MdfdVec object for it.  Returns NULL on failure.
1535  */
1536 static MdfdVec *
1537 _mdfd_openseg(SMgrRelation reln, ForkNumber forknum, BlockNumber segno,
1538                           int oflags)
1539 {
1540         MdfdVec    *v;
1541         int                     fd;
1542         char       *fullpath;
1543
1544         fullpath = _mdfd_segpath(reln, forknum, segno);
1545
1546         /* open the file */
1547         fd = PathNameOpenFile(fullpath, O_RDWR | PG_BINARY | oflags, 0600);
1548
1549         pfree(fullpath);
1550
1551         if (fd < 0)
1552                 return NULL;
1553
1554         /* allocate an mdfdvec entry for it */
1555         v = _fdvec_alloc();
1556
1557         /* fill the entry */
1558         v->mdfd_vfd = fd;
1559         v->mdfd_segno = segno;
1560         v->mdfd_chain = NULL;
1561         Assert(_mdnblocks(reln, forknum, v) <= ((BlockNumber) RELSEG_SIZE));
1562
1563         /* all done */
1564         return v;
1565 }
1566
1567 /*
1568  *      _mdfd_getseg() -- Find the segment of the relation holding the
1569  *              specified block.
1570  *
1571  * If the segment doesn't exist, we ereport, return NULL, or create the
1572  * segment, according to "behavior".  Note: skipFsync is only used in the
1573  * EXTENSION_CREATE case.
1574  */
1575 static MdfdVec *
1576 _mdfd_getseg(SMgrRelation reln, ForkNumber forknum, BlockNumber blkno,
1577                          bool skipFsync, ExtensionBehavior behavior)
1578 {
1579         MdfdVec    *v = mdopen(reln, forknum, behavior);
1580         BlockNumber targetseg;
1581         BlockNumber nextsegno;
1582
1583         if (!v)
1584                 return NULL;                    /* only possible if EXTENSION_RETURN_NULL */
1585
1586         targetseg = blkno / ((BlockNumber) RELSEG_SIZE);
1587         for (nextsegno = 1; nextsegno <= targetseg; nextsegno++)
1588         {
1589                 Assert(nextsegno == v->mdfd_segno + 1);
1590
1591                 if (v->mdfd_chain == NULL)
1592                 {
1593                         /*
1594                          * Normally we will create new segments only if authorized by the
1595                          * caller (i.e., we are doing mdextend()).      But when doing WAL
1596                          * recovery, create segments anyway; this allows cases such as
1597                          * replaying WAL data that has a write into a high-numbered
1598                          * segment of a relation that was later deleted.  We want to go
1599                          * ahead and create the segments so we can finish out the replay.
1600                          *
1601                          * We have to maintain the invariant that segments before the last
1602                          * active segment are of size RELSEG_SIZE; therefore, pad them out
1603                          * with zeroes if needed.  (This only matters if caller is
1604                          * extending the relation discontiguously, but that can happen in
1605                          * hash indexes.)
1606                          */
1607                         if (behavior == EXTENSION_CREATE || InRecovery)
1608                         {
1609                                 if (_mdnblocks(reln, forknum, v) < RELSEG_SIZE)
1610                                 {
1611                                         char       *zerobuf = palloc0(BLCKSZ);
1612
1613                                         mdextend(reln, forknum,
1614                                                          nextsegno * ((BlockNumber) RELSEG_SIZE) - 1,
1615                                                          zerobuf, skipFsync);
1616                                         pfree(zerobuf);
1617                                 }
1618                                 v->mdfd_chain = _mdfd_openseg(reln, forknum, +nextsegno, O_CREAT);
1619                         }
1620                         else
1621                         {
1622                                 /* We won't create segment if not existent */
1623                                 v->mdfd_chain = _mdfd_openseg(reln, forknum, nextsegno, 0);
1624                         }
1625                         if (v->mdfd_chain == NULL)
1626                         {
1627                                 if (behavior == EXTENSION_RETURN_NULL &&
1628                                         FILE_POSSIBLY_DELETED(errno))
1629                                         return NULL;
1630                                 ereport(ERROR,
1631                                                 (errcode_for_file_access(),
1632                                    errmsg("could not open file \"%s\" (target block %u): %m",
1633                                                   _mdfd_segpath(reln, forknum, nextsegno),
1634                                                   blkno)));
1635                         }
1636                 }
1637                 v = v->mdfd_chain;
1638         }
1639         return v;
1640 }
1641
1642 /*
1643  * Get number of blocks present in a single disk file
1644  */
1645 static BlockNumber
1646 _mdnblocks(SMgrRelation reln, ForkNumber forknum, MdfdVec *seg)
1647 {
1648         off_t           len;
1649
1650         len = FileSeek(seg->mdfd_vfd, 0L, SEEK_END);
1651         if (len < 0)
1652                 ereport(ERROR,
1653                                 (errcode_for_file_access(),
1654                                  errmsg("could not seek to end of file \"%s\": %m",
1655                                                 FilePathName(seg->mdfd_vfd))));
1656         /* note that this calculation will ignore any partial block at EOF */
1657         return (BlockNumber) (len / BLCKSZ);
1658 }