PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
fd.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * fd.c
4  * Virtual file descriptor code.
5  *
6  * Portions Copyright (c) 1996-2017, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  * IDENTIFICATION
10  * src/backend/storage/file/fd.c
11  *
12  * NOTES:
13  *
14  * This code manages a cache of 'virtual' file descriptors (VFDs).
15  * The server opens many file descriptors for a variety of reasons,
16  * including base tables, scratch files (e.g., sort and hash spool
17  * files), and random calls to C library routines like system(3); it
18  * is quite easy to exceed system limits on the number of open files a
19  * single process can have. (This is around 256 on many modern
20  * operating systems, but can be as low as 32 on others.)
21  *
22  * VFDs are managed as an LRU pool, with actual OS file descriptors
23  * being opened and closed as needed. Obviously, if a routine is
24  * opened using these interfaces, all subsequent operations must also
25  * be through these interfaces (the File type is not a real file
26  * descriptor).
27  *
28  * For this scheme to work, most (if not all) routines throughout the
29  * server should use these interfaces instead of calling the C library
30  * routines (e.g., open(2) and fopen(3)) themselves. Otherwise, we
31  * may find ourselves short of real file descriptors anyway.
32  *
33  * INTERFACE ROUTINES
34  *
35  * PathNameOpenFile and OpenTemporaryFile are used to open virtual files.
36  * A File opened with OpenTemporaryFile is automatically deleted when the
37  * File is closed, either explicitly or implicitly at end of transaction or
38  * process exit. PathNameOpenFile is intended for files that are held open
39  * for a long time, like relation files. It is the caller's responsibility
40  * to close them, there is no automatic mechanism in fd.c for that.
41  *
42  * AllocateFile, AllocateDir, OpenPipeStream and OpenTransientFile are
43  * wrappers around fopen(3), opendir(3), popen(3) and open(2), respectively.
44  * They behave like the corresponding native functions, except that the handle
45  * is registered with the current subtransaction, and will be automatically
46  * closed at abort. These are intended mainly for short operations like
47  * reading a configuration file; there is a limit on the number of files that
48  * can be opened using these functions at any one time.
49  *
50  * Finally, BasicOpenFile is just a thin wrapper around open() that can
51  * release file descriptors in use by the virtual file descriptors if
52  * necessary. There is no automatic cleanup of file descriptors returned by
53  * BasicOpenFile, it is solely the caller's responsibility to close the file
54  * descriptor by calling close(2).
55  *
56  *-------------------------------------------------------------------------
57  */
58 
59 #include "postgres.h"
60 
61 #include <sys/file.h>
62 #include <sys/param.h>
63 #include <sys/stat.h>
64 #ifndef WIN32
65 #include <sys/mman.h>
66 #endif
67 #include <limits.h>
68 #include <unistd.h>
69 #include <fcntl.h>
70 #ifdef HAVE_SYS_RESOURCE_H
71 #include <sys/resource.h> /* for getrlimit */
72 #endif
73 
74 #include "miscadmin.h"
75 #include "access/xact.h"
76 #include "access/xlog.h"
77 #include "catalog/catalog.h"
78 #include "catalog/pg_tablespace.h"
79 #include "pgstat.h"
80 #include "portability/mem.h"
81 #include "storage/fd.h"
82 #include "storage/ipc.h"
83 #include "utils/guc.h"
84 #include "utils/resowner_private.h"
85 
86 
87 /* Define PG_FLUSH_DATA_WORKS if we have an implementation for pg_flush_data */
88 #if defined(HAVE_SYNC_FILE_RANGE)
89 #define PG_FLUSH_DATA_WORKS 1
90 #elif !defined(WIN32) && defined(MS_ASYNC)
91 #define PG_FLUSH_DATA_WORKS 1
92 #elif defined(USE_POSIX_FADVISE) && defined(POSIX_FADV_DONTNEED)
93 #define PG_FLUSH_DATA_WORKS 1
94 #endif
95 
96 /*
97  * We must leave some file descriptors free for system(), the dynamic loader,
98  * and other code that tries to open files without consulting fd.c. This
99  * is the number left free. (While we can be pretty sure we won't get
100  * EMFILE, there's never any guarantee that we won't get ENFILE due to
101  * other processes chewing up FDs. So it's a bad idea to try to open files
102  * without consulting fd.c. Nonetheless we cannot control all code.)
103  *
104  * Because this is just a fixed setting, we are effectively assuming that
105  * no such code will leave FDs open over the long term; otherwise the slop
106  * is likely to be insufficient. Note in particular that we expect that
107  * loading a shared library does not result in any permanent increase in
108  * the number of open files. (This appears to be true on most if not
109  * all platforms as of Feb 2004.)
110  */
111 #define NUM_RESERVED_FDS 10
112 
113 /*
114  * If we have fewer than this many usable FDs after allowing for the reserved
115  * ones, choke.
116  */
117 #define FD_MINFREE 10
118 
119 
120 /*
121  * A number of platforms allow individual processes to open many more files
122  * than they can really support when *many* processes do the same thing.
123  * This GUC parameter lets the DBA limit max_safe_fds to something less than
124  * what the postmaster's initial probe suggests will work.
125  */
127 
128 /*
129  * Maximum number of file descriptors to open for either VFD entries or
130  * AllocateFile/AllocateDir/OpenTransientFile operations. This is initialized
131  * to a conservative value, and remains that way indefinitely in bootstrap or
132  * standalone-backend cases. In normal postmaster operation, the postmaster
133  * calls set_max_safe_fds() late in initialization to update the value, and
134  * that value is then inherited by forked subprocesses.
135  *
136  * Note: the value of max_files_per_process is taken into account while
137  * setting this variable, and so need not be tested separately.
138  */
139 int max_safe_fds = 32; /* default if not changed */
140 
141 
142 /* Debugging.... */
143 
144 #ifdef FDDEBUG
145 #define DO_DB(A) \
146  do { \
147  int _do_db_save_errno = errno; \
148  A; \
149  errno = _do_db_save_errno; \
150  } while (0)
151 #else
152 #define DO_DB(A) \
153  ((void) 0)
154 #endif
155 
156 #define VFD_CLOSED (-1)
157 
158 #define FileIsValid(file) \
159  ((file) > 0 && (file) < (int) SizeVfdCache && VfdCache[file].fileName != NULL)
160 
161 #define FileIsNotOpen(file) (VfdCache[file].fd == VFD_CLOSED)
162 
163 /*
164  * Note: a VFD's seekPos is normally always valid, but if for some reason
165  * an lseek() fails, it might become set to FileUnknownPos. We can struggle
166  * along without knowing the seek position in many cases, but in some places
167  * we have to fail if we don't have it.
168  */
169 #define FileUnknownPos ((off_t) -1)
170 #define FilePosIsUnknown(pos) ((pos) < 0)
171 
172 /* these are the assigned bits in fdstate below: */
173 #define FD_TEMPORARY (1 << 0) /* T = delete when closed */
174 #define FD_XACT_TEMPORARY (1 << 1) /* T = delete at eoXact */
175 
176 typedef struct vfd
177 {
178  int fd; /* current FD, or VFD_CLOSED if none */
179  unsigned short fdstate; /* bitflags for VFD's state */
180  ResourceOwner resowner; /* owner, for automatic cleanup */
181  File nextFree; /* link to next free VFD, if in freelist */
182  File lruMoreRecently; /* doubly linked recency-of-use list */
184  off_t seekPos; /* current logical file position, or -1 */
185  off_t fileSize; /* current size of file (0 if not temporary) */
186  char *fileName; /* name of file, or NULL for unused VFD */
187  /* NB: fileName is malloc'd, and must be free'd when closing the VFD */
188  int fileFlags; /* open(2) flags for (re)opening the file */
189  int fileMode; /* mode to pass to open(2) */
190 } Vfd;
191 
192 /*
193  * Virtual File Descriptor array pointer and size. This grows as
194  * needed. 'File' values are indexes into this array.
195  * Note that VfdCache[0] is not a usable VFD, just a list header.
196  */
197 static Vfd *VfdCache;
198 static Size SizeVfdCache = 0;
199 
200 /*
201  * Number of file descriptors known to be in use by VFD entries.
202  */
203 static int nfile = 0;
204 
205 /*
206  * Flag to tell whether it's worth scanning VfdCache looking for temp files
207  * to close
208  */
209 static bool have_xact_temporary_files = false;
210 
211 /*
212  * Tracks the total size of all temporary files. Note: when temp_file_limit
213  * is being enforced, this cannot overflow since the limit cannot be more
214  * than INT_MAX kilobytes. When not enforcing, it could theoretically
215  * overflow, but we don't care.
216  */
217 static uint64 temporary_files_size = 0;
218 
219 /*
220  * List of OS handles opened with AllocateFile, AllocateDir and
221  * OpenTransientFile.
222  */
223 typedef enum
224 {
230 
231 typedef struct
232 {
235  union
236  {
237  FILE *file;
239  int fd;
240  } desc;
241 } AllocateDesc;
242 
243 static int numAllocatedDescs = 0;
244 static int maxAllocatedDescs = 0;
246 
247 /*
248  * Number of temporary files opened during the current session;
249  * this is used in generation of tempfile names.
250  */
251 static long tempFileCounter = 0;
252 
253 /*
254  * Array of OIDs of temp tablespaces. When numTempTableSpaces is -1,
255  * this has not been set in the current transaction.
256  */
258 static int numTempTableSpaces = -1;
259 static int nextTempTableSpace = 0;
260 
261 
262 /*--------------------
263  *
264  * Private Routines
265  *
266  * Delete - delete a file from the Lru ring
267  * LruDelete - remove a file from the Lru ring and close its FD
268  * Insert - put a file at the front of the Lru ring
269  * LruInsert - put a file at the front of the Lru ring and open it
270  * ReleaseLruFile - Release an fd by closing the last entry in the Lru ring
271  * ReleaseLruFiles - Release fd(s) until we're under the max_safe_fds limit
272  * AllocateVfd - grab a free (or new) file record (from VfdArray)
273  * FreeVfd - free a file record
274  *
275  * The Least Recently Used ring is a doubly linked list that begins and
276  * ends on element zero. Element zero is special -- it doesn't represent
277  * a file and its "fd" field always == VFD_CLOSED. Element zero is just an
278  * anchor that shows us the beginning/end of the ring.
279  * Only VFD elements that are currently really open (have an FD assigned) are
280  * in the Lru ring. Elements that are "virtually" open can be recognized
281  * by having a non-null fileName field.
282  *
283  * example:
284  *
285  * /--less----\ /---------\
286  * v \ v \
287  * #0 --more---> LeastRecentlyUsed --more-\ \
288  * ^\ | |
289  * \\less--> MostRecentlyUsedFile <---/ |
290  * \more---/ \--less--/
291  *
292  *--------------------
293  */
294 static void Delete(File file);
295 static void LruDelete(File file);
296 static void Insert(File file);
297 static int LruInsert(File file);
298 static bool ReleaseLruFile(void);
299 static void ReleaseLruFiles(void);
300 static File AllocateVfd(void);
301 static void FreeVfd(File file);
302 
303 static int FileAccess(File file);
304 static File OpenTemporaryFileInTablespace(Oid tblspcOid, bool rejectError);
305 static bool reserveAllocatedDesc(void);
306 static int FreeDesc(AllocateDesc *desc);
307 static struct dirent *ReadDirExtended(DIR *dir, const char *dirname, int elevel);
308 
309 static void AtProcExit_Files(int code, Datum arg);
310 static void CleanupTempFiles(bool isProcExit);
311 static void RemovePgTempFilesInDir(const char *tmpdirname);
312 static void RemovePgTempRelationFiles(const char *tsdirname);
313 static void RemovePgTempRelationFilesInDbspace(const char *dbspacedirname);
314 static bool looks_like_temp_rel_name(const char *name);
315 
316 static void walkdir(const char *path,
317  void (*action) (const char *fname, bool isdir, int elevel),
318  bool process_symlinks,
319  int elevel);
320 #ifdef PG_FLUSH_DATA_WORKS
321 static void pre_sync_fname(const char *fname, bool isdir, int elevel);
322 #endif
323 static void datadir_fsync_fname(const char *fname, bool isdir, int elevel);
324 
325 static int fsync_fname_ext(const char *fname, bool isdir, bool ignore_perm, int elevel);
326 static int fsync_parent_path(const char *fname, int elevel);
327 
328 
329 /*
330  * pg_fsync --- do fsync with or without writethrough
331  */
332 int
334 {
335  /* #if is to skip the sync_method test if there's no need for it */
336 #if defined(HAVE_FSYNC_WRITETHROUGH) && !defined(FSYNC_WRITETHROUGH_IS_FSYNC)
338  return pg_fsync_writethrough(fd);
339  else
340 #endif
341  return pg_fsync_no_writethrough(fd);
342 }
343 
344 
345 /*
346  * pg_fsync_no_writethrough --- same as fsync except does nothing if
347  * enableFsync is off
348  */
349 int
351 {
352  if (enableFsync)
353  return fsync(fd);
354  else
355  return 0;
356 }
357 
358 /*
359  * pg_fsync_writethrough
360  */
361 int
363 {
364  if (enableFsync)
365  {
366 #ifdef WIN32
367  return _commit(fd);
368 #elif defined(F_FULLFSYNC)
369  return (fcntl(fd, F_FULLFSYNC, 0) == -1) ? -1 : 0;
370 #else
371  errno = ENOSYS;
372  return -1;
373 #endif
374  }
375  else
376  return 0;
377 }
378 
379 /*
380  * pg_fdatasync --- same as fdatasync except does nothing if enableFsync is off
381  *
382  * Not all platforms have fdatasync; treat as fsync if not available.
383  */
384 int
386 {
387  if (enableFsync)
388  {
389 #ifdef HAVE_FDATASYNC
390  return fdatasync(fd);
391 #else
392  return fsync(fd);
393 #endif
394  }
395  else
396  return 0;
397 }
398 
399 /*
400  * pg_flush_data --- advise OS that the described dirty data should be flushed
401  *
402  * offset of 0 with nbytes 0 means that the entire file should be flushed;
403  * in this case, this function may have side-effects on the file's
404  * seek position!
405  */
406 void
407 pg_flush_data(int fd, off_t offset, off_t nbytes)
408 {
409  /*
410  * Right now file flushing is primarily used to avoid making later
411  * fsync()/fdatasync() calls have less impact. Thus don't trigger flushes
412  * if fsyncs are disabled - that's a decision we might want to make
413  * configurable at some point.
414  */
415  if (!enableFsync)
416  return;
417 
418  /*
419  * We compile all alternatives that are supported on the current platform,
420  * to find portability problems more easily.
421  */
422 #if defined(HAVE_SYNC_FILE_RANGE)
423  {
424  int rc;
425 
426  /*
427  * sync_file_range(SYNC_FILE_RANGE_WRITE), currently linux specific,
428  * tells the OS that writeback for the specified blocks should be
429  * started, but that we don't want to wait for completion. Note that
430  * this call might block if too much dirty data exists in the range.
431  * This is the preferable method on OSs supporting it, as it works
432  * reliably when available (contrast to msync()) and doesn't flush out
433  * clean data (like FADV_DONTNEED).
434  */
435  rc = sync_file_range(fd, offset, nbytes,
436  SYNC_FILE_RANGE_WRITE);
437 
438  /* don't error out, this is just a performance optimization */
439  if (rc != 0)
440  {
443  errmsg("could not flush dirty data: %m")));
444  }
445 
446  return;
447  }
448 #endif
449 #if !defined(WIN32) && defined(MS_ASYNC)
450  {
451  void *p;
452  static int pagesize = 0;
453 
454  /*
455  * On several OSs msync(MS_ASYNC) on a mmap'ed file triggers
456  * writeback. On linux it only does so if MS_SYNC is specified, but
457  * then it does the writeback synchronously. Luckily all common linux
458  * systems have sync_file_range(). This is preferable over
459  * FADV_DONTNEED because it doesn't flush out clean data.
460  *
461  * We map the file (mmap()), tell the kernel to sync back the contents
462  * (msync()), and then remove the mapping again (munmap()).
463  */
464 
465  /* mmap() needs actual length if we want to map whole file */
466  if (offset == 0 && nbytes == 0)
467  {
468  nbytes = lseek(fd, 0, SEEK_END);
469  if (nbytes < 0)
470  {
473  errmsg("could not determine dirty data size: %m")));
474  return;
475  }
476  }
477 
478  /*
479  * Some platforms reject partial-page mmap() attempts. To deal with
480  * that, just truncate the request to a page boundary. If any extra
481  * bytes don't get flushed, well, it's only a hint anyway.
482  */
483 
484  /* fetch pagesize only once */
485  if (pagesize == 0)
486  pagesize = sysconf(_SC_PAGESIZE);
487 
488  /* align length to pagesize, dropping any fractional page */
489  if (pagesize > 0)
490  nbytes = (nbytes / pagesize) * pagesize;
491 
492  /* fractional-page request is a no-op */
493  if (nbytes <= 0)
494  return;
495 
496  /*
497  * mmap could well fail, particularly on 32-bit platforms where there
498  * may simply not be enough address space. If so, silently fall
499  * through to the next implementation.
500  */
501  if (nbytes <= (off_t) SSIZE_MAX)
502  p = mmap(NULL, nbytes, PROT_READ, MAP_SHARED, fd, offset);
503  else
504  p = MAP_FAILED;
505 
506  if (p != MAP_FAILED)
507  {
508  int rc;
509 
510  rc = msync(p, (size_t) nbytes, MS_ASYNC);
511  if (rc != 0)
512  {
515  errmsg("could not flush dirty data: %m")));
516  /* NB: need to fall through to munmap()! */
517  }
518 
519  rc = munmap(p, (size_t) nbytes);
520  if (rc != 0)
521  {
522  /* FATAL error because mapping would remain */
523  ereport(FATAL,
525  errmsg("could not munmap() while flushing data: %m")));
526  }
527 
528  return;
529  }
530  }
531 #endif
532 #if defined(USE_POSIX_FADVISE) && defined(POSIX_FADV_DONTNEED)
533  {
534  int rc;
535 
536  /*
537  * Signal the kernel that the passed in range should not be cached
538  * anymore. This has the, desired, side effect of writing out dirty
539  * data, and the, undesired, side effect of likely discarding useful
540  * clean cached blocks. For the latter reason this is the least
541  * preferable method.
542  */
543 
544  rc = posix_fadvise(fd, offset, nbytes, POSIX_FADV_DONTNEED);
545 
546  if (rc != 0)
547  {
548  /* don't error out, this is just a performance optimization */
551  errmsg("could not flush dirty data: %m")));
552  }
553 
554  return;
555  }
556 #endif
557 }
558 
559 
560 /*
561  * fsync_fname -- fsync a file or directory, handling errors properly
562  *
563  * Try to fsync a file or directory. When doing the latter, ignore errors that
564  * indicate the OS just doesn't allow/require fsyncing directories.
565  */
566 void
567 fsync_fname(const char *fname, bool isdir)
568 {
569  fsync_fname_ext(fname, isdir, false, ERROR);
570 }
571 
572 /*
573  * durable_rename -- rename(2) wrapper, issuing fsyncs required for durability
574  *
575  * This routine ensures that, after returning, the effect of renaming file
576  * persists in case of a crash. A crash while this routine is running will
577  * leave you with either the pre-existing or the moved file in place of the
578  * new file; no mixed state or truncated files are possible.
579  *
580  * It does so by using fsync on the old filename and the possibly existing
581  * target filename before the rename, and the target file and directory after.
582  *
583  * Note that rename() cannot be used across arbitrary directories, as they
584  * might not be on the same filesystem. Therefore this routine does not
585  * support renaming across directories.
586  *
587  * Log errors with the caller specified severity.
588  *
589  * Returns 0 if the operation succeeded, -1 otherwise. Note that errno is not
590  * valid upon return.
591  */
592 int
593 durable_rename(const char *oldfile, const char *newfile, int elevel)
594 {
595  int fd;
596 
597  /*
598  * First fsync the old and target path (if it exists), to ensure that they
599  * are properly persistent on disk. Syncing the target file is not
600  * strictly necessary, but it makes it easier to reason about crashes;
601  * because it's then guaranteed that either source or target file exists
602  * after a crash.
603  */
604  if (fsync_fname_ext(oldfile, false, false, elevel) != 0)
605  return -1;
606 
607  fd = OpenTransientFile((char *) newfile, PG_BINARY | O_RDWR, 0);
608  if (fd < 0)
609  {
610  if (errno != ENOENT)
611  {
612  ereport(elevel,
614  errmsg("could not open file \"%s\": %m", newfile)));
615  return -1;
616  }
617  }
618  else
619  {
620  if (pg_fsync(fd) != 0)
621  {
622  int save_errno;
623 
624  /* close file upon error, might not be in transaction context */
625  save_errno = errno;
626  CloseTransientFile(fd);
627  errno = save_errno;
628 
629  ereport(elevel,
631  errmsg("could not fsync file \"%s\": %m", newfile)));
632  return -1;
633  }
634  CloseTransientFile(fd);
635  }
636 
637  /* Time to do the real deal... */
638  if (rename(oldfile, newfile) < 0)
639  {
640  ereport(elevel,
642  errmsg("could not rename file \"%s\" to \"%s\": %m",
643  oldfile, newfile)));
644  return -1;
645  }
646 
647  /*
648  * To guarantee renaming the file is persistent, fsync the file with its
649  * new name, and its containing directory.
650  */
651  if (fsync_fname_ext(newfile, false, false, elevel) != 0)
652  return -1;
653 
654  if (fsync_parent_path(newfile, elevel) != 0)
655  return -1;
656 
657  return 0;
658 }
659 
660 /*
661  * durable_link_or_rename -- rename a file in a durable manner.
662  *
663  * Similar to durable_rename(), except that this routine tries (but does not
664  * guarantee) not to overwrite the target file.
665  *
666  * Note that a crash in an unfortunate moment can leave you with two links to
667  * the target file.
668  *
669  * Log errors with the caller specified severity.
670  *
671  * Returns 0 if the operation succeeded, -1 otherwise. Note that errno is not
672  * valid upon return.
673  */
674 int
675 durable_link_or_rename(const char *oldfile, const char *newfile, int elevel)
676 {
677  /*
678  * Ensure that, if we crash directly after the rename/link, a file with
679  * valid contents is moved into place.
680  */
681  if (fsync_fname_ext(oldfile, false, false, elevel) != 0)
682  return -1;
683 
684 #if HAVE_WORKING_LINK
685  if (link(oldfile, newfile) < 0)
686  {
687  ereport(elevel,
689  errmsg("could not link file \"%s\" to \"%s\": %m",
690  oldfile, newfile)));
691  return -1;
692  }
693  unlink(oldfile);
694 #else
695  /* XXX: Add racy file existence check? */
696  if (rename(oldfile, newfile) < 0)
697  {
698  ereport(elevel,
700  errmsg("could not rename file \"%s\" to \"%s\": %m",
701  oldfile, newfile)));
702  return -1;
703  }
704 #endif
705 
706  /*
707  * Make change persistent in case of an OS crash, both the new entry and
708  * its parent directory need to be flushed.
709  */
710  if (fsync_fname_ext(newfile, false, false, elevel) != 0)
711  return -1;
712 
713  /* Same for parent directory */
714  if (fsync_parent_path(newfile, elevel) != 0)
715  return -1;
716 
717  return 0;
718 }
719 
720 /*
721  * InitFileAccess --- initialize this module during backend startup
722  *
723  * This is called during either normal or standalone backend start.
724  * It is *not* called in the postmaster.
725  */
726 void
728 {
729  Assert(SizeVfdCache == 0); /* call me only once */
730 
731  /* initialize cache header entry */
732  VfdCache = (Vfd *) malloc(sizeof(Vfd));
733  if (VfdCache == NULL)
734  ereport(FATAL,
735  (errcode(ERRCODE_OUT_OF_MEMORY),
736  errmsg("out of memory")));
737 
738  MemSet((char *) &(VfdCache[0]), 0, sizeof(Vfd));
739  VfdCache->fd = VFD_CLOSED;
740 
741  SizeVfdCache = 1;
742 
743  /* register proc-exit hook to ensure temp files are dropped at exit */
745 }
746 
747 /*
748  * count_usable_fds --- count how many FDs the system will let us open,
749  * and estimate how many are already open.
750  *
751  * We stop counting if usable_fds reaches max_to_probe. Note: a small
752  * value of max_to_probe might result in an underestimate of already_open;
753  * we must fill in any "gaps" in the set of used FDs before the calculation
754  * of already_open will give the right answer. In practice, max_to_probe
755  * of a couple of dozen should be enough to ensure good results.
756  *
757  * We assume stdin (FD 0) is available for dup'ing
758  */
759 static void
760 count_usable_fds(int max_to_probe, int *usable_fds, int *already_open)
761 {
762  int *fd;
763  int size;
764  int used = 0;
765  int highestfd = 0;
766  int j;
767 
768 #ifdef HAVE_GETRLIMIT
769  struct rlimit rlim;
770  int getrlimit_status;
771 #endif
772 
773  size = 1024;
774  fd = (int *) palloc(size * sizeof(int));
775 
776 #ifdef HAVE_GETRLIMIT
777 #ifdef RLIMIT_NOFILE /* most platforms use RLIMIT_NOFILE */
778  getrlimit_status = getrlimit(RLIMIT_NOFILE, &rlim);
779 #else /* but BSD doesn't ... */
780  getrlimit_status = getrlimit(RLIMIT_OFILE, &rlim);
781 #endif /* RLIMIT_NOFILE */
782  if (getrlimit_status != 0)
783  ereport(WARNING, (errmsg("getrlimit failed: %m")));
784 #endif /* HAVE_GETRLIMIT */
785 
786  /* dup until failure or probe limit reached */
787  for (;;)
788  {
789  int thisfd;
790 
791 #ifdef HAVE_GETRLIMIT
792 
793  /*
794  * don't go beyond RLIMIT_NOFILE; causes irritating kernel logs on
795  * some platforms
796  */
797  if (getrlimit_status == 0 && highestfd >= rlim.rlim_cur - 1)
798  break;
799 #endif
800 
801  thisfd = dup(0);
802  if (thisfd < 0)
803  {
804  /* Expect EMFILE or ENFILE, else it's fishy */
805  if (errno != EMFILE && errno != ENFILE)
806  elog(WARNING, "dup(0) failed after %d successes: %m", used);
807  break;
808  }
809 
810  if (used >= size)
811  {
812  size *= 2;
813  fd = (int *) repalloc(fd, size * sizeof(int));
814  }
815  fd[used++] = thisfd;
816 
817  if (highestfd < thisfd)
818  highestfd = thisfd;
819 
820  if (used >= max_to_probe)
821  break;
822  }
823 
824  /* release the files we opened */
825  for (j = 0; j < used; j++)
826  close(fd[j]);
827 
828  pfree(fd);
829 
830  /*
831  * Return results. usable_fds is just the number of successful dups. We
832  * assume that the system limit is highestfd+1 (remember 0 is a legal FD
833  * number) and so already_open is highestfd+1 - usable_fds.
834  */
835  *usable_fds = used;
836  *already_open = highestfd + 1 - used;
837 }
838 
839 /*
840  * set_max_safe_fds
841  * Determine number of filedescriptors that fd.c is allowed to use
842  */
843 void
845 {
846  int usable_fds;
847  int already_open;
848 
849  /*----------
850  * We want to set max_safe_fds to
851  * MIN(usable_fds, max_files_per_process - already_open)
852  * less the slop factor for files that are opened without consulting
853  * fd.c. This ensures that we won't exceed either max_files_per_process
854  * or the experimentally-determined EMFILE limit.
855  *----------
856  */
858  &usable_fds, &already_open);
859 
860  max_safe_fds = Min(usable_fds, max_files_per_process - already_open);
861 
862  /*
863  * Take off the FDs reserved for system() etc.
864  */
866 
867  /*
868  * Make sure we still have enough to get by.
869  */
870  if (max_safe_fds < FD_MINFREE)
871  ereport(FATAL,
872  (errcode(ERRCODE_INSUFFICIENT_RESOURCES),
873  errmsg("insufficient file descriptors available to start server process"),
874  errdetail("System allows %d, we need at least %d.",
877 
878  elog(DEBUG2, "max_safe_fds = %d, usable_fds = %d, already_open = %d",
879  max_safe_fds, usable_fds, already_open);
880 }
881 
882 /*
883  * BasicOpenFile --- same as open(2) except can free other FDs if needed
884  *
885  * This is exported for use by places that really want a plain kernel FD,
886  * but need to be proof against running out of FDs. Once an FD has been
887  * successfully returned, it is the caller's responsibility to ensure that
888  * it will not be leaked on ereport()! Most users should *not* call this
889  * routine directly, but instead use the VFD abstraction level, which
890  * provides protection against descriptor leaks as well as management of
891  * files that need to be open for more than a short period of time.
892  *
893  * Ideally this should be the *only* direct call of open() in the backend.
894  * In practice, the postmaster calls open() directly, and there are some
895  * direct open() calls done early in backend startup. Those are OK since
896  * this module wouldn't have any open files to close at that point anyway.
897  */
898 int
899 BasicOpenFile(FileName fileName, int fileFlags, int fileMode)
900 {
901  int fd;
902 
903 tryAgain:
904  fd = open(fileName, fileFlags, fileMode);
905 
906  if (fd >= 0)
907  return fd; /* success! */
908 
909  if (errno == EMFILE || errno == ENFILE)
910  {
911  int save_errno = errno;
912 
913  ereport(LOG,
914  (errcode(ERRCODE_INSUFFICIENT_RESOURCES),
915  errmsg("out of file descriptors: %m; release and retry")));
916  errno = 0;
917  if (ReleaseLruFile())
918  goto tryAgain;
919  errno = save_errno;
920  }
921 
922  return -1; /* failure */
923 }
924 
925 #if defined(FDDEBUG)
926 
927 static void
928 _dump_lru(void)
929 {
930  int mru = VfdCache[0].lruLessRecently;
931  Vfd *vfdP = &VfdCache[mru];
932  char buf[2048];
933 
934  snprintf(buf, sizeof(buf), "LRU: MOST %d ", mru);
935  while (mru != 0)
936  {
937  mru = vfdP->lruLessRecently;
938  vfdP = &VfdCache[mru];
939  snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%d ", mru);
940  }
941  snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "LEAST");
942  elog(LOG, "%s", buf);
943 }
944 #endif /* FDDEBUG */
945 
946 static void
948 {
949  Vfd *vfdP;
950 
951  Assert(file != 0);
952 
953  DO_DB(elog(LOG, "Delete %d (%s)",
954  file, VfdCache[file].fileName));
955  DO_DB(_dump_lru());
956 
957  vfdP = &VfdCache[file];
958 
959  VfdCache[vfdP->lruLessRecently].lruMoreRecently = vfdP->lruMoreRecently;
960  VfdCache[vfdP->lruMoreRecently].lruLessRecently = vfdP->lruLessRecently;
961 
962  DO_DB(_dump_lru());
963 }
964 
965 static void
967 {
968  Vfd *vfdP;
969 
970  Assert(file != 0);
971 
972  DO_DB(elog(LOG, "LruDelete %d (%s)",
973  file, VfdCache[file].fileName));
974 
975  vfdP = &VfdCache[file];
976 
977  /*
978  * Normally we should know the seek position, but if for some reason we
979  * have lost track of it, try again to get it. If we still can't get it,
980  * we have a problem: we will be unable to restore the file seek position
981  * when and if the file is re-opened. But we can't really throw an error
982  * and refuse to close the file, or activities such as transaction cleanup
983  * will be broken.
984  */
985  if (FilePosIsUnknown(vfdP->seekPos))
986  {
987  vfdP->seekPos = lseek(vfdP->fd, (off_t) 0, SEEK_CUR);
988  if (FilePosIsUnknown(vfdP->seekPos))
989  elog(LOG, "could not seek file \"%s\" before closing: %m",
990  vfdP->fileName);
991  }
992 
993  /*
994  * Close the file. We aren't expecting this to fail; if it does, better
995  * to leak the FD than to mess up our internal state.
996  */
997  if (close(vfdP->fd))
998  elog(LOG, "could not close file \"%s\": %m", vfdP->fileName);
999  vfdP->fd = VFD_CLOSED;
1000  --nfile;
1001 
1002  /* delete the vfd record from the LRU ring */
1003  Delete(file);
1004 }
1005 
1006 static void
1008 {
1009  Vfd *vfdP;
1010 
1011  Assert(file != 0);
1012 
1013  DO_DB(elog(LOG, "Insert %d (%s)",
1014  file, VfdCache[file].fileName));
1015  DO_DB(_dump_lru());
1016 
1017  vfdP = &VfdCache[file];
1018 
1019  vfdP->lruMoreRecently = 0;
1020  vfdP->lruLessRecently = VfdCache[0].lruLessRecently;
1021  VfdCache[0].lruLessRecently = file;
1022  VfdCache[vfdP->lruLessRecently].lruMoreRecently = file;
1023 
1024  DO_DB(_dump_lru());
1025 }
1026 
1027 /* returns 0 on success, -1 on re-open failure (with errno set) */
1028 static int
1030 {
1031  Vfd *vfdP;
1032 
1033  Assert(file != 0);
1034 
1035  DO_DB(elog(LOG, "LruInsert %d (%s)",
1036  file, VfdCache[file].fileName));
1037 
1038  vfdP = &VfdCache[file];
1039 
1040  if (FileIsNotOpen(file))
1041  {
1042  /* Close excess kernel FDs. */
1043  ReleaseLruFiles();
1044 
1045  /*
1046  * The open could still fail for lack of file descriptors, eg due to
1047  * overall system file table being full. So, be prepared to release
1048  * another FD if necessary...
1049  */
1050  vfdP->fd = BasicOpenFile(vfdP->fileName, vfdP->fileFlags,
1051  vfdP->fileMode);
1052  if (vfdP->fd < 0)
1053  {
1054  DO_DB(elog(LOG, "re-open failed: %m"));
1055  return -1;
1056  }
1057  else
1058  {
1059  ++nfile;
1060  }
1061 
1062  /*
1063  * Seek to the right position. We need no special case for seekPos
1064  * equal to FileUnknownPos, as lseek() will certainly reject that
1065  * (thus completing the logic noted in LruDelete() that we will fail
1066  * to re-open a file if we couldn't get its seek position before
1067  * closing).
1068  */
1069  if (vfdP->seekPos != (off_t) 0)
1070  {
1071  if (lseek(vfdP->fd, vfdP->seekPos, SEEK_SET) < 0)
1072  {
1073  /*
1074  * If we fail to restore the seek position, treat it like an
1075  * open() failure.
1076  */
1077  int save_errno = errno;
1078 
1079  elog(LOG, "could not seek file \"%s\" after re-opening: %m",
1080  vfdP->fileName);
1081  (void) close(vfdP->fd);
1082  vfdP->fd = VFD_CLOSED;
1083  --nfile;
1084  errno = save_errno;
1085  return -1;
1086  }
1087  }
1088  }
1089 
1090  /*
1091  * put it at the head of the Lru ring
1092  */
1093 
1094  Insert(file);
1095 
1096  return 0;
1097 }
1098 
1099 /*
1100  * Release one kernel FD by closing the least-recently-used VFD.
1101  */
1102 static bool
1104 {
1105  DO_DB(elog(LOG, "ReleaseLruFile. Opened %d", nfile));
1106 
1107  if (nfile > 0)
1108  {
1109  /*
1110  * There are opened files and so there should be at least one used vfd
1111  * in the ring.
1112  */
1113  Assert(VfdCache[0].lruMoreRecently != 0);
1114  LruDelete(VfdCache[0].lruMoreRecently);
1115  return true; /* freed a file */
1116  }
1117  return false; /* no files available to free */
1118 }
1119 
1120 /*
1121  * Release kernel FDs as needed to get under the max_safe_fds limit.
1122  * After calling this, it's OK to try to open another file.
1123  */
1124 static void
1126 {
1127  while (nfile + numAllocatedDescs >= max_safe_fds)
1128  {
1129  if (!ReleaseLruFile())
1130  break;
1131  }
1132 }
1133 
1134 static File
1136 {
1137  Index i;
1138  File file;
1139 
1140  DO_DB(elog(LOG, "AllocateVfd. Size %zu", SizeVfdCache));
1141 
1142  Assert(SizeVfdCache > 0); /* InitFileAccess not called? */
1143 
1144  if (VfdCache[0].nextFree == 0)
1145  {
1146  /*
1147  * The free list is empty so it is time to increase the size of the
1148  * array. We choose to double it each time this happens. However,
1149  * there's not much point in starting *real* small.
1150  */
1151  Size newCacheSize = SizeVfdCache * 2;
1152  Vfd *newVfdCache;
1153 
1154  if (newCacheSize < 32)
1155  newCacheSize = 32;
1156 
1157  /*
1158  * Be careful not to clobber VfdCache ptr if realloc fails.
1159  */
1160  newVfdCache = (Vfd *) realloc(VfdCache, sizeof(Vfd) * newCacheSize);
1161  if (newVfdCache == NULL)
1162  ereport(ERROR,
1163  (errcode(ERRCODE_OUT_OF_MEMORY),
1164  errmsg("out of memory")));
1165  VfdCache = newVfdCache;
1166 
1167  /*
1168  * Initialize the new entries and link them into the free list.
1169  */
1170  for (i = SizeVfdCache; i < newCacheSize; i++)
1171  {
1172  MemSet((char *) &(VfdCache[i]), 0, sizeof(Vfd));
1173  VfdCache[i].nextFree = i + 1;
1174  VfdCache[i].fd = VFD_CLOSED;
1175  }
1176  VfdCache[newCacheSize - 1].nextFree = 0;
1177  VfdCache[0].nextFree = SizeVfdCache;
1178 
1179  /*
1180  * Record the new size
1181  */
1182  SizeVfdCache = newCacheSize;
1183  }
1184 
1185  file = VfdCache[0].nextFree;
1186 
1187  VfdCache[0].nextFree = VfdCache[file].nextFree;
1188 
1189  return file;
1190 }
1191 
1192 static void
1194 {
1195  Vfd *vfdP = &VfdCache[file];
1196 
1197  DO_DB(elog(LOG, "FreeVfd: %d (%s)",
1198  file, vfdP->fileName ? vfdP->fileName : ""));
1199 
1200  if (vfdP->fileName != NULL)
1201  {
1202  free(vfdP->fileName);
1203  vfdP->fileName = NULL;
1204  }
1205  vfdP->fdstate = 0x0;
1206 
1207  vfdP->nextFree = VfdCache[0].nextFree;
1208  VfdCache[0].nextFree = file;
1209 }
1210 
1211 /* returns 0 on success, -1 on re-open failure (with errno set) */
1212 static int
1214 {
1215  int returnValue;
1216 
1217  DO_DB(elog(LOG, "FileAccess %d (%s)",
1218  file, VfdCache[file].fileName));
1219 
1220  /*
1221  * Is the file open? If not, open it and put it at the head of the LRU
1222  * ring (possibly closing the least recently used file to get an FD).
1223  */
1224 
1225  if (FileIsNotOpen(file))
1226  {
1227  returnValue = LruInsert(file);
1228  if (returnValue != 0)
1229  return returnValue;
1230  }
1231  else if (VfdCache[0].lruLessRecently != file)
1232  {
1233  /*
1234  * We now know that the file is open and that it is not the last one
1235  * accessed, so we need to move it to the head of the Lru ring.
1236  */
1237 
1238  Delete(file);
1239  Insert(file);
1240  }
1241 
1242  return 0;
1243 }
1244 
1245 /*
1246  * Called when we get a shared invalidation message on some relation.
1247  */
1248 #ifdef NOT_USED
1249 void
1250 FileInvalidate(File file)
1251 {
1252  Assert(FileIsValid(file));
1253  if (!FileIsNotOpen(file))
1254  LruDelete(file);
1255 }
1256 #endif
1257 
1258 /*
1259  * open a file in an arbitrary directory
1260  *
1261  * NB: if the passed pathname is relative (which it usually is),
1262  * it will be interpreted relative to the process' working directory
1263  * (which should always be $PGDATA when this code is running).
1264  */
1265 File
1266 PathNameOpenFile(FileName fileName, int fileFlags, int fileMode)
1267 {
1268  char *fnamecopy;
1269  File file;
1270  Vfd *vfdP;
1271 
1272  DO_DB(elog(LOG, "PathNameOpenFile: %s %x %o",
1273  fileName, fileFlags, fileMode));
1274 
1275  /*
1276  * We need a malloc'd copy of the file name; fail cleanly if no room.
1277  */
1278  fnamecopy = strdup(fileName);
1279  if (fnamecopy == NULL)
1280  ereport(ERROR,
1281  (errcode(ERRCODE_OUT_OF_MEMORY),
1282  errmsg("out of memory")));
1283 
1284  file = AllocateVfd();
1285  vfdP = &VfdCache[file];
1286 
1287  /* Close excess kernel FDs. */
1288  ReleaseLruFiles();
1289 
1290  vfdP->fd = BasicOpenFile(fileName, fileFlags, fileMode);
1291 
1292  if (vfdP->fd < 0)
1293  {
1294  int save_errno = errno;
1295 
1296  FreeVfd(file);
1297  free(fnamecopy);
1298  errno = save_errno;
1299  return -1;
1300  }
1301  ++nfile;
1302  DO_DB(elog(LOG, "PathNameOpenFile: success %d",
1303  vfdP->fd));
1304 
1305  Insert(file);
1306 
1307  vfdP->fileName = fnamecopy;
1308  /* Saved flags are adjusted to be OK for re-opening file */
1309  vfdP->fileFlags = fileFlags & ~(O_CREAT | O_TRUNC | O_EXCL);
1310  vfdP->fileMode = fileMode;
1311  vfdP->seekPos = 0;
1312  vfdP->fileSize = 0;
1313  vfdP->fdstate = 0x0;
1314  vfdP->resowner = NULL;
1315 
1316  return file;
1317 }
1318 
1319 /*
1320  * Open a temporary file that will disappear when we close it.
1321  *
1322  * This routine takes care of generating an appropriate tempfile name.
1323  * There's no need to pass in fileFlags or fileMode either, since only
1324  * one setting makes any sense for a temp file.
1325  *
1326  * Unless interXact is true, the file is remembered by CurrentResourceOwner
1327  * to ensure it's closed and deleted when it's no longer needed, typically at
1328  * the end-of-transaction. In most cases, you don't want temporary files to
1329  * outlive the transaction that created them, so this should be false -- but
1330  * if you need "somewhat" temporary storage, this might be useful. In either
1331  * case, the file is removed when the File is explicitly closed.
1332  */
1333 File
1334 OpenTemporaryFile(bool interXact)
1335 {
1336  File file = 0;
1337 
1338  /*
1339  * If some temp tablespace(s) have been given to us, try to use the next
1340  * one. If a given tablespace can't be found, we silently fall back to
1341  * the database's default tablespace.
1342  *
1343  * BUT: if the temp file is slated to outlive the current transaction,
1344  * force it into the database's default tablespace, so that it will not
1345  * pose a threat to possible tablespace drop attempts.
1346  */
1347  if (numTempTableSpaces > 0 && !interXact)
1348  {
1349  Oid tblspcOid = GetNextTempTableSpace();
1350 
1351  if (OidIsValid(tblspcOid))
1352  file = OpenTemporaryFileInTablespace(tblspcOid, false);
1353  }
1354 
1355  /*
1356  * If not, or if tablespace is bad, create in database's default
1357  * tablespace. MyDatabaseTableSpace should normally be set before we get
1358  * here, but just in case it isn't, fall back to pg_default tablespace.
1359  */
1360  if (file <= 0)
1364  true);
1365 
1366  /* Mark it for deletion at close */
1367  VfdCache[file].fdstate |= FD_TEMPORARY;
1368 
1369  /* Register it with the current resource owner */
1370  if (!interXact)
1371  {
1372  VfdCache[file].fdstate |= FD_XACT_TEMPORARY;
1373 
1376  VfdCache[file].resowner = CurrentResourceOwner;
1377 
1378  /* ensure cleanup happens at eoxact */
1380  }
1381 
1382  return file;
1383 }
1384 
1385 /*
1386  * Open a temporary file in a specific tablespace.
1387  * Subroutine for OpenTemporaryFile, which see for details.
1388  */
1389 static File
1390 OpenTemporaryFileInTablespace(Oid tblspcOid, bool rejectError)
1391 {
1392  char tempdirpath[MAXPGPATH];
1393  char tempfilepath[MAXPGPATH];
1394  File file;
1395 
1396  /*
1397  * Identify the tempfile directory for this tablespace.
1398  *
1399  * If someone tries to specify pg_global, use pg_default instead.
1400  */
1401  if (tblspcOid == DEFAULTTABLESPACE_OID ||
1402  tblspcOid == GLOBALTABLESPACE_OID)
1403  {
1404  /* The default tablespace is {datadir}/base */
1405  snprintf(tempdirpath, sizeof(tempdirpath), "base/%s",
1407  }
1408  else
1409  {
1410  /* All other tablespaces are accessed via symlinks */
1411  snprintf(tempdirpath, sizeof(tempdirpath), "pg_tblspc/%u/%s/%s",
1413  }
1414 
1415  /*
1416  * Generate a tempfile name that should be unique within the current
1417  * database instance.
1418  */
1419  snprintf(tempfilepath, sizeof(tempfilepath), "%s/%s%d.%ld",
1420  tempdirpath, PG_TEMP_FILE_PREFIX, MyProcPid, tempFileCounter++);
1421 
1422  /*
1423  * Open the file. Note: we don't use O_EXCL, in case there is an orphaned
1424  * temp file that can be reused.
1425  */
1426  file = PathNameOpenFile(tempfilepath,
1427  O_RDWR | O_CREAT | O_TRUNC | PG_BINARY,
1428  0600);
1429  if (file <= 0)
1430  {
1431  /*
1432  * We might need to create the tablespace's tempfile directory, if no
1433  * one has yet done so.
1434  *
1435  * Don't check for error from mkdir; it could fail if someone else
1436  * just did the same thing. If it doesn't work then we'll bomb out on
1437  * the second create attempt, instead.
1438  */
1439  mkdir(tempdirpath, S_IRWXU);
1440 
1441  file = PathNameOpenFile(tempfilepath,
1442  O_RDWR | O_CREAT | O_TRUNC | PG_BINARY,
1443  0600);
1444  if (file <= 0 && rejectError)
1445  elog(ERROR, "could not create temporary file \"%s\": %m",
1446  tempfilepath);
1447  }
1448 
1449  return file;
1450 }
1451 
1452 /*
1453  * close a file when done with it
1454  */
1455 void
1457 {
1458  Vfd *vfdP;
1459 
1460  Assert(FileIsValid(file));
1461 
1462  DO_DB(elog(LOG, "FileClose: %d (%s)",
1463  file, VfdCache[file].fileName));
1464 
1465  vfdP = &VfdCache[file];
1466 
1467  if (!FileIsNotOpen(file))
1468  {
1469  /* close the file */
1470  if (close(vfdP->fd))
1471  elog(LOG, "could not close file \"%s\": %m", vfdP->fileName);
1472 
1473  --nfile;
1474  vfdP->fd = VFD_CLOSED;
1475 
1476  /* remove the file from the lru ring */
1477  Delete(file);
1478  }
1479 
1480  /*
1481  * Delete the file if it was temporary, and make a log entry if wanted
1482  */
1483  if (vfdP->fdstate & FD_TEMPORARY)
1484  {
1485  struct stat filestats;
1486  int stat_errno;
1487 
1488  /*
1489  * If we get an error, as could happen within the ereport/elog calls,
1490  * we'll come right back here during transaction abort. Reset the
1491  * flag to ensure that we can't get into an infinite loop. This code
1492  * is arranged to ensure that the worst-case consequence is failing to
1493  * emit log message(s), not failing to attempt the unlink.
1494  */
1495  vfdP->fdstate &= ~FD_TEMPORARY;
1496 
1497  /* Subtract its size from current usage (do first in case of error) */
1498  temporary_files_size -= vfdP->fileSize;
1499  vfdP->fileSize = 0;
1500 
1501  /* first try the stat() */
1502  if (stat(vfdP->fileName, &filestats))
1503  stat_errno = errno;
1504  else
1505  stat_errno = 0;
1506 
1507  /* in any case do the unlink */
1508  if (unlink(vfdP->fileName))
1509  elog(LOG, "could not unlink file \"%s\": %m", vfdP->fileName);
1510 
1511  /* and last report the stat results */
1512  if (stat_errno == 0)
1513  {
1514  pgstat_report_tempfile(filestats.st_size);
1515 
1516  if (log_temp_files >= 0)
1517  {
1518  if ((filestats.st_size / 1024) >= log_temp_files)
1519  ereport(LOG,
1520  (errmsg("temporary file: path \"%s\", size %lu",
1521  vfdP->fileName,
1522  (unsigned long) filestats.st_size)));
1523  }
1524  }
1525  else
1526  {
1527  errno = stat_errno;
1528  elog(LOG, "could not stat file \"%s\": %m", vfdP->fileName);
1529  }
1530  }
1531 
1532  /* Unregister it from the resource owner */
1533  if (vfdP->resowner)
1534  ResourceOwnerForgetFile(vfdP->resowner, file);
1535 
1536  /*
1537  * Return the Vfd slot to the free list
1538  */
1539  FreeVfd(file);
1540 }
1541 
1542 /*
1543  * FilePrefetch - initiate asynchronous read of a given range of the file.
1544  * The logical seek position is unaffected.
1545  *
1546  * Currently the only implementation of this function is using posix_fadvise
1547  * which is the simplest standardized interface that accomplishes this.
1548  * We could add an implementation using libaio in the future; but note that
1549  * this API is inappropriate for libaio, which wants to have a buffer provided
1550  * to read into.
1551  */
1552 int
1553 FilePrefetch(File file, off_t offset, int amount, uint32 wait_event_info)
1554 {
1555 #if defined(USE_POSIX_FADVISE) && defined(POSIX_FADV_WILLNEED)
1556  int returnCode;
1557 
1558  Assert(FileIsValid(file));
1559 
1560  DO_DB(elog(LOG, "FilePrefetch: %d (%s) " INT64_FORMAT " %d",
1561  file, VfdCache[file].fileName,
1562  (int64) offset, amount));
1563 
1564  returnCode = FileAccess(file);
1565  if (returnCode < 0)
1566  return returnCode;
1567 
1568  pgstat_report_wait_start(wait_event_info);
1569  returnCode = posix_fadvise(VfdCache[file].fd, offset, amount,
1570  POSIX_FADV_WILLNEED);
1572 
1573  return returnCode;
1574 #else
1575  Assert(FileIsValid(file));
1576  return 0;
1577 #endif
1578 }
1579 
1580 void
1581 FileWriteback(File file, off_t offset, off_t nbytes, uint32 wait_event_info)
1582 {
1583  int returnCode;
1584 
1585  Assert(FileIsValid(file));
1586 
1587  DO_DB(elog(LOG, "FileWriteback: %d (%s) " INT64_FORMAT " " INT64_FORMAT,
1588  file, VfdCache[file].fileName,
1589  (int64) offset, (int64) nbytes));
1590 
1591  /*
1592  * Caution: do not call pg_flush_data with nbytes = 0, it could trash the
1593  * file's seek position. We prefer to define that as a no-op here.
1594  */
1595  if (nbytes <= 0)
1596  return;
1597 
1598  returnCode = FileAccess(file);
1599  if (returnCode < 0)
1600  return;
1601 
1602  pgstat_report_wait_start(wait_event_info);
1603  pg_flush_data(VfdCache[file].fd, offset, nbytes);
1605 }
1606 
1607 int
1608 FileRead(File file, char *buffer, int amount, uint32 wait_event_info)
1609 {
1610  int returnCode;
1611  Vfd *vfdP;
1612 
1613  Assert(FileIsValid(file));
1614 
1615  DO_DB(elog(LOG, "FileRead: %d (%s) " INT64_FORMAT " %d %p",
1616  file, VfdCache[file].fileName,
1617  (int64) VfdCache[file].seekPos,
1618  amount, buffer));
1619 
1620  returnCode = FileAccess(file);
1621  if (returnCode < 0)
1622  return returnCode;
1623 
1624  vfdP = &VfdCache[file];
1625 
1626 retry:
1627  pgstat_report_wait_start(wait_event_info);
1628  returnCode = read(vfdP->fd, buffer, amount);
1630 
1631  if (returnCode >= 0)
1632  {
1633  /* if seekPos is unknown, leave it that way */
1634  if (!FilePosIsUnknown(vfdP->seekPos))
1635  vfdP->seekPos += returnCode;
1636  }
1637  else
1638  {
1639  /*
1640  * Windows may run out of kernel buffers and return "Insufficient
1641  * system resources" error. Wait a bit and retry to solve it.
1642  *
1643  * It is rumored that EINTR is also possible on some Unix filesystems,
1644  * in which case immediate retry is indicated.
1645  */
1646 #ifdef WIN32
1647  DWORD error = GetLastError();
1648 
1649  switch (error)
1650  {
1651  case ERROR_NO_SYSTEM_RESOURCES:
1652  pg_usleep(1000L);
1653  errno = EINTR;
1654  break;
1655  default:
1656  _dosmaperr(error);
1657  break;
1658  }
1659 #endif
1660  /* OK to retry if interrupted */
1661  if (errno == EINTR)
1662  goto retry;
1663 
1664  /* Trouble, so assume we don't know the file position anymore */
1665  vfdP->seekPos = FileUnknownPos;
1666  }
1667 
1668  return returnCode;
1669 }
1670 
1671 int
1672 FileWrite(File file, char *buffer, int amount, uint32 wait_event_info)
1673 {
1674  int returnCode;
1675  Vfd *vfdP;
1676 
1677  Assert(FileIsValid(file));
1678 
1679  DO_DB(elog(LOG, "FileWrite: %d (%s) " INT64_FORMAT " %d %p",
1680  file, VfdCache[file].fileName,
1681  (int64) VfdCache[file].seekPos,
1682  amount, buffer));
1683 
1684  returnCode = FileAccess(file);
1685  if (returnCode < 0)
1686  return returnCode;
1687 
1688  vfdP = &VfdCache[file];
1689 
1690  /*
1691  * If enforcing temp_file_limit and it's a temp file, check to see if the
1692  * write would overrun temp_file_limit, and throw error if so. Note: it's
1693  * really a modularity violation to throw error here; we should set errno
1694  * and return -1. However, there's no way to report a suitable error
1695  * message if we do that. All current callers would just throw error
1696  * immediately anyway, so this is safe at present.
1697  */
1698  if (temp_file_limit >= 0 && (vfdP->fdstate & FD_TEMPORARY))
1699  {
1700  off_t newPos;
1701 
1702  /*
1703  * Normally we should know the seek position, but if for some reason
1704  * we have lost track of it, try again to get it. Here, it's fine to
1705  * throw an error if we still can't get it.
1706  */
1707  if (FilePosIsUnknown(vfdP->seekPos))
1708  {
1709  vfdP->seekPos = lseek(vfdP->fd, (off_t) 0, SEEK_CUR);
1710  if (FilePosIsUnknown(vfdP->seekPos))
1711  elog(ERROR, "could not seek file \"%s\": %m", vfdP->fileName);
1712  }
1713 
1714  newPos = vfdP->seekPos + amount;
1715  if (newPos > vfdP->fileSize)
1716  {
1717  uint64 newTotal = temporary_files_size;
1718 
1719  newTotal += newPos - vfdP->fileSize;
1720  if (newTotal > (uint64) temp_file_limit * (uint64) 1024)
1721  ereport(ERROR,
1722  (errcode(ERRCODE_CONFIGURATION_LIMIT_EXCEEDED),
1723  errmsg("temporary file size exceeds temp_file_limit (%dkB)",
1724  temp_file_limit)));
1725  }
1726  }
1727 
1728 retry:
1729  errno = 0;
1730  pgstat_report_wait_start(wait_event_info);
1731  returnCode = write(vfdP->fd, buffer, amount);
1733 
1734  /* if write didn't set errno, assume problem is no disk space */
1735  if (returnCode != amount && errno == 0)
1736  errno = ENOSPC;
1737 
1738  if (returnCode >= 0)
1739  {
1740  /* if seekPos is unknown, leave it that way */
1741  if (!FilePosIsUnknown(vfdP->seekPos))
1742  vfdP->seekPos += returnCode;
1743 
1744  /*
1745  * Maintain fileSize and temporary_files_size if it's a temp file.
1746  *
1747  * If seekPos is -1 (unknown), this will do nothing; but we could only
1748  * get here in that state if we're not enforcing temporary_files_size,
1749  * so we don't care.
1750  */
1751  if (vfdP->fdstate & FD_TEMPORARY)
1752  {
1753  off_t newPos = vfdP->seekPos;
1754 
1755  if (newPos > vfdP->fileSize)
1756  {
1757  temporary_files_size += newPos - vfdP->fileSize;
1758  vfdP->fileSize = newPos;
1759  }
1760  }
1761  }
1762  else
1763  {
1764  /*
1765  * See comments in FileRead()
1766  */
1767 #ifdef WIN32
1768  DWORD error = GetLastError();
1769 
1770  switch (error)
1771  {
1772  case ERROR_NO_SYSTEM_RESOURCES:
1773  pg_usleep(1000L);
1774  errno = EINTR;
1775  break;
1776  default:
1777  _dosmaperr(error);
1778  break;
1779  }
1780 #endif
1781  /* OK to retry if interrupted */
1782  if (errno == EINTR)
1783  goto retry;
1784 
1785  /* Trouble, so assume we don't know the file position anymore */
1786  vfdP->seekPos = FileUnknownPos;
1787  }
1788 
1789  return returnCode;
1790 }
1791 
1792 int
1793 FileSync(File file, uint32 wait_event_info)
1794 {
1795  int returnCode;
1796 
1797  Assert(FileIsValid(file));
1798 
1799  DO_DB(elog(LOG, "FileSync: %d (%s)",
1800  file, VfdCache[file].fileName));
1801 
1802  returnCode = FileAccess(file);
1803  if (returnCode < 0)
1804  return returnCode;
1805 
1806  pgstat_report_wait_start(wait_event_info);
1807  returnCode = pg_fsync(VfdCache[file].fd);
1809 
1810  return returnCode;
1811 }
1812 
1813 off_t
1814 FileSeek(File file, off_t offset, int whence)
1815 {
1816  Vfd *vfdP;
1817 
1818  Assert(FileIsValid(file));
1819 
1820  DO_DB(elog(LOG, "FileSeek: %d (%s) " INT64_FORMAT " " INT64_FORMAT " %d",
1821  file, VfdCache[file].fileName,
1822  (int64) VfdCache[file].seekPos,
1823  (int64) offset, whence));
1824 
1825  vfdP = &VfdCache[file];
1826 
1827  if (FileIsNotOpen(file))
1828  {
1829  switch (whence)
1830  {
1831  case SEEK_SET:
1832  if (offset < 0)
1833  {
1834  errno = EINVAL;
1835  return (off_t) -1;
1836  }
1837  vfdP->seekPos = offset;
1838  break;
1839  case SEEK_CUR:
1840  if (FilePosIsUnknown(vfdP->seekPos) ||
1841  vfdP->seekPos + offset < 0)
1842  {
1843  errno = EINVAL;
1844  return (off_t) -1;
1845  }
1846  vfdP->seekPos += offset;
1847  break;
1848  case SEEK_END:
1849  if (FileAccess(file) < 0)
1850  return (off_t) -1;
1851  vfdP->seekPos = lseek(vfdP->fd, offset, whence);
1852  break;
1853  default:
1854  elog(ERROR, "invalid whence: %d", whence);
1855  break;
1856  }
1857  }
1858  else
1859  {
1860  switch (whence)
1861  {
1862  case SEEK_SET:
1863  if (offset < 0)
1864  {
1865  errno = EINVAL;
1866  return (off_t) -1;
1867  }
1868  if (vfdP->seekPos != offset)
1869  vfdP->seekPos = lseek(vfdP->fd, offset, whence);
1870  break;
1871  case SEEK_CUR:
1872  if (offset != 0 || FilePosIsUnknown(vfdP->seekPos))
1873  vfdP->seekPos = lseek(vfdP->fd, offset, whence);
1874  break;
1875  case SEEK_END:
1876  vfdP->seekPos = lseek(vfdP->fd, offset, whence);
1877  break;
1878  default:
1879  elog(ERROR, "invalid whence: %d", whence);
1880  break;
1881  }
1882  }
1883 
1884  return vfdP->seekPos;
1885 }
1886 
1887 /*
1888  * XXX not actually used but here for completeness
1889  */
1890 #ifdef NOT_USED
1891 off_t
1892 FileTell(File file)
1893 {
1894  Assert(FileIsValid(file));
1895  DO_DB(elog(LOG, "FileTell %d (%s)",
1896  file, VfdCache[file].fileName));
1897  return VfdCache[file].seekPos;
1898 }
1899 #endif
1900 
1901 int
1902 FileTruncate(File file, off_t offset, uint32 wait_event_info)
1903 {
1904  int returnCode;
1905 
1906  Assert(FileIsValid(file));
1907 
1908  DO_DB(elog(LOG, "FileTruncate %d (%s)",
1909  file, VfdCache[file].fileName));
1910 
1911  returnCode = FileAccess(file);
1912  if (returnCode < 0)
1913  return returnCode;
1914 
1915  pgstat_report_wait_start(wait_event_info);
1916  returnCode = ftruncate(VfdCache[file].fd, offset);
1918 
1919  if (returnCode == 0 && VfdCache[file].fileSize > offset)
1920  {
1921  /* adjust our state for truncation of a temp file */
1922  Assert(VfdCache[file].fdstate & FD_TEMPORARY);
1923  temporary_files_size -= VfdCache[file].fileSize - offset;
1924  VfdCache[file].fileSize = offset;
1925  }
1926 
1927  return returnCode;
1928 }
1929 
1930 /*
1931  * Return the pathname associated with an open file.
1932  *
1933  * The returned string points to an internal buffer, which is valid until
1934  * the file is closed.
1935  */
1936 char *
1938 {
1939  Assert(FileIsValid(file));
1940 
1941  return VfdCache[file].fileName;
1942 }
1943 
1944 /*
1945  * Return the raw file descriptor of an opened file.
1946  *
1947  * The returned file descriptor will be valid until the file is closed, but
1948  * there are a lot of things that can make that happen. So the caller should
1949  * be careful not to do much of anything else before it finishes using the
1950  * returned file descriptor.
1951  */
1952 int
1954 {
1955  Assert(FileIsValid(file));
1956  return VfdCache[file].fd;
1957 }
1958 
1959 /*
1960  * FileGetRawFlags - returns the file flags on open(2)
1961  */
1962 int
1964 {
1965  Assert(FileIsValid(file));
1966  return VfdCache[file].fileFlags;
1967 }
1968 
1969 /*
1970  * FileGetRawMode - returns the mode bitmask passed to open(2)
1971  */
1972 int
1974 {
1975  Assert(FileIsValid(file));
1976  return VfdCache[file].fileMode;
1977 }
1978 
1979 /*
1980  * Make room for another allocatedDescs[] array entry if needed and possible.
1981  * Returns true if an array element is available.
1982  */
1983 static bool
1985 {
1986  AllocateDesc *newDescs;
1987  int newMax;
1988 
1989  /* Quick out if array already has a free slot. */
1991  return true;
1992 
1993  /*
1994  * If the array hasn't yet been created in the current process, initialize
1995  * it with FD_MINFREE / 2 elements. In many scenarios this is as many as
1996  * we will ever need, anyway. We don't want to look at max_safe_fds
1997  * immediately because set_max_safe_fds() may not have run yet.
1998  */
1999  if (allocatedDescs == NULL)
2000  {
2001  newMax = FD_MINFREE / 2;
2002  newDescs = (AllocateDesc *) malloc(newMax * sizeof(AllocateDesc));
2003  /* Out of memory already? Treat as fatal error. */
2004  if (newDescs == NULL)
2005  ereport(ERROR,
2006  (errcode(ERRCODE_OUT_OF_MEMORY),
2007  errmsg("out of memory")));
2008  allocatedDescs = newDescs;
2009  maxAllocatedDescs = newMax;
2010  return true;
2011  }
2012 
2013  /*
2014  * Consider enlarging the array beyond the initial allocation used above.
2015  * By the time this happens, max_safe_fds should be known accurately.
2016  *
2017  * We mustn't let allocated descriptors hog all the available FDs, and in
2018  * practice we'd better leave a reasonable number of FDs for VFD use. So
2019  * set the maximum to max_safe_fds / 2. (This should certainly be at
2020  * least as large as the initial size, FD_MINFREE / 2.)
2021  */
2022  newMax = max_safe_fds / 2;
2023  if (newMax > maxAllocatedDescs)
2024  {
2025  newDescs = (AllocateDesc *) realloc(allocatedDescs,
2026  newMax * sizeof(AllocateDesc));
2027  /* Treat out-of-memory as a non-fatal error. */
2028  if (newDescs == NULL)
2029  return false;
2030  allocatedDescs = newDescs;
2031  maxAllocatedDescs = newMax;
2032  return true;
2033  }
2034 
2035  /* Can't enlarge allocatedDescs[] any more. */
2036  return false;
2037 }
2038 
2039 /*
2040  * Routines that want to use stdio (ie, FILE*) should use AllocateFile
2041  * rather than plain fopen(). This lets fd.c deal with freeing FDs if
2042  * necessary to open the file. When done, call FreeFile rather than fclose.
2043  *
2044  * Note that files that will be open for any significant length of time
2045  * should NOT be handled this way, since they cannot share kernel file
2046  * descriptors with other files; there is grave risk of running out of FDs
2047  * if anyone locks down too many FDs. Most callers of this routine are
2048  * simply reading a config file that they will read and close immediately.
2049  *
2050  * fd.c will automatically close all files opened with AllocateFile at
2051  * transaction commit or abort; this prevents FD leakage if a routine
2052  * that calls AllocateFile is terminated prematurely by ereport(ERROR).
2053  *
2054  * Ideally this should be the *only* direct call of fopen() in the backend.
2055  */
2056 FILE *
2057 AllocateFile(const char *name, const char *mode)
2058 {
2059  FILE *file;
2060 
2061  DO_DB(elog(LOG, "AllocateFile: Allocated %d (%s)",
2062  numAllocatedDescs, name));
2063 
2064  /* Can we allocate another non-virtual FD? */
2065  if (!reserveAllocatedDesc())
2066  ereport(ERROR,
2067  (errcode(ERRCODE_INSUFFICIENT_RESOURCES),
2068  errmsg("exceeded maxAllocatedDescs (%d) while trying to open file \"%s\"",
2069  maxAllocatedDescs, name)));
2070 
2071  /* Close excess kernel FDs. */
2072  ReleaseLruFiles();
2073 
2074 TryAgain:
2075  if ((file = fopen(name, mode)) != NULL)
2076  {
2077  AllocateDesc *desc = &allocatedDescs[numAllocatedDescs];
2078 
2079  desc->kind = AllocateDescFile;
2080  desc->desc.file = file;
2083  return desc->desc.file;
2084  }
2085 
2086  if (errno == EMFILE || errno == ENFILE)
2087  {
2088  int save_errno = errno;
2089 
2090  ereport(LOG,
2091  (errcode(ERRCODE_INSUFFICIENT_RESOURCES),
2092  errmsg("out of file descriptors: %m; release and retry")));
2093  errno = 0;
2094  if (ReleaseLruFile())
2095  goto TryAgain;
2096  errno = save_errno;
2097  }
2098 
2099  return NULL;
2100 }
2101 
2102 
2103 /*
2104  * Like AllocateFile, but returns an unbuffered fd like open(2)
2105  */
2106 int
2107 OpenTransientFile(FileName fileName, int fileFlags, int fileMode)
2108 {
2109  int fd;
2110 
2111  DO_DB(elog(LOG, "OpenTransientFile: Allocated %d (%s)",
2112  numAllocatedDescs, fileName));
2113 
2114  /* Can we allocate another non-virtual FD? */
2115  if (!reserveAllocatedDesc())
2116  ereport(ERROR,
2117  (errcode(ERRCODE_INSUFFICIENT_RESOURCES),
2118  errmsg("exceeded maxAllocatedDescs (%d) while trying to open file \"%s\"",
2119  maxAllocatedDescs, fileName)));
2120 
2121  /* Close excess kernel FDs. */
2122  ReleaseLruFiles();
2123 
2124  fd = BasicOpenFile(fileName, fileFlags, fileMode);
2125 
2126  if (fd >= 0)
2127  {
2128  AllocateDesc *desc = &allocatedDescs[numAllocatedDescs];
2129 
2130  desc->kind = AllocateDescRawFD;
2131  desc->desc.fd = fd;
2134 
2135  return fd;
2136  }
2137 
2138  return -1; /* failure */
2139 }
2140 
2141 /*
2142  * Routines that want to initiate a pipe stream should use OpenPipeStream
2143  * rather than plain popen(). This lets fd.c deal with freeing FDs if
2144  * necessary. When done, call ClosePipeStream rather than pclose.
2145  */
2146 FILE *
2147 OpenPipeStream(const char *command, const char *mode)
2148 {
2149  FILE *file;
2150 
2151  DO_DB(elog(LOG, "OpenPipeStream: Allocated %d (%s)",
2152  numAllocatedDescs, command));
2153 
2154  /* Can we allocate another non-virtual FD? */
2155  if (!reserveAllocatedDesc())
2156  ereport(ERROR,
2157  (errcode(ERRCODE_INSUFFICIENT_RESOURCES),
2158  errmsg("exceeded maxAllocatedDescs (%d) while trying to execute command \"%s\"",
2159  maxAllocatedDescs, command)));
2160 
2161  /* Close excess kernel FDs. */
2162  ReleaseLruFiles();
2163 
2164 TryAgain:
2165  fflush(stdout);
2166  fflush(stderr);
2167  errno = 0;
2168  if ((file = popen(command, mode)) != NULL)
2169  {
2170  AllocateDesc *desc = &allocatedDescs[numAllocatedDescs];
2171 
2172  desc->kind = AllocateDescPipe;
2173  desc->desc.file = file;
2176  return desc->desc.file;
2177  }
2178 
2179  if (errno == EMFILE || errno == ENFILE)
2180  {
2181  int save_errno = errno;
2182 
2183  ereport(LOG,
2184  (errcode(ERRCODE_INSUFFICIENT_RESOURCES),
2185  errmsg("out of file descriptors: %m; release and retry")));
2186  errno = 0;
2187  if (ReleaseLruFile())
2188  goto TryAgain;
2189  errno = save_errno;
2190  }
2191 
2192  return NULL;
2193 }
2194 
2195 /*
2196  * Free an AllocateDesc of any type.
2197  *
2198  * The argument *must* point into the allocatedDescs[] array.
2199  */
2200 static int
2202 {
2203  int result;
2204 
2205  /* Close the underlying object */
2206  switch (desc->kind)
2207  {
2208  case AllocateDescFile:
2209  result = fclose(desc->desc.file);
2210  break;
2211  case AllocateDescPipe:
2212  result = pclose(desc->desc.file);
2213  break;
2214  case AllocateDescDir:
2215  result = closedir(desc->desc.dir);
2216  break;
2217  case AllocateDescRawFD:
2218  result = close(desc->desc.fd);
2219  break;
2220  default:
2221  elog(ERROR, "AllocateDesc kind not recognized");
2222  result = 0; /* keep compiler quiet */
2223  break;
2224  }
2225 
2226  /* Compact storage in the allocatedDescs array */
2228  *desc = allocatedDescs[numAllocatedDescs];
2229 
2230  return result;
2231 }
2232 
2233 /*
2234  * Close a file returned by AllocateFile.
2235  *
2236  * Note we do not check fclose's return value --- it is up to the caller
2237  * to handle close errors.
2238  */
2239 int
2240 FreeFile(FILE *file)
2241 {
2242  int i;
2243 
2244  DO_DB(elog(LOG, "FreeFile: Allocated %d", numAllocatedDescs));
2245 
2246  /* Remove file from list of allocated files, if it's present */
2247  for (i = numAllocatedDescs; --i >= 0;)
2248  {
2249  AllocateDesc *desc = &allocatedDescs[i];
2250 
2251  if (desc->kind == AllocateDescFile && desc->desc.file == file)
2252  return FreeDesc(desc);
2253  }
2254 
2255  /* Only get here if someone passes us a file not in allocatedDescs */
2256  elog(WARNING, "file passed to FreeFile was not obtained from AllocateFile");
2257 
2258  return fclose(file);
2259 }
2260 
2261 /*
2262  * Close a file returned by OpenTransientFile.
2263  *
2264  * Note we do not check close's return value --- it is up to the caller
2265  * to handle close errors.
2266  */
2267 int
2269 {
2270  int i;
2271 
2272  DO_DB(elog(LOG, "CloseTransientFile: Allocated %d", numAllocatedDescs));
2273 
2274  /* Remove fd from list of allocated files, if it's present */
2275  for (i = numAllocatedDescs; --i >= 0;)
2276  {
2277  AllocateDesc *desc = &allocatedDescs[i];
2278 
2279  if (desc->kind == AllocateDescRawFD && desc->desc.fd == fd)
2280  return FreeDesc(desc);
2281  }
2282 
2283  /* Only get here if someone passes us a file not in allocatedDescs */
2284  elog(WARNING, "fd passed to CloseTransientFile was not obtained from OpenTransientFile");
2285 
2286  return close(fd);
2287 }
2288 
2289 /*
2290  * Routines that want to use <dirent.h> (ie, DIR*) should use AllocateDir
2291  * rather than plain opendir(). This lets fd.c deal with freeing FDs if
2292  * necessary to open the directory, and with closing it after an elog.
2293  * When done, call FreeDir rather than closedir.
2294  *
2295  * Ideally this should be the *only* direct call of opendir() in the backend.
2296  */
2297 DIR *
2298 AllocateDir(const char *dirname)
2299 {
2300  DIR *dir;
2301 
2302  DO_DB(elog(LOG, "AllocateDir: Allocated %d (%s)",
2303  numAllocatedDescs, dirname));
2304 
2305  /* Can we allocate another non-virtual FD? */
2306  if (!reserveAllocatedDesc())
2307  ereport(ERROR,
2308  (errcode(ERRCODE_INSUFFICIENT_RESOURCES),
2309  errmsg("exceeded maxAllocatedDescs (%d) while trying to open directory \"%s\"",
2310  maxAllocatedDescs, dirname)));
2311 
2312  /* Close excess kernel FDs. */
2313  ReleaseLruFiles();
2314 
2315 TryAgain:
2316  if ((dir = opendir(dirname)) != NULL)
2317  {
2318  AllocateDesc *desc = &allocatedDescs[numAllocatedDescs];
2319 
2320  desc->kind = AllocateDescDir;
2321  desc->desc.dir = dir;
2324  return desc->desc.dir;
2325  }
2326 
2327  if (errno == EMFILE || errno == ENFILE)
2328  {
2329  int save_errno = errno;
2330 
2331  ereport(LOG,
2332  (errcode(ERRCODE_INSUFFICIENT_RESOURCES),
2333  errmsg("out of file descriptors: %m; release and retry")));
2334  errno = 0;
2335  if (ReleaseLruFile())
2336  goto TryAgain;
2337  errno = save_errno;
2338  }
2339 
2340  return NULL;
2341 }
2342 
2343 /*
2344  * Read a directory opened with AllocateDir, ereport'ing any error.
2345  *
2346  * This is easier to use than raw readdir() since it takes care of some
2347  * otherwise rather tedious and error-prone manipulation of errno. Also,
2348  * if you are happy with a generic error message for AllocateDir failure,
2349  * you can just do
2350  *
2351  * dir = AllocateDir(path);
2352  * while ((dirent = ReadDir(dir, path)) != NULL)
2353  * process dirent;
2354  * FreeDir(dir);
2355  *
2356  * since a NULL dir parameter is taken as indicating AllocateDir failed.
2357  * (Make sure errno hasn't been changed since AllocateDir if you use this
2358  * shortcut.)
2359  *
2360  * The pathname passed to AllocateDir must be passed to this routine too,
2361  * but it is only used for error reporting.
2362  */
2363 struct dirent *
2364 ReadDir(DIR *dir, const char *dirname)
2365 {
2366  return ReadDirExtended(dir, dirname, ERROR);
2367 }
2368 
2369 /*
2370  * Alternate version that allows caller to specify the elevel for any
2371  * error report. If elevel < ERROR, returns NULL on any error.
2372  */
2373 static struct dirent *
2374 ReadDirExtended(DIR *dir, const char *dirname, int elevel)
2375 {
2376  struct dirent *dent;
2377 
2378  /* Give a generic message for AllocateDir failure, if caller didn't */
2379  if (dir == NULL)
2380  {
2381  ereport(elevel,
2383  errmsg("could not open directory \"%s\": %m",
2384  dirname)));
2385  return NULL;
2386  }
2387 
2388  errno = 0;
2389  if ((dent = readdir(dir)) != NULL)
2390  return dent;
2391 
2392  if (errno)
2393  ereport(elevel,
2395  errmsg("could not read directory \"%s\": %m",
2396  dirname)));
2397  return NULL;
2398 }
2399 
2400 /*
2401  * Close a directory opened with AllocateDir.
2402  *
2403  * Note we do not check closedir's return value --- it is up to the caller
2404  * to handle close errors.
2405  */
2406 int
2408 {
2409  int i;
2410 
2411  DO_DB(elog(LOG, "FreeDir: Allocated %d", numAllocatedDescs));
2412 
2413  /* Remove dir from list of allocated dirs, if it's present */
2414  for (i = numAllocatedDescs; --i >= 0;)
2415  {
2416  AllocateDesc *desc = &allocatedDescs[i];
2417 
2418  if (desc->kind == AllocateDescDir && desc->desc.dir == dir)
2419  return FreeDesc(desc);
2420  }
2421 
2422  /* Only get here if someone passes us a dir not in allocatedDescs */
2423  elog(WARNING, "dir passed to FreeDir was not obtained from AllocateDir");
2424 
2425  return closedir(dir);
2426 }
2427 
2428 
2429 /*
2430  * Close a pipe stream returned by OpenPipeStream.
2431  */
2432 int
2433 ClosePipeStream(FILE *file)
2434 {
2435  int i;
2436 
2437  DO_DB(elog(LOG, "ClosePipeStream: Allocated %d", numAllocatedDescs));
2438 
2439  /* Remove file from list of allocated files, if it's present */
2440  for (i = numAllocatedDescs; --i >= 0;)
2441  {
2442  AllocateDesc *desc = &allocatedDescs[i];
2443 
2444  if (desc->kind == AllocateDescPipe && desc->desc.file == file)
2445  return FreeDesc(desc);
2446  }
2447 
2448  /* Only get here if someone passes us a file not in allocatedDescs */
2449  elog(WARNING, "file passed to ClosePipeStream was not obtained from OpenPipeStream");
2450 
2451  return pclose(file);
2452 }
2453 
2454 /*
2455  * closeAllVfds
2456  *
2457  * Force all VFDs into the physically-closed state, so that the fewest
2458  * possible number of kernel file descriptors are in use. There is no
2459  * change in the logical state of the VFDs.
2460  */
2461 void
2463 {
2464  Index i;
2465 
2466  if (SizeVfdCache > 0)
2467  {
2468  Assert(FileIsNotOpen(0)); /* Make sure ring not corrupted */
2469  for (i = 1; i < SizeVfdCache; i++)
2470  {
2471  if (!FileIsNotOpen(i))
2472  LruDelete(i);
2473  }
2474  }
2475 }
2476 
2477 
2478 /*
2479  * SetTempTablespaces
2480  *
2481  * Define a list (actually an array) of OIDs of tablespaces to use for
2482  * temporary files. This list will be used until end of transaction,
2483  * unless this function is called again before then. It is caller's
2484  * responsibility that the passed-in array has adequate lifespan (typically
2485  * it'd be allocated in TopTransactionContext).
2486  */
2487 void
2488 SetTempTablespaces(Oid *tableSpaces, int numSpaces)
2489 {
2490  Assert(numSpaces >= 0);
2491  tempTableSpaces = tableSpaces;
2492  numTempTableSpaces = numSpaces;
2493 
2494  /*
2495  * Select a random starting point in the list. This is to minimize
2496  * conflicts between backends that are most likely sharing the same list
2497  * of temp tablespaces. Note that if we create multiple temp files in the
2498  * same transaction, we'll advance circularly through the list --- this
2499  * ensures that large temporary sort files are nicely spread across all
2500  * available tablespaces.
2501  */
2502  if (numSpaces > 1)
2503  nextTempTableSpace = random() % numSpaces;
2504  else
2505  nextTempTableSpace = 0;
2506 }
2507 
2508 /*
2509  * TempTablespacesAreSet
2510  *
2511  * Returns TRUE if SetTempTablespaces has been called in current transaction.
2512  * (This is just so that tablespaces.c doesn't need its own per-transaction
2513  * state.)
2514  */
2515 bool
2517 {
2518  return (numTempTableSpaces >= 0);
2519 }
2520 
2521 /*
2522  * GetNextTempTableSpace
2523  *
2524  * Select the next temp tablespace to use. A result of InvalidOid means
2525  * to use the current database's default tablespace.
2526  */
2527 Oid
2529 {
2530  if (numTempTableSpaces > 0)
2531  {
2532  /* Advance nextTempTableSpace counter with wraparound */
2534  nextTempTableSpace = 0;
2536  }
2537  return InvalidOid;
2538 }
2539 
2540 
2541 /*
2542  * AtEOSubXact_Files
2543  *
2544  * Take care of subtransaction commit/abort. At abort, we close temp files
2545  * that the subtransaction may have opened. At commit, we reassign the
2546  * files that were opened to the parent subtransaction.
2547  */
2548 void
2549 AtEOSubXact_Files(bool isCommit, SubTransactionId mySubid,
2550  SubTransactionId parentSubid)
2551 {
2552  Index i;
2553 
2554  for (i = 0; i < numAllocatedDescs; i++)
2555  {
2556  if (allocatedDescs[i].create_subid == mySubid)
2557  {
2558  if (isCommit)
2559  allocatedDescs[i].create_subid = parentSubid;
2560  else
2561  {
2562  /* have to recheck the item after FreeDesc (ugly) */
2563  FreeDesc(&allocatedDescs[i--]);
2564  }
2565  }
2566  }
2567 }
2568 
2569 /*
2570  * AtEOXact_Files
2571  *
2572  * This routine is called during transaction commit or abort (it doesn't
2573  * particularly care which). All still-open per-transaction temporary file
2574  * VFDs are closed, which also causes the underlying files to be deleted
2575  * (although they should've been closed already by the ResourceOwner
2576  * cleanup). Furthermore, all "allocated" stdio files are closed. We also
2577  * forget any transaction-local temp tablespace list.
2578  */
2579 void
2581 {
2582  CleanupTempFiles(false);
2584  numTempTableSpaces = -1;
2585 }
2586 
2587 /*
2588  * AtProcExit_Files
2589  *
2590  * on_proc_exit hook to clean up temp files during backend shutdown.
2591  * Here, we want to clean up *all* temp files including interXact ones.
2592  */
2593 static void
2595 {
2596  CleanupTempFiles(true);
2597 }
2598 
2599 /*
2600  * Close temporary files and delete their underlying files.
2601  *
2602  * isProcExit: if true, this is being called as the backend process is
2603  * exiting. If that's the case, we should remove all temporary files; if
2604  * that's not the case, we are being called for transaction commit/abort
2605  * and should only remove transaction-local temp files. In either case,
2606  * also clean up "allocated" stdio files, dirs and fds.
2607  */
2608 static void
2609 CleanupTempFiles(bool isProcExit)
2610 {
2611  Index i;
2612 
2613  /*
2614  * Careful here: at proc_exit we need extra cleanup, not just
2615  * xact_temporary files.
2616  */
2617  if (isProcExit || have_xact_temporary_files)
2618  {
2619  Assert(FileIsNotOpen(0)); /* Make sure ring not corrupted */
2620  for (i = 1; i < SizeVfdCache; i++)
2621  {
2622  unsigned short fdstate = VfdCache[i].fdstate;
2623 
2624  if ((fdstate & FD_TEMPORARY) && VfdCache[i].fileName != NULL)
2625  {
2626  /*
2627  * If we're in the process of exiting a backend process, close
2628  * all temporary files. Otherwise, only close temporary files
2629  * local to the current transaction. They should be closed by
2630  * the ResourceOwner mechanism already, so this is just a
2631  * debugging cross-check.
2632  */
2633  if (isProcExit)
2634  FileClose(i);
2635  else if (fdstate & FD_XACT_TEMPORARY)
2636  {
2637  elog(WARNING,
2638  "temporary file %s not closed at end-of-transaction",
2639  VfdCache[i].fileName);
2640  FileClose(i);
2641  }
2642  }
2643  }
2644 
2645  have_xact_temporary_files = false;
2646  }
2647 
2648  /* Clean up "allocated" stdio files, dirs and fds. */
2649  while (numAllocatedDescs > 0)
2650  FreeDesc(&allocatedDescs[0]);
2651 }
2652 
2653 
2654 /*
2655  * Remove temporary and temporary relation files left over from a prior
2656  * postmaster session
2657  *
2658  * This should be called during postmaster startup. It will forcibly
2659  * remove any leftover files created by OpenTemporaryFile and any leftover
2660  * temporary relation files created by mdcreate.
2661  *
2662  * NOTE: we could, but don't, call this during a post-backend-crash restart
2663  * cycle. The argument for not doing it is that someone might want to examine
2664  * the temp files for debugging purposes. This does however mean that
2665  * OpenTemporaryFile had better allow for collision with an existing temp
2666  * file name.
2667  */
2668 void
2670 {
2671  char temp_path[MAXPGPATH];
2672  DIR *spc_dir;
2673  struct dirent *spc_de;
2674 
2675  /*
2676  * First process temp files in pg_default ($PGDATA/base)
2677  */
2678  snprintf(temp_path, sizeof(temp_path), "base/%s", PG_TEMP_FILES_DIR);
2679  RemovePgTempFilesInDir(temp_path);
2680  RemovePgTempRelationFiles("base");
2681 
2682  /*
2683  * Cycle through temp directories for all non-default tablespaces.
2684  */
2685  spc_dir = AllocateDir("pg_tblspc");
2686 
2687  while ((spc_de = ReadDir(spc_dir, "pg_tblspc")) != NULL)
2688  {
2689  if (strcmp(spc_de->d_name, ".") == 0 ||
2690  strcmp(spc_de->d_name, "..") == 0)
2691  continue;
2692 
2693  snprintf(temp_path, sizeof(temp_path), "pg_tblspc/%s/%s/%s",
2695  RemovePgTempFilesInDir(temp_path);
2696 
2697  snprintf(temp_path, sizeof(temp_path), "pg_tblspc/%s/%s",
2699  RemovePgTempRelationFiles(temp_path);
2700  }
2701 
2702  FreeDir(spc_dir);
2703 
2704  /*
2705  * In EXEC_BACKEND case there is a pgsql_tmp directory at the top level of
2706  * DataDir as well.
2707  */
2708 #ifdef EXEC_BACKEND
2710 #endif
2711 }
2712 
2713 /* Process one pgsql_tmp directory for RemovePgTempFiles */
2714 static void
2715 RemovePgTempFilesInDir(const char *tmpdirname)
2716 {
2717  DIR *temp_dir;
2718  struct dirent *temp_de;
2719  char rm_path[MAXPGPATH];
2720 
2721  temp_dir = AllocateDir(tmpdirname);
2722  if (temp_dir == NULL)
2723  {
2724  /* anything except ENOENT is fishy */
2725  if (errno != ENOENT)
2726  elog(LOG,
2727  "could not open temporary-files directory \"%s\": %m",
2728  tmpdirname);
2729  return;
2730  }
2731 
2732  while ((temp_de = ReadDir(temp_dir, tmpdirname)) != NULL)
2733  {
2734  if (strcmp(temp_de->d_name, ".") == 0 ||
2735  strcmp(temp_de->d_name, "..") == 0)
2736  continue;
2737 
2738  snprintf(rm_path, sizeof(rm_path), "%s/%s",
2739  tmpdirname, temp_de->d_name);
2740 
2741  if (strncmp(temp_de->d_name,
2743  strlen(PG_TEMP_FILE_PREFIX)) == 0)
2744  unlink(rm_path); /* note we ignore any error */
2745  else
2746  elog(LOG,
2747  "unexpected file found in temporary-files directory: \"%s\"",
2748  rm_path);
2749  }
2750 
2751  FreeDir(temp_dir);
2752 }
2753 
2754 /* Process one tablespace directory, look for per-DB subdirectories */
2755 static void
2756 RemovePgTempRelationFiles(const char *tsdirname)
2757 {
2758  DIR *ts_dir;
2759  struct dirent *de;
2760  char dbspace_path[MAXPGPATH];
2761 
2762  ts_dir = AllocateDir(tsdirname);
2763  if (ts_dir == NULL)
2764  {
2765  /* anything except ENOENT is fishy */
2766  if (errno != ENOENT)
2767  elog(LOG,
2768  "could not open tablespace directory \"%s\": %m",
2769  tsdirname);
2770  return;
2771  }
2772 
2773  while ((de = ReadDir(ts_dir, tsdirname)) != NULL)
2774  {
2775  int i = 0;
2776 
2777  /*
2778  * We're only interested in the per-database directories, which have
2779  * numeric names. Note that this code will also (properly) ignore "."
2780  * and "..".
2781  */
2782  while (isdigit((unsigned char) de->d_name[i]))
2783  ++i;
2784  if (de->d_name[i] != '\0' || i == 0)
2785  continue;
2786 
2787  snprintf(dbspace_path, sizeof(dbspace_path), "%s/%s",
2788  tsdirname, de->d_name);
2789  RemovePgTempRelationFilesInDbspace(dbspace_path);
2790  }
2791 
2792  FreeDir(ts_dir);
2793 }
2794 
2795 /* Process one per-dbspace directory for RemovePgTempRelationFiles */
2796 static void
2797 RemovePgTempRelationFilesInDbspace(const char *dbspacedirname)
2798 {
2799  DIR *dbspace_dir;
2800  struct dirent *de;
2801  char rm_path[MAXPGPATH];
2802 
2803  dbspace_dir = AllocateDir(dbspacedirname);
2804  if (dbspace_dir == NULL)
2805  {
2806  /* we just saw this directory, so it really ought to be there */
2807  elog(LOG,
2808  "could not open dbspace directory \"%s\": %m",
2809  dbspacedirname);
2810  return;
2811  }
2812 
2813  while ((de = ReadDir(dbspace_dir, dbspacedirname)) != NULL)
2814  {
2815  if (!looks_like_temp_rel_name(de->d_name))
2816  continue;
2817 
2818  snprintf(rm_path, sizeof(rm_path), "%s/%s",
2819  dbspacedirname, de->d_name);
2820 
2821  unlink(rm_path); /* note we ignore any error */
2822  }
2823 
2824  FreeDir(dbspace_dir);
2825 }
2826 
2827 /* t<digits>_<digits>, or t<digits>_<digits>_<forkname> */
2828 static bool
2830 {
2831  int pos;
2832  int savepos;
2833 
2834  /* Must start with "t". */
2835  if (name[0] != 't')
2836  return false;
2837 
2838  /* Followed by a non-empty string of digits and then an underscore. */
2839  for (pos = 1; isdigit((unsigned char) name[pos]); ++pos)
2840  ;
2841  if (pos == 1 || name[pos] != '_')
2842  return false;
2843 
2844  /* Followed by another nonempty string of digits. */
2845  for (savepos = ++pos; isdigit((unsigned char) name[pos]); ++pos)
2846  ;
2847  if (savepos == pos)
2848  return false;
2849 
2850  /* We might have _forkname or .segment or both. */
2851  if (name[pos] == '_')
2852  {
2853  int forkchar = forkname_chars(&name[pos + 1], NULL);
2854 
2855  if (forkchar <= 0)
2856  return false;
2857  pos += forkchar + 1;
2858  }
2859  if (name[pos] == '.')
2860  {
2861  int segchar;
2862 
2863  for (segchar = 1; isdigit((unsigned char) name[pos + segchar]); ++segchar)
2864  ;
2865  if (segchar <= 1)
2866  return false;
2867  pos += segchar;
2868  }
2869 
2870  /* Now we should be at the end. */
2871  if (name[pos] != '\0')
2872  return false;
2873  return true;
2874 }
2875 
2876 
2877 /*
2878  * Issue fsync recursively on PGDATA and all its contents.
2879  *
2880  * We fsync regular files and directories wherever they are, but we
2881  * follow symlinks only for pg_wal and immediately under pg_tblspc.
2882  * Other symlinks are presumed to point at files we're not responsible
2883  * for fsyncing, and might not have privileges to write at all.
2884  *
2885  * Errors are logged but not considered fatal; that's because this is used
2886  * only during database startup, to deal with the possibility that there are
2887  * issued-but-unsynced writes pending against the data directory. We want to
2888  * ensure that such writes reach disk before anything that's done in the new
2889  * run. However, aborting on error would result in failure to start for
2890  * harmless cases such as read-only files in the data directory, and that's
2891  * not good either.
2892  *
2893  * Note we assume we're chdir'd into PGDATA to begin with.
2894  */
2895 void
2897 {
2898  bool xlog_is_symlink;
2899 
2900  /* We can skip this whole thing if fsync is disabled. */
2901  if (!enableFsync)
2902  return;
2903 
2904  /*
2905  * If pg_wal is a symlink, we'll need to recurse into it separately,
2906  * because the first walkdir below will ignore it.
2907  */
2908  xlog_is_symlink = false;
2909 
2910 #ifndef WIN32
2911  {
2912  struct stat st;
2913 
2914  if (lstat("pg_wal", &st) < 0)
2915  ereport(LOG,
2917  errmsg("could not stat file \"%s\": %m",
2918  "pg_wal")));
2919  else if (S_ISLNK(st.st_mode))
2920  xlog_is_symlink = true;
2921  }
2922 #else
2923  if (pgwin32_is_junction("pg_wal"))
2924  xlog_is_symlink = true;
2925 #endif
2926 
2927  /*
2928  * If possible, hint to the kernel that we're soon going to fsync the data
2929  * directory and its contents. Errors in this step are even less
2930  * interesting than normal, so log them only at DEBUG1.
2931  */
2932 #ifdef PG_FLUSH_DATA_WORKS
2933  walkdir(".", pre_sync_fname, false, DEBUG1);
2934  if (xlog_is_symlink)
2935  walkdir("pg_wal", pre_sync_fname, false, DEBUG1);
2936  walkdir("pg_tblspc", pre_sync_fname, true, DEBUG1);
2937 #endif
2938 
2939  /*
2940  * Now we do the fsync()s in the same order.
2941  *
2942  * The main call ignores symlinks, so in addition to specially processing
2943  * pg_wal if it's a symlink, pg_tblspc has to be visited separately with
2944  * process_symlinks = true. Note that if there are any plain directories
2945  * in pg_tblspc, they'll get fsync'd twice. That's not an expected case
2946  * so we don't worry about optimizing it.
2947  */
2948  walkdir(".", datadir_fsync_fname, false, LOG);
2949  if (xlog_is_symlink)
2950  walkdir("pg_wal", datadir_fsync_fname, false, LOG);
2951  walkdir("pg_tblspc", datadir_fsync_fname, true, LOG);
2952 }
2953 
2954 /*
2955  * walkdir: recursively walk a directory, applying the action to each
2956  * regular file and directory (including the named directory itself).
2957  *
2958  * If process_symlinks is true, the action and recursion are also applied
2959  * to regular files and directories that are pointed to by symlinks in the
2960  * given directory; otherwise symlinks are ignored. Symlinks are always
2961  * ignored in subdirectories, ie we intentionally don't pass down the
2962  * process_symlinks flag to recursive calls.
2963  *
2964  * Errors are reported at level elevel, which might be ERROR or less.
2965  *
2966  * See also walkdir in initdb.c, which is a frontend version of this logic.
2967  */
2968 static void
2969 walkdir(const char *path,
2970  void (*action) (const char *fname, bool isdir, int elevel),
2971  bool process_symlinks,
2972  int elevel)
2973 {
2974  DIR *dir;
2975  struct dirent *de;
2976 
2977  dir = AllocateDir(path);
2978  if (dir == NULL)
2979  {
2980  ereport(elevel,
2982  errmsg("could not open directory \"%s\": %m", path)));
2983  return;
2984  }
2985 
2986  while ((de = ReadDirExtended(dir, path, elevel)) != NULL)
2987  {
2988  char subpath[MAXPGPATH];
2989  struct stat fst;
2990  int sret;
2991 
2993 
2994  if (strcmp(de->d_name, ".") == 0 ||
2995  strcmp(de->d_name, "..") == 0)
2996  continue;
2997 
2998  snprintf(subpath, MAXPGPATH, "%s/%s", path, de->d_name);
2999 
3000  if (process_symlinks)
3001  sret = stat(subpath, &fst);
3002  else
3003  sret = lstat(subpath, &fst);
3004 
3005  if (sret < 0)
3006  {
3007  ereport(elevel,
3009  errmsg("could not stat file \"%s\": %m", subpath)));
3010  continue;
3011  }
3012 
3013  if (S_ISREG(fst.st_mode))
3014  (*action) (subpath, false, elevel);
3015  else if (S_ISDIR(fst.st_mode))
3016  walkdir(subpath, action, false, elevel);
3017  }
3018 
3019  FreeDir(dir); /* we ignore any error here */
3020 
3021  /*
3022  * It's important to fsync the destination directory itself as individual
3023  * file fsyncs don't guarantee that the directory entry for the file is
3024  * synced.
3025  */
3026  (*action) (path, true, elevel);
3027 }
3028 
3029 
3030 /*
3031  * Hint to the OS that it should get ready to fsync() this file.
3032  *
3033  * Ignores errors trying to open unreadable files, and logs other errors at a
3034  * caller-specified level.
3035  */
3036 #ifdef PG_FLUSH_DATA_WORKS
3037 
3038 static void
3039 pre_sync_fname(const char *fname, bool isdir, int elevel)
3040 {
3041  int fd;
3042 
3043  /* Don't try to flush directories, it'll likely just fail */
3044  if (isdir)
3045  return;
3046 
3047  fd = OpenTransientFile((char *) fname, O_RDONLY | PG_BINARY, 0);
3048 
3049  if (fd < 0)
3050  {
3051  if (errno == EACCES)
3052  return;
3053  ereport(elevel,
3055  errmsg("could not open file \"%s\": %m", fname)));
3056  return;
3057  }
3058 
3059  /*
3060  * pg_flush_data() ignores errors, which is ok because this is only a
3061  * hint.
3062  */
3063  pg_flush_data(fd, 0, 0);
3064 
3065  (void) CloseTransientFile(fd);
3066 }
3067 
3068 #endif /* PG_FLUSH_DATA_WORKS */
3069 
3070 static void
3071 datadir_fsync_fname(const char *fname, bool isdir, int elevel)
3072 {
3073  /*
3074  * We want to silently ignoring errors about unreadable files. Pass that
3075  * desire on to fsync_fname_ext().
3076  */
3077  fsync_fname_ext(fname, isdir, true, elevel);
3078 }
3079 
3080 /*
3081  * fsync_fname_ext -- Try to fsync a file or directory
3082  *
3083  * If ignore_perm is true, ignore errors upon trying to open unreadable
3084  * files. Logs other errors at a caller-specified level.
3085  *
3086  * Returns 0 if the operation succeeded, -1 otherwise.
3087  */
3088 static int
3089 fsync_fname_ext(const char *fname, bool isdir, bool ignore_perm, int elevel)
3090 {
3091  int fd;
3092  int flags;
3093  int returncode;
3094 
3095  /*
3096  * Some OSs require directories to be opened read-only whereas other
3097  * systems don't allow us to fsync files opened read-only; so we need both
3098  * cases here. Using O_RDWR will cause us to fail to fsync files that are
3099  * not writable by our userid, but we assume that's OK.
3100  */
3101  flags = PG_BINARY;
3102  if (!isdir)
3103  flags |= O_RDWR;
3104  else
3105  flags |= O_RDONLY;
3106 
3107  fd = OpenTransientFile((char *) fname, flags, 0);
3108 
3109  /*
3110  * Some OSs don't allow us to open directories at all (Windows returns
3111  * EACCES), just ignore the error in that case. If desired also silently
3112  * ignoring errors about unreadable files. Log others.
3113  */
3114  if (fd < 0 && isdir && (errno == EISDIR || errno == EACCES))
3115  return 0;
3116  else if (fd < 0 && ignore_perm && errno == EACCES)
3117  return 0;
3118  else if (fd < 0)
3119  {
3120  ereport(elevel,
3122  errmsg("could not open file \"%s\": %m", fname)));
3123  return -1;
3124  }
3125 
3126  returncode = pg_fsync(fd);
3127 
3128  /*
3129  * Some OSes don't allow us to fsync directories at all, so we can ignore
3130  * those errors. Anything else needs to be logged.
3131  */
3132  if (returncode != 0 && !(isdir && errno == EBADF))
3133  {
3134  int save_errno;
3135 
3136  /* close file upon error, might not be in transaction context */
3137  save_errno = errno;
3138  (void) CloseTransientFile(fd);
3139  errno = save_errno;
3140 
3141  ereport(elevel,
3143  errmsg("could not fsync file \"%s\": %m", fname)));
3144  return -1;
3145  }
3146 
3147  (void) CloseTransientFile(fd);
3148 
3149  return 0;
3150 }
3151 
3152 /*
3153  * fsync_parent_path -- fsync the parent path of a file or directory
3154  *
3155  * This is aimed at making file operations persistent on disk in case of
3156  * an OS crash or power failure.
3157  */
3158 static int
3159 fsync_parent_path(const char *fname, int elevel)
3160 {
3161  char parentpath[MAXPGPATH];
3162 
3163  strlcpy(parentpath, fname, MAXPGPATH);
3164  get_parent_directory(parentpath);
3165 
3166  /*
3167  * get_parent_directory() returns an empty string if the input argument is
3168  * just a file name (see comments in path.c), so handle that as being the
3169  * current directory.
3170  */
3171  if (strlen(parentpath) == 0)
3172  strlcpy(parentpath, ".", MAXPGPATH);
3173 
3174  if (fsync_fname_ext(parentpath, true, false, elevel) != 0)
3175  return -1;
3176 
3177  return 0;
3178 }
File lruLessRecently
Definition: fd.c:183
void closeAllVfds(void)
Definition: fd.c:2462
File nextFree
Definition: fd.c:181
static void count_usable_fds(int max_to_probe, int *usable_fds, int *already_open)
Definition: fd.c:760
File PathNameOpenFile(FileName fileName, int fileFlags, int fileMode)
Definition: fd.c:1266
#define MAP_FAILED
Definition: mem.h:45
#define DEBUG1
Definition: elog.h:25
int MyProcPid
Definition: globals.c:38
#define NUM_RESERVED_FDS
Definition: fd.c:111
static AllocateDesc * allocatedDescs
Definition: fd.c:245
char * FileName
Definition: fd.h:49
int pg_fdatasync(int fd)
Definition: fd.c:385
static void error(void)
Definition: sql-dyntest.c:147
union AllocateDesc::@26 desc
#define SYNC_METHOD_FSYNC_WRITETHROUGH
Definition: xlog.h:28
AllocateDescKind
Definition: fd.c:223
DIR * dir
Definition: fd.c:238
static File OpenTemporaryFileInTablespace(Oid tblspcOid, bool rejectError)
Definition: fd.c:1390
static void AtProcExit_Files(int code, Datum arg)
Definition: fd.c:2594
#define write(a, b, c)
Definition: win32.h:19
static Size SizeVfdCache
Definition: fd.c:198
void on_proc_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:292
#define DO_DB(A)
Definition: fd.c:152
static void walkdir(const char *path, void(*action)(const char *fname, bool isdir, int elevel), bool process_symlinks, int elevel)
Definition: fd.c:2969
long random(void)
Definition: random.c:22
#define mkdir(a, b)
Definition: win32.h:65
ResourceOwner CurrentResourceOwner
Definition: resowner.c:138
int pg_fsync_writethrough(int fd)
Definition: fd.c:362
int forkname_chars(const char *str, ForkNumber *fork)
Definition: relpath.c:79
int max_safe_fds
Definition: fd.c:139
#define Min(x, y)
Definition: c.h:806
void fsync_fname(const char *fname, bool isdir)
Definition: fd.c:567
int log_temp_files
Definition: guc.c:457
#define GLOBALTABLESPACE_OID
Definition: pg_tablespace.h:64
static Vfd * VfdCache
Definition: fd.c:197
static void Delete(File file)
Definition: fd.c:947
int closedir(DIR *)
Definition: dirent.c:113
static int numTempTableSpaces
Definition: fd.c:258
int errcode(int sqlerrcode)
Definition: elog.c:575
#define MemSet(start, val, len)
Definition: c.h:857
return result
Definition: formatting.c:1618
int pg_fsync_no_writethrough(int fd)
Definition: fd.c:350
static void RemovePgTempRelationFilesInDbspace(const char *dbspacedirname)
Definition: fd.c:2797
int snprintf(char *str, size_t count, const char *fmt,...) pg_attribute_printf(3
#define PG_TEMP_FILE_PREFIX
Definition: fd.h:127
void pgstat_report_tempfile(size_t filesize)
Definition: pgstat.c:1467
static bool reserveAllocatedDesc(void)
Definition: fd.c:1984
uint32 SubTransactionId
Definition: c.h:401
#define LOG
Definition: elog.h:26
static void RemovePgTempFilesInDir(const char *tmpdirname)
Definition: fd.c:2715
unsigned int Oid
Definition: postgres_ext.h:31
#define FilePosIsUnknown(pos)
Definition: fd.c:170
AllocateDescKind kind
Definition: fd.c:233
char * FilePathName(File file)
Definition: fd.c:1937
Definition: dirent.h:9
#define OidIsValid(objectId)
Definition: c.h:538
static int fd(const char *x, int i)
Definition: preproc-init.c:105
#define PG_BINARY
Definition: c.h:1038
Oid MyDatabaseTableSpace
Definition: globals.c:78
int ClosePipeStream(FILE *file)
Definition: fd.c:2433
#define malloc(a)
Definition: header.h:50
static void LruDelete(File file)
Definition: fd.c:966
int fileMode
Definition: fd.c:189
void pg_usleep(long microsec)
Definition: signal.c:53
bool TempTablespacesAreSet(void)
Definition: fd.c:2516
static int FreeDesc(AllocateDesc *desc)
Definition: fd.c:2201
void pfree(void *pointer)
Definition: mcxt.c:950
static void RemovePgTempRelationFiles(const char *tsdirname)
Definition: fd.c:2756
static bool ReleaseLruFile(void)
Definition: fd.c:1103
Definition: dirent.c:25
#define ERROR
Definition: elog.h:43
static int LruInsert(File file)
Definition: fd.c:1029
void AtEOXact_Files(void)
Definition: fd.c:2580
#define FATAL
Definition: elog.h:52
static bool have_xact_temporary_files
Definition: fd.c:209
#define MAXPGPATH
DIR * opendir(const char *)
Definition: dirent.c:33
int FileSync(File file, uint32 wait_event_info)
Definition: fd.c:1793
#define DEBUG2
Definition: elog.h:24
char * fileName
Definition: fd.c:186
static struct dirent * ReadDirExtended(DIR *dir, const char *dirname, int elevel)
Definition: fd.c:2374
static char * buf
Definition: pg_test_fsync.c:65
Oid GetNextTempTableSpace(void)
Definition: fd.c:2528
void ResourceOwnerRememberFile(ResourceOwner owner, File file)
Definition: resowner.c:1200
static void CleanupTempFiles(bool isProcExit)
Definition: fd.c:2609
#define DEFAULTTABLESPACE_OID
Definition: pg_tablespace.h:63
int OpenTransientFile(FileName fileName, int fileFlags, int fileMode)
Definition: fd.c:2107
int errdetail(const char *fmt,...)
Definition: elog.c:873
int errcode_for_file_access(void)
Definition: elog.c:598
void get_parent_directory(char *path)
Definition: path.c:854
FILE * AllocateFile(const char *name, const char *mode)
Definition: fd.c:2057
static int nfile
Definition: fd.c:203
unsigned int uint32
Definition: c.h:268
void SyncDataDirectory(void)
Definition: fd.c:2896
DIR * AllocateDir(const char *dirname)
Definition: fd.c:2298
static int nextTempTableSpace
Definition: fd.c:259
int FileWrite(File file, char *buffer, int amount, uint32 wait_event_info)
Definition: fd.c:1672
static void pgstat_report_wait_end(void)
Definition: pgstat.h:1231
int max_files_per_process
Definition: fd.c:126
static File AllocateVfd(void)
Definition: fd.c:1135
FILE * OpenPipeStream(const char *command, const char *mode)
Definition: fd.c:2147
off_t seekPos
Definition: fd.c:184
unsigned short fdstate
Definition: fd.c:179
Definition: fd.c:176
off_t fileSize
Definition: fd.c:185
int fd
Definition: fd.c:178
int unlink(const char *filename)
#define ereport(elevel, rest)
Definition: elog.h:122
int FileRead(File file, char *buffer, int amount, uint32 wait_event_info)
Definition: fd.c:1608
int link(const char *fromname, const char *toname)
void SetTempTablespaces(Oid *tableSpaces, int numSpaces)
Definition: fd.c:2488
#define fsync(fd)
Definition: win32.h:70
int durable_rename(const char *oldfile, const char *newfile, int elevel)
Definition: fd.c:593
static void Insert(File file)
Definition: fd.c:1007
ResourceOwner resowner
Definition: fd.c:180
static void datadir_fsync_fname(const char *fname, bool isdir, int elevel)
Definition: fd.c:3071
int CloseTransientFile(int fd)
Definition: fd.c:2268
static void ReleaseLruFiles(void)
Definition: fd.c:1125
#define WARNING
Definition: elog.h:40
#define FileIsNotOpen(file)
Definition: fd.c:161
static int elevel
Definition: vacuumlazy.c:137
#define FD_TEMPORARY
Definition: fd.c:173
#define FD_XACT_TEMPORARY
Definition: fd.c:174
struct vfd Vfd
uintptr_t Datum
Definition: postgres.h:372
void AtEOSubXact_Files(bool isCommit, SubTransactionId mySubid, SubTransactionId parentSubid)
Definition: fd.c:2549
#define EINTR
Definition: win32.h:295
unsigned int Index
Definition: c.h:365
void pg_flush_data(int fd, off_t offset, off_t nbytes)
Definition: fd.c:407
#define FileIsValid(file)
Definition: fd.c:158
FILE * file
Definition: fd.c:237
static bool looks_like_temp_rel_name(const char *name)
Definition: fd.c:2829
#define InvalidOid
Definition: postgres_ext.h:36
#define VFD_CLOSED
Definition: fd.c:156
static uint64 temporary_files_size
Definition: fd.c:217
#define free(a)
Definition: header.h:65
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
#define ftruncate(a, b)
Definition: win32.h:67
#define PG_TEMP_FILES_DIR
Definition: fd.h:126
void FileClose(File file)
Definition: fd.c:1456
int FilePrefetch(File file, off_t offset, int amount, uint32 wait_event_info)
Definition: fd.c:1553
#define NULL
Definition: c.h:229
static int FileAccess(File file)
Definition: fd.c:1213
#define Assert(condition)
Definition: c.h:675
void _dosmaperr(unsigned long)
Definition: win32error.c:171
SubTransactionId GetCurrentSubTransactionId(void)
Definition: xact.c:649
struct dirent * ReadDir(DIR *dir, const char *dirname)
Definition: fd.c:2364
File lruMoreRecently
Definition: fd.c:182
void FileWriteback(File file, off_t offset, off_t nbytes, uint32 wait_event_info)
Definition: fd.c:1581
void RemovePgTempFiles(void)
Definition: fd.c:2669
SubTransactionId create_subid
Definition: fd.c:234
WalTimeSample buffer[LAG_TRACKER_BUFFER_SIZE]
Definition: walsender.c:207
File OpenTemporaryFile(bool interXact)
Definition: fd.c:1334
int durable_link_or_rename(const char *oldfile, const char *newfile, int elevel)
Definition: fd.c:675
size_t Size
Definition: c.h:356
static void pgstat_report_wait_start(uint32 wait_event_info)
Definition: pgstat.h:1207
int sync_method
Definition: xlog.c:103
struct dirent * readdir(DIR *)
Definition: dirent.c:78
#define FD_MINFREE
Definition: fd.c:117
#define TABLESPACE_VERSION_DIRECTORY
Definition: catalog.h:26
#define realloc(a, b)
Definition: header.h:60
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:963
#define INT64_FORMAT
Definition: c.h:315
const char * name
Definition: encode.c:521
static long tempFileCounter
Definition: fd.c:251
int fd
Definition: fd.c:239
int FreeFile(FILE *file)
Definition: fd.c:2240
void set_max_safe_fds(void)
Definition: fd.c:844
bool enableFsync
Definition: globals.c:110
static Oid * tempTableSpaces
Definition: fd.c:257
void * palloc(Size size)
Definition: mcxt.c:849
int errmsg(const char *fmt,...)
Definition: elog.c:797
int FileGetRawFlags(File file)
Definition: fd.c:1963
void ResourceOwnerEnlargeFiles(ResourceOwner owner)
Definition: resowner.c:1189
int FileGetRawMode(File file)
Definition: fd.c:1973
static int fsync_fname_ext(const char *fname, bool isdir, bool ignore_perm, int elevel)
Definition: fd.c:3089
int i
void * arg
int FileGetRawDesc(File file)
Definition: fd.c:1953
static void FreeVfd(File file)
Definition: fd.c:1193
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:97
int pg_fsync(int fd)
Definition: fd.c:333
char d_name[MAX_PATH]
Definition: dirent.h:14
#define elog
Definition: elog.h:219
#define close(a)
Definition: win32.h:17
int fileFlags
Definition: fd.c:188
off_t FileSeek(File file, off_t offset, int whence)
Definition: fd.c:1814
#define lstat(path, sb)
Definition: win32.h:272
void ResourceOwnerForgetFile(ResourceOwner owner, File file)
Definition: resowner.c:1209
int FileTruncate(File file, off_t offset, uint32 wait_event_info)
Definition: fd.c:1902
#define FileUnknownPos
Definition: fd.c:169
static int maxAllocatedDescs
Definition: fd.c:244
static int fsync_parent_path(const char *fname, int elevel)
Definition: fd.c:3159
int File
Definition: fd.h:51
#define read(a, b, c)
Definition: win32.h:18
int FreeDir(DIR *dir)
Definition: fd.c:2407
int temp_file_limit
Definition: guc.c:460
Datum subpath(PG_FUNCTION_ARGS)
Definition: ltree_op.c:234
void InitFileAccess(void)
Definition: fd.c:727
static int numAllocatedDescs
Definition: fd.c:243
int BasicOpenFile(FileName fileName, int fileFlags, int fileMode)
Definition: fd.c:899