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