PostgreSQL Source Code  git master
md.c
Go to the documentation of this file.
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-2022, 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 "access/xlog.h"
29 #include "access/xlogutils.h"
30 #include "commands/tablespace.h"
31 #include "miscadmin.h"
32 #include "pg_trace.h"
33 #include "pgstat.h"
34 #include "postmaster/bgwriter.h"
35 #include "storage/bufmgr.h"
36 #include "storage/fd.h"
37 #include "storage/md.h"
38 #include "storage/relfilenode.h"
39 #include "storage/smgr.h"
40 #include "storage/sync.h"
41 #include "utils/hsearch.h"
42 #include "utils/memutils.h"
43 
44 /*
45  * The magnetic disk storage manager keeps track of open file
46  * descriptors in its own descriptor pool. This is done to make it
47  * easier to support relations that are larger than the operating
48  * system's file size limit (often 2GBytes). In order to do that,
49  * we break relations up into "segment" files that are each shorter than
50  * the OS file size limit. The segment size is set by the RELSEG_SIZE
51  * configuration constant in pg_config.h.
52  *
53  * On disk, a relation must consist of consecutively numbered segment
54  * files in the pattern
55  * -- Zero or more full segments of exactly RELSEG_SIZE blocks each
56  * -- Exactly one partial segment of size 0 <= size < RELSEG_SIZE blocks
57  * -- Optionally, any number of inactive segments of size 0 blocks.
58  * The full and partial segments are collectively the "active" segments.
59  * Inactive segments are those that once contained data but are currently
60  * not needed because of an mdtruncate() operation. The reason for leaving
61  * them present at size zero, rather than unlinking them, is that other
62  * backends and/or the checkpointer might be holding open file references to
63  * such segments. If the relation expands again after mdtruncate(), such
64  * that a deactivated segment becomes active again, it is important that
65  * such file references still be valid --- else data might get written
66  * out to an unlinked old copy of a segment file that will eventually
67  * disappear.
68  *
69  * File descriptors are stored in the per-fork md_seg_fds arrays inside
70  * SMgrRelation. The length of these arrays is stored in md_num_open_segs.
71  * Note that a fork's md_num_open_segs having a specific value does not
72  * necessarily mean the relation doesn't have additional segments; we may
73  * just not have opened the next segment yet. (We could not have "all
74  * segments are in the array" as an invariant anyway, since another backend
75  * could extend the relation while we aren't looking.) We do not have
76  * entries for inactive segments, however; as soon as we find a partial
77  * segment, we assume that any subsequent segments are inactive.
78  *
79  * The entire MdfdVec array is palloc'd in the MdCxt memory context.
80  */
81 
82 typedef struct _MdfdVec
83 {
84  File mdfd_vfd; /* fd number in fd.c's pool */
85  BlockNumber mdfd_segno; /* segment number, from 0 */
87 
88 static MemoryContext MdCxt; /* context for all MdfdVec objects */
89 
90 
91 /* Populate a file tag describing an md.c segment file. */
92 #define INIT_MD_FILETAG(a,xx_rnode,xx_forknum,xx_segno) \
93 ( \
94  memset(&(a), 0, sizeof(FileTag)), \
95  (a).handler = SYNC_HANDLER_MD, \
96  (a).rnode = (xx_rnode), \
97  (a).forknum = (xx_forknum), \
98  (a).segno = (xx_segno) \
99 )
100 
101 
102 /*** behavior for mdopen & _mdfd_getseg ***/
103 /* ereport if segment not present */
104 #define EXTENSION_FAIL (1 << 0)
105 /* return NULL if segment not present */
106 #define EXTENSION_RETURN_NULL (1 << 1)
107 /* create new segments as needed */
108 #define EXTENSION_CREATE (1 << 2)
109 /* create new segments if needed during recovery */
110 #define EXTENSION_CREATE_RECOVERY (1 << 3)
111 /*
112  * Allow opening segments which are preceded by segments smaller than
113  * RELSEG_SIZE, e.g. inactive segments (see above). Note that this breaks
114  * mdnblocks() and related functionality henceforth - which currently is ok,
115  * because this is only required in the checkpointer which never uses
116  * mdnblocks().
117  */
118 #define EXTENSION_DONT_CHECK_SIZE (1 << 4)
119 /* don't try to open a segment, if not already open */
120 #define EXTENSION_DONT_OPEN (1 << 5)
121 
122 
123 /* local routines */
124 static void mdunlinkfork(RelFileNodeBackend rnode, ForkNumber forkNum,
125  bool isRedo);
126 static MdfdVec *mdopenfork(SMgrRelation reln, ForkNumber forknum, int behavior);
127 static void register_dirty_segment(SMgrRelation reln, ForkNumber forknum,
128  MdfdVec *seg);
129 static void register_unlink_segment(RelFileNodeBackend rnode, ForkNumber forknum,
130  BlockNumber segno);
131 static void register_forget_request(RelFileNodeBackend rnode, ForkNumber forknum,
132  BlockNumber segno);
133 static void _fdvec_resize(SMgrRelation reln,
134  ForkNumber forknum,
135  int nseg);
136 static char *_mdfd_segpath(SMgrRelation reln, ForkNumber forknum,
137  BlockNumber segno);
138 static MdfdVec *_mdfd_openseg(SMgrRelation reln, ForkNumber forkno,
139  BlockNumber segno, int oflags);
140 static MdfdVec *_mdfd_getseg(SMgrRelation reln, ForkNumber forkno,
141  BlockNumber blkno, bool skipFsync, int behavior);
142 static BlockNumber _mdnblocks(SMgrRelation reln, ForkNumber forknum,
143  MdfdVec *seg);
144 
145 
146 /*
147  * mdinit() -- Initialize private state for magnetic disk storage manager.
148  */
149 void
150 mdinit(void)
151 {
153  "MdSmgr",
155 }
156 
157 /*
158  * mdexists() -- Does the physical file exist?
159  *
160  * Note: this will return true for lingering files, with pending deletions
161  */
162 bool
164 {
165  /*
166  * Close it first, to ensure that we notice if the fork has been unlinked
167  * since we opened it. As an optimization, we can skip that in recovery,
168  * which already closes relations when dropping them.
169  */
170  if (!InRecovery)
171  mdclose(reln, forkNum);
172 
173  return (mdopenfork(reln, forkNum, EXTENSION_RETURN_NULL) != NULL);
174 }
175 
176 /*
177  * mdcreate() -- Create a new relation on magnetic disk.
178  *
179  * If isRedo is true, it's okay for the relation to exist already.
180  */
181 void
182 mdcreate(SMgrRelation reln, ForkNumber forkNum, bool isRedo)
183 {
184  MdfdVec *mdfd;
185  char *path;
186  File fd;
187 
188  if (isRedo && reln->md_num_open_segs[forkNum] > 0)
189  return; /* created and opened already... */
190 
191  Assert(reln->md_num_open_segs[forkNum] == 0);
192 
193  /*
194  * We may be using the target table space for the first time in this
195  * database, so create a per-database subdirectory if needed.
196  *
197  * XXX this is a fairly ugly violation of module layering, but this seems
198  * to be the best place to put the check. Maybe TablespaceCreateDbspace
199  * should be here and not in commands/tablespace.c? But that would imply
200  * importing a lot of stuff that smgr.c oughtn't know, either.
201  */
203  reln->smgr_rnode.node.dbNode,
204  isRedo);
205 
206  path = relpath(reln->smgr_rnode, forkNum);
207 
208  fd = PathNameOpenFile(path, O_RDWR | O_CREAT | O_EXCL | PG_BINARY);
209 
210  if (fd < 0)
211  {
212  int save_errno = errno;
213 
214  if (isRedo)
215  fd = PathNameOpenFile(path, O_RDWR | PG_BINARY);
216  if (fd < 0)
217  {
218  /* be sure to report the error reported by create, not open */
219  errno = save_errno;
220  ereport(ERROR,
222  errmsg("could not create file \"%s\": %m", path)));
223  }
224  }
225 
226  pfree(path);
227 
228  _fdvec_resize(reln, forkNum, 1);
229  mdfd = &reln->md_seg_fds[forkNum][0];
230  mdfd->mdfd_vfd = fd;
231  mdfd->mdfd_segno = 0;
232 }
233 
234 /*
235  * mdunlink() -- Unlink a relation.
236  *
237  * Note that we're passed a RelFileNodeBackend --- by the time this is called,
238  * there won't be an SMgrRelation hashtable entry anymore.
239  *
240  * forkNum can be a fork number to delete a specific fork, or InvalidForkNumber
241  * to delete all forks.
242  *
243  * For regular relations, we don't unlink the first segment file of the rel,
244  * but just truncate it to zero length, and record a request to unlink it after
245  * the next checkpoint. Additional segments can be unlinked immediately,
246  * however. Leaving the empty file in place prevents that relfilenode
247  * number from being reused. The scenario this protects us from is:
248  * 1. We delete a relation (and commit, and actually remove its file).
249  * 2. We create a new relation, which by chance gets the same relfilenode as
250  * the just-deleted one (OIDs must've wrapped around for that to happen).
251  * 3. We crash before another checkpoint occurs.
252  * During replay, we would delete the file and then recreate it, which is fine
253  * if the contents of the file were repopulated by subsequent WAL entries.
254  * But if we didn't WAL-log insertions, but instead relied on fsyncing the
255  * file after populating it (as we do at wal_level=minimal), the contents of
256  * the file would be lost forever. By leaving the empty file until after the
257  * next checkpoint, we prevent reassignment of the relfilenode number until
258  * it's safe, because relfilenode assignment skips over any existing file.
259  *
260  * We do not need to go through this dance for temp relations, though, because
261  * we never make WAL entries for temp rels, and so a temp rel poses no threat
262  * to the health of a regular rel that has taken over its relfilenode number.
263  * The fact that temp rels and regular rels have different file naming
264  * patterns provides additional safety.
265  *
266  * All the above applies only to the relation's main fork; other forks can
267  * just be removed immediately, since they are not needed to prevent the
268  * relfilenode number from being recycled. Also, we do not carefully
269  * track whether other forks have been created or not, but just attempt to
270  * unlink them unconditionally; so we should never complain about ENOENT.
271  *
272  * If isRedo is true, it's unsurprising for the relation to be already gone.
273  * Also, we should remove the file immediately instead of queuing a request
274  * for later, since during redo there's no possibility of creating a
275  * conflicting relation.
276  *
277  * Note: any failure should be reported as WARNING not ERROR, because
278  * we are usually not in a transaction anymore when this is called.
279  */
280 void
281 mdunlink(RelFileNodeBackend rnode, ForkNumber forkNum, bool isRedo)
282 {
283  /* Now do the per-fork work */
284  if (forkNum == InvalidForkNumber)
285  {
286  for (forkNum = 0; forkNum <= MAX_FORKNUM; forkNum++)
287  mdunlinkfork(rnode, forkNum, isRedo);
288  }
289  else
290  mdunlinkfork(rnode, forkNum, isRedo);
291 }
292 
293 /*
294  * Truncate a file to release disk space.
295  */
296 static int
297 do_truncate(const char *path)
298 {
299  int save_errno;
300  int ret;
301 
302  ret = pg_truncate(path, 0);
303 
304  /* Log a warning here to avoid repetition in callers. */
305  if (ret < 0 && errno != ENOENT)
306  {
307  save_errno = errno;
310  errmsg("could not truncate file \"%s\": %m", path)));
311  errno = save_errno;
312  }
313 
314  return ret;
315 }
316 
317 static void
318 mdunlinkfork(RelFileNodeBackend rnode, ForkNumber forkNum, bool isRedo)
319 {
320  char *path;
321  int ret;
322 
323  path = relpath(rnode, forkNum);
324 
325  /*
326  * Delete or truncate the first segment.
327  */
328  if (isRedo || forkNum != MAIN_FORKNUM || RelFileNodeBackendIsTemp(rnode))
329  {
330  if (!RelFileNodeBackendIsTemp(rnode))
331  {
332  /* Prevent other backends' fds from holding on to the disk space */
333  ret = do_truncate(path);
334 
335  /* Forget any pending sync requests for the first segment */
336  register_forget_request(rnode, forkNum, 0 /* first seg */ );
337  }
338  else
339  ret = 0;
340 
341  /* Next unlink the file, unless it was already found to be missing */
342  if (ret == 0 || errno != ENOENT)
343  {
344  ret = unlink(path);
345  if (ret < 0 && errno != ENOENT)
348  errmsg("could not remove file \"%s\": %m", path)));
349  }
350  }
351  else
352  {
353  /* Prevent other backends' fds from holding on to the disk space */
354  ret = do_truncate(path);
355 
356  /* Register request to unlink first segment later */
357  register_unlink_segment(rnode, forkNum, 0 /* first seg */ );
358  }
359 
360  /*
361  * Delete any additional segments.
362  */
363  if (ret >= 0)
364  {
365  char *segpath = (char *) palloc(strlen(path) + 12);
366  BlockNumber segno;
367 
368  /*
369  * Note that because we loop until getting ENOENT, we will correctly
370  * remove all inactive segments as well as active ones.
371  */
372  for (segno = 1;; segno++)
373  {
374  sprintf(segpath, "%s.%u", path, segno);
375 
376  if (!RelFileNodeBackendIsTemp(rnode))
377  {
378  /*
379  * Prevent other backends' fds from holding on to the disk
380  * space.
381  */
382  if (do_truncate(segpath) < 0 && errno == ENOENT)
383  break;
384 
385  /*
386  * Forget any pending sync requests for this segment before we
387  * try to unlink.
388  */
389  register_forget_request(rnode, forkNum, segno);
390  }
391 
392  if (unlink(segpath) < 0)
393  {
394  /* ENOENT is expected after the last segment... */
395  if (errno != ENOENT)
398  errmsg("could not remove file \"%s\": %m", segpath)));
399  break;
400  }
401  }
402  pfree(segpath);
403  }
404 
405  pfree(path);
406 }
407 
408 /*
409  * mdextend() -- Add a block to the specified relation.
410  *
411  * The semantics are nearly the same as mdwrite(): write at the
412  * specified position. However, this is to be used for the case of
413  * extending a relation (i.e., blocknum is at or beyond the current
414  * EOF). Note that we assume writing a block beyond current EOF
415  * causes intervening file space to become filled with zeroes.
416  */
417 void
418 mdextend(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum,
419  char *buffer, bool skipFsync)
420 {
421  off_t seekpos;
422  int nbytes;
423  MdfdVec *v;
424 
425  /* This assert is too expensive to have on normally ... */
426 #ifdef CHECK_WRITE_VS_EXTEND
427  Assert(blocknum >= mdnblocks(reln, forknum));
428 #endif
429 
430  /*
431  * If a relation manages to grow to 2^32-1 blocks, refuse to extend it any
432  * more --- we mustn't create a block whose number actually is
433  * InvalidBlockNumber. (Note that this failure should be unreachable
434  * because of upstream checks in bufmgr.c.)
435  */
436  if (blocknum == InvalidBlockNumber)
437  ereport(ERROR,
438  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
439  errmsg("cannot extend file \"%s\" beyond %u blocks",
440  relpath(reln->smgr_rnode, forknum),
442 
443  v = _mdfd_getseg(reln, forknum, blocknum, skipFsync, EXTENSION_CREATE);
444 
445  seekpos = (off_t) BLCKSZ * (blocknum % ((BlockNumber) RELSEG_SIZE));
446 
447  Assert(seekpos < (off_t) BLCKSZ * RELSEG_SIZE);
448 
449  if ((nbytes = FileWrite(v->mdfd_vfd, buffer, BLCKSZ, seekpos, WAIT_EVENT_DATA_FILE_EXTEND)) != BLCKSZ)
450  {
451  if (nbytes < 0)
452  ereport(ERROR,
454  errmsg("could not extend file \"%s\": %m",
455  FilePathName(v->mdfd_vfd)),
456  errhint("Check free disk space.")));
457  /* short write: complain appropriately */
458  ereport(ERROR,
459  (errcode(ERRCODE_DISK_FULL),
460  errmsg("could not extend file \"%s\": wrote only %d of %d bytes at block %u",
462  nbytes, BLCKSZ, blocknum),
463  errhint("Check free disk space.")));
464  }
465 
466  if (!skipFsync && !SmgrIsTemp(reln))
467  register_dirty_segment(reln, forknum, v);
468 
469  Assert(_mdnblocks(reln, forknum, v) <= ((BlockNumber) RELSEG_SIZE));
470 }
471 
472 /*
473  * mdopenfork() -- Open one fork of the specified relation.
474  *
475  * Note we only open the first segment, when there are multiple segments.
476  *
477  * If first segment is not present, either ereport or return NULL according
478  * to "behavior". We treat EXTENSION_CREATE the same as EXTENSION_FAIL;
479  * EXTENSION_CREATE means it's OK to extend an existing relation, not to
480  * invent one out of whole cloth.
481  */
482 static MdfdVec *
483 mdopenfork(SMgrRelation reln, ForkNumber forknum, int behavior)
484 {
485  MdfdVec *mdfd;
486  char *path;
487  File fd;
488 
489  /* No work if already open */
490  if (reln->md_num_open_segs[forknum] > 0)
491  return &reln->md_seg_fds[forknum][0];
492 
493  path = relpath(reln->smgr_rnode, forknum);
494 
495  fd = PathNameOpenFile(path, O_RDWR | PG_BINARY);
496 
497  if (fd < 0)
498  {
499  if ((behavior & EXTENSION_RETURN_NULL) &&
500  FILE_POSSIBLY_DELETED(errno))
501  {
502  pfree(path);
503  return NULL;
504  }
505  ereport(ERROR,
507  errmsg("could not open file \"%s\": %m", path)));
508  }
509 
510  pfree(path);
511 
512  _fdvec_resize(reln, forknum, 1);
513  mdfd = &reln->md_seg_fds[forknum][0];
514  mdfd->mdfd_vfd = fd;
515  mdfd->mdfd_segno = 0;
516 
517  Assert(_mdnblocks(reln, forknum, mdfd) <= ((BlockNumber) RELSEG_SIZE));
518 
519  return mdfd;
520 }
521 
522 /*
523  * mdopen() -- Initialize newly-opened relation.
524  */
525 void
527 {
528  /* mark it not open */
529  for (int forknum = 0; forknum <= MAX_FORKNUM; forknum++)
530  reln->md_num_open_segs[forknum] = 0;
531 }
532 
533 /*
534  * mdclose() -- Close the specified relation, if it isn't closed already.
535  */
536 void
538 {
539  int nopensegs = reln->md_num_open_segs[forknum];
540 
541  /* No work if already closed */
542  if (nopensegs == 0)
543  return;
544 
545  /* close segments starting from the end */
546  while (nopensegs > 0)
547  {
548  MdfdVec *v = &reln->md_seg_fds[forknum][nopensegs - 1];
549 
550  FileClose(v->mdfd_vfd);
551  _fdvec_resize(reln, forknum, nopensegs - 1);
552  nopensegs--;
553  }
554 }
555 
556 /*
557  * mdprefetch() -- Initiate asynchronous read of the specified block of a relation
558  */
559 bool
561 {
562 #ifdef USE_PREFETCH
563  off_t seekpos;
564  MdfdVec *v;
565 
566  v = _mdfd_getseg(reln, forknum, blocknum, false,
568  if (v == NULL)
569  return false;
570 
571  seekpos = (off_t) BLCKSZ * (blocknum % ((BlockNumber) RELSEG_SIZE));
572 
573  Assert(seekpos < (off_t) BLCKSZ * RELSEG_SIZE);
574 
575  (void) FilePrefetch(v->mdfd_vfd, seekpos, BLCKSZ, WAIT_EVENT_DATA_FILE_PREFETCH);
576 #endif /* USE_PREFETCH */
577 
578  return true;
579 }
580 
581 /*
582  * mdwriteback() -- Tell the kernel to write pages back to storage.
583  *
584  * This accepts a range of blocks because flushing several pages at once is
585  * considerably more efficient than doing so individually.
586  */
587 void
589  BlockNumber blocknum, BlockNumber nblocks)
590 {
591  /*
592  * Issue flush requests in as few requests as possible; have to split at
593  * segment boundaries though, since those are actually separate files.
594  */
595  while (nblocks > 0)
596  {
597  BlockNumber nflush = nblocks;
598  off_t seekpos;
599  MdfdVec *v;
600  int segnum_start,
601  segnum_end;
602 
603  v = _mdfd_getseg(reln, forknum, blocknum, true /* not used */ ,
605 
606  /*
607  * We might be flushing buffers of already removed relations, that's
608  * ok, just ignore that case. If the segment file wasn't open already
609  * (ie from a recent mdwrite()), then we don't want to re-open it, to
610  * avoid a race with PROCSIGNAL_BARRIER_SMGRRELEASE that might leave
611  * us with a descriptor to a file that is about to be unlinked.
612  */
613  if (!v)
614  return;
615 
616  /* compute offset inside the current segment */
617  segnum_start = blocknum / RELSEG_SIZE;
618 
619  /* compute number of desired writes within the current segment */
620  segnum_end = (blocknum + nblocks - 1) / RELSEG_SIZE;
621  if (segnum_start != segnum_end)
622  nflush = RELSEG_SIZE - (blocknum % ((BlockNumber) RELSEG_SIZE));
623 
624  Assert(nflush >= 1);
625  Assert(nflush <= nblocks);
626 
627  seekpos = (off_t) BLCKSZ * (blocknum % ((BlockNumber) RELSEG_SIZE));
628 
629  FileWriteback(v->mdfd_vfd, seekpos, (off_t) BLCKSZ * nflush, WAIT_EVENT_DATA_FILE_FLUSH);
630 
631  nblocks -= nflush;
632  blocknum += nflush;
633  }
634 }
635 
636 /*
637  * mdread() -- Read the specified block from a relation.
638  */
639 void
640 mdread(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum,
641  char *buffer)
642 {
643  off_t seekpos;
644  int nbytes;
645  MdfdVec *v;
646 
647  TRACE_POSTGRESQL_SMGR_MD_READ_START(forknum, blocknum,
648  reln->smgr_rnode.node.spcNode,
649  reln->smgr_rnode.node.dbNode,
650  reln->smgr_rnode.node.relNode,
651  reln->smgr_rnode.backend);
652 
653  v = _mdfd_getseg(reln, forknum, blocknum, false,
655 
656  seekpos = (off_t) BLCKSZ * (blocknum % ((BlockNumber) RELSEG_SIZE));
657 
658  Assert(seekpos < (off_t) BLCKSZ * RELSEG_SIZE);
659 
660  nbytes = FileRead(v->mdfd_vfd, buffer, BLCKSZ, seekpos, WAIT_EVENT_DATA_FILE_READ);
661 
662  TRACE_POSTGRESQL_SMGR_MD_READ_DONE(forknum, blocknum,
663  reln->smgr_rnode.node.spcNode,
664  reln->smgr_rnode.node.dbNode,
665  reln->smgr_rnode.node.relNode,
666  reln->smgr_rnode.backend,
667  nbytes,
668  BLCKSZ);
669 
670  if (nbytes != BLCKSZ)
671  {
672  if (nbytes < 0)
673  ereport(ERROR,
675  errmsg("could not read block %u in file \"%s\": %m",
676  blocknum, FilePathName(v->mdfd_vfd))));
677 
678  /*
679  * Short read: we are at or past EOF, or we read a partial block at
680  * EOF. Normally this is an error; upper levels should never try to
681  * read a nonexistent block. However, if zero_damaged_pages is ON or
682  * we are InRecovery, we should instead return zeroes without
683  * complaining. This allows, for example, the case of trying to
684  * update a block that was later truncated away.
685  */
687  MemSet(buffer, 0, BLCKSZ);
688  else
689  ereport(ERROR,
691  errmsg("could not read block %u in file \"%s\": read only %d of %d bytes",
692  blocknum, FilePathName(v->mdfd_vfd),
693  nbytes, BLCKSZ)));
694  }
695 }
696 
697 /*
698  * mdwrite() -- Write the supplied block at the appropriate location.
699  *
700  * This is to be used only for updating already-existing blocks of a
701  * relation (ie, those before the current EOF). To extend a relation,
702  * use mdextend().
703  */
704 void
705 mdwrite(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum,
706  char *buffer, bool skipFsync)
707 {
708  off_t seekpos;
709  int nbytes;
710  MdfdVec *v;
711 
712  /* This assert is too expensive to have on normally ... */
713 #ifdef CHECK_WRITE_VS_EXTEND
714  Assert(blocknum < mdnblocks(reln, forknum));
715 #endif
716 
717  TRACE_POSTGRESQL_SMGR_MD_WRITE_START(forknum, blocknum,
718  reln->smgr_rnode.node.spcNode,
719  reln->smgr_rnode.node.dbNode,
720  reln->smgr_rnode.node.relNode,
721  reln->smgr_rnode.backend);
722 
723  v = _mdfd_getseg(reln, forknum, blocknum, skipFsync,
725 
726  seekpos = (off_t) BLCKSZ * (blocknum % ((BlockNumber) RELSEG_SIZE));
727 
728  Assert(seekpos < (off_t) BLCKSZ * RELSEG_SIZE);
729 
730  nbytes = FileWrite(v->mdfd_vfd, buffer, BLCKSZ, seekpos, WAIT_EVENT_DATA_FILE_WRITE);
731 
732  TRACE_POSTGRESQL_SMGR_MD_WRITE_DONE(forknum, blocknum,
733  reln->smgr_rnode.node.spcNode,
734  reln->smgr_rnode.node.dbNode,
735  reln->smgr_rnode.node.relNode,
736  reln->smgr_rnode.backend,
737  nbytes,
738  BLCKSZ);
739 
740  if (nbytes != BLCKSZ)
741  {
742  if (nbytes < 0)
743  ereport(ERROR,
745  errmsg("could not write block %u in file \"%s\": %m",
746  blocknum, FilePathName(v->mdfd_vfd))));
747  /* short write: complain appropriately */
748  ereport(ERROR,
749  (errcode(ERRCODE_DISK_FULL),
750  errmsg("could not write block %u in file \"%s\": wrote only %d of %d bytes",
751  blocknum,
753  nbytes, BLCKSZ),
754  errhint("Check free disk space.")));
755  }
756 
757  if (!skipFsync && !SmgrIsTemp(reln))
758  register_dirty_segment(reln, forknum, v);
759 }
760 
761 /*
762  * mdnblocks() -- Get the number of blocks stored in a relation.
763  *
764  * Important side effect: all active segments of the relation are opened
765  * and added to the md_seg_fds array. If this routine has not been
766  * called, then only segments up to the last one actually touched
767  * are present in the array.
768  */
771 {
772  MdfdVec *v;
773  BlockNumber nblocks;
774  BlockNumber segno;
775 
776  mdopenfork(reln, forknum, EXTENSION_FAIL);
777 
778  /* mdopen has opened the first segment */
779  Assert(reln->md_num_open_segs[forknum] > 0);
780 
781  /*
782  * Start from the last open segments, to avoid redundant seeks. We have
783  * previously verified that these segments are exactly RELSEG_SIZE long,
784  * and it's useless to recheck that each time.
785  *
786  * NOTE: this assumption could only be wrong if another backend has
787  * truncated the relation. We rely on higher code levels to handle that
788  * scenario by closing and re-opening the md fd, which is handled via
789  * relcache flush. (Since the checkpointer doesn't participate in
790  * relcache flush, it could have segment entries for inactive segments;
791  * that's OK because the checkpointer never needs to compute relation
792  * size.)
793  */
794  segno = reln->md_num_open_segs[forknum] - 1;
795  v = &reln->md_seg_fds[forknum][segno];
796 
797  for (;;)
798  {
799  nblocks = _mdnblocks(reln, forknum, v);
800  if (nblocks > ((BlockNumber) RELSEG_SIZE))
801  elog(FATAL, "segment too big");
802  if (nblocks < ((BlockNumber) RELSEG_SIZE))
803  return (segno * ((BlockNumber) RELSEG_SIZE)) + nblocks;
804 
805  /*
806  * If segment is exactly RELSEG_SIZE, advance to next one.
807  */
808  segno++;
809 
810  /*
811  * We used to pass O_CREAT here, but that has the disadvantage that it
812  * might create a segment which has vanished through some operating
813  * system misadventure. In such a case, creating the segment here
814  * undermines _mdfd_getseg's attempts to notice and report an error
815  * upon access to a missing segment.
816  */
817  v = _mdfd_openseg(reln, forknum, segno, 0);
818  if (v == NULL)
819  return segno * ((BlockNumber) RELSEG_SIZE);
820  }
821 }
822 
823 /*
824  * mdtruncate() -- Truncate relation to specified number of blocks.
825  */
826 void
828 {
829  BlockNumber curnblk;
830  BlockNumber priorblocks;
831  int curopensegs;
832 
833  /*
834  * NOTE: mdnblocks makes sure we have opened all active segments, so that
835  * truncation loop will get them all!
836  */
837  curnblk = mdnblocks(reln, forknum);
838  if (nblocks > curnblk)
839  {
840  /* Bogus request ... but no complaint if InRecovery */
841  if (InRecovery)
842  return;
843  ereport(ERROR,
844  (errmsg("could not truncate file \"%s\" to %u blocks: it's only %u blocks now",
845  relpath(reln->smgr_rnode, forknum),
846  nblocks, curnblk)));
847  }
848  if (nblocks == curnblk)
849  return; /* no work */
850 
851  /*
852  * Truncate segments, starting at the last one. Starting at the end makes
853  * managing the memory for the fd array easier, should there be errors.
854  */
855  curopensegs = reln->md_num_open_segs[forknum];
856  while (curopensegs > 0)
857  {
858  MdfdVec *v;
859 
860  priorblocks = (curopensegs - 1) * RELSEG_SIZE;
861 
862  v = &reln->md_seg_fds[forknum][curopensegs - 1];
863 
864  if (priorblocks > nblocks)
865  {
866  /*
867  * This segment is no longer active. We truncate the file, but do
868  * not delete it, for reasons explained in the header comments.
869  */
871  ereport(ERROR,
873  errmsg("could not truncate file \"%s\": %m",
874  FilePathName(v->mdfd_vfd))));
875 
876  if (!SmgrIsTemp(reln))
877  register_dirty_segment(reln, forknum, v);
878 
879  /* we never drop the 1st segment */
880  Assert(v != &reln->md_seg_fds[forknum][0]);
881 
882  FileClose(v->mdfd_vfd);
883  _fdvec_resize(reln, forknum, curopensegs - 1);
884  }
885  else if (priorblocks + ((BlockNumber) RELSEG_SIZE) > nblocks)
886  {
887  /*
888  * This is the last segment we want to keep. Truncate the file to
889  * the right length. NOTE: if nblocks is exactly a multiple K of
890  * RELSEG_SIZE, we will truncate the K+1st segment to 0 length but
891  * keep it. This adheres to the invariant given in the header
892  * comments.
893  */
894  BlockNumber lastsegblocks = nblocks - priorblocks;
895 
896  if (FileTruncate(v->mdfd_vfd, (off_t) lastsegblocks * BLCKSZ, WAIT_EVENT_DATA_FILE_TRUNCATE) < 0)
897  ereport(ERROR,
899  errmsg("could not truncate file \"%s\" to %u blocks: %m",
901  nblocks)));
902  if (!SmgrIsTemp(reln))
903  register_dirty_segment(reln, forknum, v);
904  }
905  else
906  {
907  /*
908  * We still need this segment, so nothing to do for this and any
909  * earlier segment.
910  */
911  break;
912  }
913  curopensegs--;
914  }
915 }
916 
917 /*
918  * mdimmedsync() -- Immediately sync a relation to stable storage.
919  *
920  * Note that only writes already issued are synced; this routine knows
921  * nothing of dirty buffers that may exist inside the buffer manager. We
922  * sync active and inactive segments; smgrDoPendingSyncs() relies on this.
923  * Consider a relation skipping WAL. Suppose a checkpoint syncs blocks of
924  * some segment, then mdtruncate() renders that segment inactive. If we
925  * crash before the next checkpoint syncs the newly-inactive segment, that
926  * segment may survive recovery, reintroducing unwanted data into the table.
927  */
928 void
930 {
931  int segno;
932  int min_inactive_seg;
933 
934  /*
935  * NOTE: mdnblocks makes sure we have opened all active segments, so that
936  * fsync loop will get them all!
937  */
938  mdnblocks(reln, forknum);
939 
940  min_inactive_seg = segno = reln->md_num_open_segs[forknum];
941 
942  /*
943  * Temporarily open inactive segments, then close them after sync. There
944  * may be some inactive segments left opened after fsync() error, but that
945  * is harmless. We don't bother to clean them up and take a risk of
946  * further trouble. The next mdclose() will soon close them.
947  */
948  while (_mdfd_openseg(reln, forknum, segno, 0) != NULL)
949  segno++;
950 
951  while (segno > 0)
952  {
953  MdfdVec *v = &reln->md_seg_fds[forknum][segno - 1];
954 
958  errmsg("could not fsync file \"%s\": %m",
959  FilePathName(v->mdfd_vfd))));
960 
961  /* Close inactive segments immediately */
962  if (segno > min_inactive_seg)
963  {
964  FileClose(v->mdfd_vfd);
965  _fdvec_resize(reln, forknum, segno - 1);
966  }
967 
968  segno--;
969  }
970 }
971 
972 /*
973  * register_dirty_segment() -- Mark a relation segment as needing fsync
974  *
975  * If there is a local pending-ops table, just make an entry in it for
976  * ProcessSyncRequests to process later. Otherwise, try to pass off the
977  * fsync request to the checkpointer process. If that fails, just do the
978  * fsync locally before returning (we hope this will not happen often
979  * enough to be a performance problem).
980  */
981 static void
983 {
984  FileTag tag;
985 
986  INIT_MD_FILETAG(tag, reln->smgr_rnode.node, forknum, seg->mdfd_segno);
987 
988  /* Temp relations should never be fsync'd */
989  Assert(!SmgrIsTemp(reln));
990 
991  if (!RegisterSyncRequest(&tag, SYNC_REQUEST, false /* retryOnError */ ))
992  {
993  ereport(DEBUG1,
994  (errmsg_internal("could not forward fsync request because request queue is full")));
995 
999  errmsg("could not fsync file \"%s\": %m",
1000  FilePathName(seg->mdfd_vfd))));
1001  }
1002 }
1003 
1004 /*
1005  * register_unlink_segment() -- Schedule a file to be deleted after next checkpoint
1006  */
1007 static void
1009  BlockNumber segno)
1010 {
1011  FileTag tag;
1012 
1013  INIT_MD_FILETAG(tag, rnode.node, forknum, segno);
1014 
1015  /* Should never be used with temp relations */
1017 
1018  RegisterSyncRequest(&tag, SYNC_UNLINK_REQUEST, true /* retryOnError */ );
1019 }
1020 
1021 /*
1022  * register_forget_request() -- forget any fsyncs for a relation fork's segment
1023  */
1024 static void
1026  BlockNumber segno)
1027 {
1028  FileTag tag;
1029 
1030  INIT_MD_FILETAG(tag, rnode.node, forknum, segno);
1031 
1032  RegisterSyncRequest(&tag, SYNC_FORGET_REQUEST, true /* retryOnError */ );
1033 }
1034 
1035 /*
1036  * ForgetDatabaseSyncRequests -- forget any fsyncs and unlinks for a DB
1037  */
1038 void
1040 {
1041  FileTag tag;
1042  RelFileNode rnode;
1043 
1044  rnode.dbNode = dbid;
1045  rnode.spcNode = 0;
1046  rnode.relNode = 0;
1047 
1049 
1050  RegisterSyncRequest(&tag, SYNC_FILTER_REQUEST, true /* retryOnError */ );
1051 }
1052 
1053 /*
1054  * DropRelationFiles -- drop files of all given relations
1055  */
1056 void
1057 DropRelationFiles(RelFileNode *delrels, int ndelrels, bool isRedo)
1058 {
1059  SMgrRelation *srels;
1060  int i;
1061 
1062  srels = palloc(sizeof(SMgrRelation) * ndelrels);
1063  for (i = 0; i < ndelrels; i++)
1064  {
1065  SMgrRelation srel = smgropen(delrels[i], InvalidBackendId);
1066 
1067  if (isRedo)
1068  {
1069  ForkNumber fork;
1070 
1071  for (fork = 0; fork <= MAX_FORKNUM; fork++)
1072  XLogDropRelation(delrels[i], fork);
1073  }
1074  srels[i] = srel;
1075  }
1076 
1077  smgrdounlinkall(srels, ndelrels, isRedo);
1078 
1079  for (i = 0; i < ndelrels; i++)
1080  smgrclose(srels[i]);
1081  pfree(srels);
1082 }
1083 
1084 
1085 /*
1086  * _fdvec_resize() -- Resize the fork's open segments array
1087  */
1088 static void
1090  ForkNumber forknum,
1091  int nseg)
1092 {
1093  if (nseg == 0)
1094  {
1095  if (reln->md_num_open_segs[forknum] > 0)
1096  {
1097  pfree(reln->md_seg_fds[forknum]);
1098  reln->md_seg_fds[forknum] = NULL;
1099  }
1100  }
1101  else if (reln->md_num_open_segs[forknum] == 0)
1102  {
1103  reln->md_seg_fds[forknum] =
1104  MemoryContextAlloc(MdCxt, sizeof(MdfdVec) * nseg);
1105  }
1106  else
1107  {
1108  /*
1109  * It doesn't seem worthwhile complicating the code to amortize
1110  * repalloc() calls. Those are far faster than PathNameOpenFile() or
1111  * FileClose(), and the memory context internally will sometimes avoid
1112  * doing an actual reallocation.
1113  */
1114  reln->md_seg_fds[forknum] =
1115  repalloc(reln->md_seg_fds[forknum],
1116  sizeof(MdfdVec) * nseg);
1117  }
1118 
1119  reln->md_num_open_segs[forknum] = nseg;
1120 }
1121 
1122 /*
1123  * Return the filename for the specified segment of the relation. The
1124  * returned string is palloc'd.
1125  */
1126 static char *
1128 {
1129  char *path,
1130  *fullpath;
1131 
1132  path = relpath(reln->smgr_rnode, forknum);
1133 
1134  if (segno > 0)
1135  {
1136  fullpath = psprintf("%s.%u", path, segno);
1137  pfree(path);
1138  }
1139  else
1140  fullpath = path;
1141 
1142  return fullpath;
1143 }
1144 
1145 /*
1146  * Open the specified segment of the relation,
1147  * and make a MdfdVec object for it. Returns NULL on failure.
1148  */
1149 static MdfdVec *
1151  int oflags)
1152 {
1153  MdfdVec *v;
1154  File fd;
1155  char *fullpath;
1156 
1157  fullpath = _mdfd_segpath(reln, forknum, segno);
1158 
1159  /* open the file */
1160  fd = PathNameOpenFile(fullpath, O_RDWR | PG_BINARY | oflags);
1161 
1162  pfree(fullpath);
1163 
1164  if (fd < 0)
1165  return NULL;
1166 
1167  /*
1168  * Segments are always opened in order from lowest to highest, so we must
1169  * be adding a new one at the end.
1170  */
1171  Assert(segno == reln->md_num_open_segs[forknum]);
1172 
1173  _fdvec_resize(reln, forknum, segno + 1);
1174 
1175  /* fill the entry */
1176  v = &reln->md_seg_fds[forknum][segno];
1177  v->mdfd_vfd = fd;
1178  v->mdfd_segno = segno;
1179 
1180  Assert(_mdnblocks(reln, forknum, v) <= ((BlockNumber) RELSEG_SIZE));
1181 
1182  /* all done */
1183  return v;
1184 }
1185 
1186 /*
1187  * _mdfd_getseg() -- Find the segment of the relation holding the
1188  * specified block.
1189  *
1190  * If the segment doesn't exist, we ereport, return NULL, or create the
1191  * segment, according to "behavior". Note: skipFsync is only used in the
1192  * EXTENSION_CREATE case.
1193  */
1194 static MdfdVec *
1196  bool skipFsync, int behavior)
1197 {
1198  MdfdVec *v;
1199  BlockNumber targetseg;
1200  BlockNumber nextsegno;
1201 
1202  /* some way to handle non-existent segments needs to be specified */
1203  Assert(behavior &
1206 
1207  targetseg = blkno / ((BlockNumber) RELSEG_SIZE);
1208 
1209  /* if an existing and opened segment, we're done */
1210  if (targetseg < reln->md_num_open_segs[forknum])
1211  {
1212  v = &reln->md_seg_fds[forknum][targetseg];
1213  return v;
1214  }
1215 
1216  /* The caller only wants the segment if we already had it open. */
1217  if (behavior & EXTENSION_DONT_OPEN)
1218  return NULL;
1219 
1220  /*
1221  * The target segment is not yet open. Iterate over all the segments
1222  * between the last opened and the target segment. This way missing
1223  * segments either raise an error, or get created (according to
1224  * 'behavior'). Start with either the last opened, or the first segment if
1225  * none was opened before.
1226  */
1227  if (reln->md_num_open_segs[forknum] > 0)
1228  v = &reln->md_seg_fds[forknum][reln->md_num_open_segs[forknum] - 1];
1229  else
1230  {
1231  v = mdopenfork(reln, forknum, behavior);
1232  if (!v)
1233  return NULL; /* if behavior & EXTENSION_RETURN_NULL */
1234  }
1235 
1236  for (nextsegno = reln->md_num_open_segs[forknum];
1237  nextsegno <= targetseg; nextsegno++)
1238  {
1239  BlockNumber nblocks = _mdnblocks(reln, forknum, v);
1240  int flags = 0;
1241 
1242  Assert(nextsegno == v->mdfd_segno + 1);
1243 
1244  if (nblocks > ((BlockNumber) RELSEG_SIZE))
1245  elog(FATAL, "segment too big");
1246 
1247  if ((behavior & EXTENSION_CREATE) ||
1248  (InRecovery && (behavior & EXTENSION_CREATE_RECOVERY)))
1249  {
1250  /*
1251  * Normally we will create new segments only if authorized by the
1252  * caller (i.e., we are doing mdextend()). But when doing WAL
1253  * recovery, create segments anyway; this allows cases such as
1254  * replaying WAL data that has a write into a high-numbered
1255  * segment of a relation that was later deleted. We want to go
1256  * ahead and create the segments so we can finish out the replay.
1257  *
1258  * We have to maintain the invariant that segments before the last
1259  * active segment are of size RELSEG_SIZE; therefore, if
1260  * extending, pad them out with zeroes if needed. (This only
1261  * matters if in recovery, or if the caller is extending the
1262  * relation discontiguously, but that can happen in hash indexes.)
1263  */
1264  if (nblocks < ((BlockNumber) RELSEG_SIZE))
1265  {
1266  char *zerobuf = palloc0(BLCKSZ);
1267 
1268  mdextend(reln, forknum,
1269  nextsegno * ((BlockNumber) RELSEG_SIZE) - 1,
1270  zerobuf, skipFsync);
1271  pfree(zerobuf);
1272  }
1273  flags = O_CREAT;
1274  }
1275  else if (!(behavior & EXTENSION_DONT_CHECK_SIZE) &&
1276  nblocks < ((BlockNumber) RELSEG_SIZE))
1277  {
1278  /*
1279  * When not extending (or explicitly including truncated
1280  * segments), only open the next segment if the current one is
1281  * exactly RELSEG_SIZE. If not (this branch), either return NULL
1282  * or fail.
1283  */
1284  if (behavior & EXTENSION_RETURN_NULL)
1285  {
1286  /*
1287  * Some callers discern between reasons for _mdfd_getseg()
1288  * returning NULL based on errno. As there's no failing
1289  * syscall involved in this case, explicitly set errno to
1290  * ENOENT, as that seems the closest interpretation.
1291  */
1292  errno = ENOENT;
1293  return NULL;
1294  }
1295 
1296  ereport(ERROR,
1298  errmsg("could not open file \"%s\" (target block %u): previous segment is only %u blocks",
1299  _mdfd_segpath(reln, forknum, nextsegno),
1300  blkno, nblocks)));
1301  }
1302 
1303  v = _mdfd_openseg(reln, forknum, nextsegno, flags);
1304 
1305  if (v == NULL)
1306  {
1307  if ((behavior & EXTENSION_RETURN_NULL) &&
1308  FILE_POSSIBLY_DELETED(errno))
1309  return NULL;
1310  ereport(ERROR,
1312  errmsg("could not open file \"%s\" (target block %u): %m",
1313  _mdfd_segpath(reln, forknum, nextsegno),
1314  blkno)));
1315  }
1316  }
1317 
1318  return v;
1319 }
1320 
1321 /*
1322  * Get number of blocks present in a single disk file
1323  */
1324 static BlockNumber
1326 {
1327  off_t len;
1328 
1329  len = FileSize(seg->mdfd_vfd);
1330  if (len < 0)
1331  ereport(ERROR,
1333  errmsg("could not seek to end of file \"%s\": %m",
1334  FilePathName(seg->mdfd_vfd))));
1335  /* note that this calculation will ignore any partial block at EOF */
1336  return (BlockNumber) (len / BLCKSZ);
1337 }
1338 
1339 /*
1340  * Sync a file to disk, given a file tag. Write the path into an output
1341  * buffer so the caller can use it in error messages.
1342  *
1343  * Return 0 on success, -1 on failure, with errno set.
1344  */
1345 int
1346 mdsyncfiletag(const FileTag *ftag, char *path)
1347 {
1349  File file;
1350  bool need_to_close;
1351  int result,
1352  save_errno;
1353 
1354  /* See if we already have the file open, or need to open it. */
1355  if (ftag->segno < reln->md_num_open_segs[ftag->forknum])
1356  {
1357  file = reln->md_seg_fds[ftag->forknum][ftag->segno].mdfd_vfd;
1358  strlcpy(path, FilePathName(file), MAXPGPATH);
1359  need_to_close = false;
1360  }
1361  else
1362  {
1363  char *p;
1364 
1365  p = _mdfd_segpath(reln, ftag->forknum, ftag->segno);
1366  strlcpy(path, p, MAXPGPATH);
1367  pfree(p);
1368 
1369  file = PathNameOpenFile(path, O_RDWR | PG_BINARY);
1370  if (file < 0)
1371  return -1;
1372  need_to_close = true;
1373  }
1374 
1375  /* Sync the file. */
1376  result = FileSync(file, WAIT_EVENT_DATA_FILE_SYNC);
1377  save_errno = errno;
1378 
1379  if (need_to_close)
1380  FileClose(file);
1381 
1382  errno = save_errno;
1383  return result;
1384 }
1385 
1386 /*
1387  * Unlink a file, given a file tag. Write the path into an output
1388  * buffer so the caller can use it in error messages.
1389  *
1390  * Return 0 on success, -1 on failure, with errno set.
1391  */
1392 int
1393 mdunlinkfiletag(const FileTag *ftag, char *path)
1394 {
1395  char *p;
1396 
1397  /* Compute the path. */
1398  p = relpathperm(ftag->rnode, MAIN_FORKNUM);
1399  strlcpy(path, p, MAXPGPATH);
1400  pfree(p);
1401 
1402  /* Try to unlink the file. */
1403  return unlink(path);
1404 }
1405 
1406 /*
1407  * Check if a given candidate request matches a given tag, when processing
1408  * a SYNC_FILTER_REQUEST request. This will be called for all pending
1409  * requests to find out whether to forget them.
1410  */
1411 bool
1412 mdfiletagmatches(const FileTag *ftag, const FileTag *candidate)
1413 {
1414  /*
1415  * For now we only use filter requests as a way to drop all scheduled
1416  * callbacks relating to a given database, when dropping the database.
1417  * We'll return true for all candidates that have the same database OID as
1418  * the ftag from the SYNC_FILTER_REQUEST request, so they're forgotten.
1419  */
1420  return ftag->rnode.dbNode == candidate->rnode.dbNode;
1421 }
void TablespaceCreateDbspace(Oid spcNode, Oid dbNode, bool isRedo)
Definition: tablespace.c:118
#define InvalidBackendId
Definition: backendid.h:23
uint32 BlockNumber
Definition: block.h:31
#define InvalidBlockNumber
Definition: block.h:33
bool zero_damaged_pages
Definition: bufmgr.c:134
#define PG_BINARY
Definition: c.h:1268
#define MemSet(start, val, len)
Definition: c.h:1008
int errmsg_internal(const char *fmt,...)
Definition: elog.c:991
int errcode_for_file_access(void)
Definition: elog.c:716
int errhint(const char *fmt,...)
Definition: elog.c:1151
int errcode(int sqlerrcode)
Definition: elog.c:693
int errmsg(const char *fmt,...)
Definition: elog.c:904
#define FATAL
Definition: elog.h:35
#define WARNING
Definition: elog.h:30
#define DEBUG1
Definition: elog.h:24
#define ERROR
Definition: elog.h:33
#define elog(elevel,...)
Definition: elog.h:218
#define ereport(elevel,...)
Definition: elog.h:143
void FileWriteback(File file, off_t offset, off_t nbytes, uint32 wait_event_info)
Definition: fd.c:2089
int FilePrefetch(File file, off_t offset, int amount, uint32 wait_event_info)
Definition: fd.c:2061
int FileSync(File file, uint32 wait_event_info)
Definition: fd.c:2266
void FileClose(File file)
Definition: fd.c:1961
int data_sync_elevel(int elevel)
Definition: fd.c:3826
File PathNameOpenFile(const char *fileName, int fileFlags)
Definition: fd.c:1566
int FileWrite(File file, char *buffer, int amount, off_t offset, uint32 wait_event_info)
Definition: fd.c:2168
char * FilePathName(File file)
Definition: fd.c:2339
int FileRead(File file, char *buffer, int amount, off_t offset, uint32 wait_event_info)
Definition: fd.c:2112
off_t FileSize(File file)
Definition: fd.c:2287
int FileTruncate(File file, off_t offset, uint32 wait_event_info)
Definition: fd.c:2304
int pg_truncate(const char *path, off_t length)
Definition: fd.c:642
#define FILE_POSSIBLY_DELETED(err)
Definition: fd.h:77
int File
Definition: fd.h:54
int i
Definition: isn.c:73
Assert(fmt[strlen(fmt) - 1] !='\n')
void pfree(void *pointer)
Definition: mcxt.c:1175
MemoryContext TopMemoryContext
Definition: mcxt.c:48
void * palloc0(Size size)
Definition: mcxt.c:1099
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:1188
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:863
void * palloc(Size size)
Definition: mcxt.c:1068
#define EXTENSION_CREATE_RECOVERY
Definition: md.c:110
static BlockNumber _mdnblocks(SMgrRelation reln, ForkNumber forknum, MdfdVec *seg)
Definition: md.c:1325
bool mdfiletagmatches(const FileTag *ftag, const FileTag *candidate)
Definition: md.c:1412
static MdfdVec * _mdfd_openseg(SMgrRelation reln, ForkNumber forkno, BlockNumber segno, int oflags)
Definition: md.c:1150
#define EXTENSION_DONT_OPEN
Definition: md.c:120
bool mdexists(SMgrRelation reln, ForkNumber forkNum)
Definition: md.c:163
BlockNumber mdnblocks(SMgrRelation reln, ForkNumber forknum)
Definition: md.c:770
int mdunlinkfiletag(const FileTag *ftag, char *path)
Definition: md.c:1393
static void register_unlink_segment(RelFileNodeBackend rnode, ForkNumber forknum, BlockNumber segno)
Definition: md.c:1008
static MemoryContext MdCxt
Definition: md.c:88
void mdcreate(SMgrRelation reln, ForkNumber forkNum, bool isRedo)
Definition: md.c:182
void DropRelationFiles(RelFileNode *delrels, int ndelrels, bool isRedo)
Definition: md.c:1057
void mdextend(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum, char *buffer, bool skipFsync)
Definition: md.c:418
static int do_truncate(const char *path)
Definition: md.c:297
void mdinit(void)
Definition: md.c:150
void mdclose(SMgrRelation reln, ForkNumber forknum)
Definition: md.c:537
void mdunlink(RelFileNodeBackend rnode, ForkNumber forkNum, bool isRedo)
Definition: md.c:281
static void register_dirty_segment(SMgrRelation reln, ForkNumber forknum, MdfdVec *seg)
Definition: md.c:982
int mdsyncfiletag(const FileTag *ftag, char *path)
Definition: md.c:1346
void mdwriteback(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum, BlockNumber nblocks)
Definition: md.c:588
#define INIT_MD_FILETAG(a, xx_rnode, xx_forknum, xx_segno)
Definition: md.c:92
#define EXTENSION_RETURN_NULL
Definition: md.c:106
static char * _mdfd_segpath(SMgrRelation reln, ForkNumber forknum, BlockNumber segno)
Definition: md.c:1127
void mdopen(SMgrRelation reln)
Definition: md.c:526
#define EXTENSION_CREATE
Definition: md.c:108
void mdread(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum, char *buffer)
Definition: md.c:640
bool mdprefetch(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum)
Definition: md.c:560
#define EXTENSION_DONT_CHECK_SIZE
Definition: md.c:118
#define EXTENSION_FAIL
Definition: md.c:104
static MdfdVec * mdopenfork(SMgrRelation reln, ForkNumber forknum, int behavior)
Definition: md.c:483
static MdfdVec * _mdfd_getseg(SMgrRelation reln, ForkNumber forkno, BlockNumber blkno, bool skipFsync, int behavior)
Definition: md.c:1195
void mdwrite(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum, char *buffer, bool skipFsync)
Definition: md.c:705
static void _fdvec_resize(SMgrRelation reln, ForkNumber forknum, int nseg)
Definition: md.c:1089
void ForgetDatabaseSyncRequests(Oid dbid)
Definition: md.c:1039
void mdtruncate(SMgrRelation reln, ForkNumber forknum, BlockNumber nblocks)
Definition: md.c:827
void mdimmedsync(SMgrRelation reln, ForkNumber forknum)
Definition: md.c:929
static void mdunlinkfork(RelFileNodeBackend rnode, ForkNumber forkNum, bool isRedo)
Definition: md.c:318
struct _MdfdVec MdfdVec
static void register_forget_request(RelFileNodeBackend rnode, ForkNumber forknum, BlockNumber segno)
Definition: md.c:1025
#define AllocSetContextCreate
Definition: memutils.h:173
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:197
#define ERRCODE_DATA_CORRUPTED
Definition: pg_basebackup.c:43
#define MAXPGPATH
const void size_t len
#define sprintf
Definition: port.h:227
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
unsigned int Oid
Definition: postgres_ext.h:31
static int fd(const char *x, int i)
Definition: preproc-init.c:105
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
#define RelFileNodeBackendIsTemp(rnode)
Definition: relfilenode.h:78
ForkNumber
Definition: relpath.h:41
@ MAIN_FORKNUM
Definition: relpath.h:43
@ InvalidForkNumber
Definition: relpath.h:42
#define MAX_FORKNUM
Definition: relpath.h:55
#define relpathperm(rnode, forknum)
Definition: relpath.h:83
#define relpath(rnode, forknum)
Definition: relpath.h:87
void smgrclose(SMgrRelation reln)
Definition: smgr.c:256
SMgrRelation smgropen(RelFileNode rnode, BackendId backend)
Definition: smgr.c:146
void smgrdounlinkall(SMgrRelation *rels, int nrels, bool isRedo)
Definition: smgr.c:420
#define SmgrIsTemp(smgr)
Definition: smgr.h:77
Definition: sync.h:51
int16 forknum
Definition: sync.h:53
uint32 segno
Definition: sync.h:55
RelFileNode rnode
Definition: sync.h:54
BackendId backend
Definition: relfilenode.h:75
RelFileNode node
Definition: relfilenode.h:74
int md_num_open_segs[MAX_FORKNUM+1]
Definition: smgr.h:68
RelFileNodeBackend smgr_rnode
Definition: smgr.h:42
struct _MdfdVec * md_seg_fds[MAX_FORKNUM+1]
Definition: smgr.h:69
Definition: md.c:83
File mdfd_vfd
Definition: md.c:84
BlockNumber mdfd_segno
Definition: md.c:85
bool RegisterSyncRequest(const FileTag *ftag, SyncRequestType type, bool retryOnError)
Definition: sync.c:587
@ SYNC_FILTER_REQUEST
Definition: sync.h:28
@ SYNC_FORGET_REQUEST
Definition: sync.h:27
@ SYNC_UNLINK_REQUEST
Definition: sync.h:26
@ SYNC_REQUEST
Definition: sync.h:25
@ WAIT_EVENT_DATA_FILE_IMMEDIATE_SYNC
Definition: wait_event.h:175
@ WAIT_EVENT_DATA_FILE_READ
Definition: wait_event.h:177
@ WAIT_EVENT_DATA_FILE_WRITE
Definition: wait_event.h:180
@ WAIT_EVENT_DATA_FILE_FLUSH
Definition: wait_event.h:174
@ WAIT_EVENT_DATA_FILE_EXTEND
Definition: wait_event.h:173
@ WAIT_EVENT_DATA_FILE_TRUNCATE
Definition: wait_event.h:179
@ WAIT_EVENT_DATA_FILE_PREFETCH
Definition: wait_event.h:176
@ WAIT_EVENT_DATA_FILE_SYNC
Definition: wait_event.h:178
void XLogDropRelation(RelFileNode rnode, ForkNumber forknum)
Definition: xlogutils.c:655
bool InRecovery
Definition: xlogutils.c:53