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)
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  returnCode = posix_fadvise(VfdCache[file].fd, offset, amount,
1569  POSIX_FADV_WILLNEED);
1570 
1571  return returnCode;
1572 #else
1573  Assert(FileIsValid(file));
1574  return 0;
1575 #endif
1576 }
1577 
1578 void
1579 FileWriteback(File file, off_t offset, off_t nbytes)
1580 {
1581  int returnCode;
1582 
1583  Assert(FileIsValid(file));
1584 
1585  DO_DB(elog(LOG, "FileWriteback: %d (%s) " INT64_FORMAT " " INT64_FORMAT,
1586  file, VfdCache[file].fileName,
1587  (int64) offset, (int64) nbytes));
1588 
1589  /*
1590  * Caution: do not call pg_flush_data with nbytes = 0, it could trash the
1591  * file's seek position. We prefer to define that as a no-op here.
1592  */
1593  if (nbytes <= 0)
1594  return;
1595 
1596  returnCode = FileAccess(file);
1597  if (returnCode < 0)
1598  return;
1599 
1600  pg_flush_data(VfdCache[file].fd, offset, nbytes);
1601 }
1602 
1603 int
1604 FileRead(File file, char *buffer, int amount)
1605 {
1606  int returnCode;
1607  Vfd *vfdP;
1608 
1609  Assert(FileIsValid(file));
1610 
1611  DO_DB(elog(LOG, "FileRead: %d (%s) " INT64_FORMAT " %d %p",
1612  file, VfdCache[file].fileName,
1613  (int64) VfdCache[file].seekPos,
1614  amount, buffer));
1615 
1616  returnCode = FileAccess(file);
1617  if (returnCode < 0)
1618  return returnCode;
1619 
1620  vfdP = &VfdCache[file];
1621 
1622 retry:
1623  returnCode = read(vfdP->fd, buffer, amount);
1624 
1625  if (returnCode >= 0)
1626  {
1627  /* if seekPos is unknown, leave it that way */
1628  if (!FilePosIsUnknown(vfdP->seekPos))
1629  vfdP->seekPos += returnCode;
1630  }
1631  else
1632  {
1633  /*
1634  * Windows may run out of kernel buffers and return "Insufficient
1635  * system resources" error. Wait a bit and retry to solve it.
1636  *
1637  * It is rumored that EINTR is also possible on some Unix filesystems,
1638  * in which case immediate retry is indicated.
1639  */
1640 #ifdef WIN32
1641  DWORD error = GetLastError();
1642 
1643  switch (error)
1644  {
1645  case ERROR_NO_SYSTEM_RESOURCES:
1646  pg_usleep(1000L);
1647  errno = EINTR;
1648  break;
1649  default:
1650  _dosmaperr(error);
1651  break;
1652  }
1653 #endif
1654  /* OK to retry if interrupted */
1655  if (errno == EINTR)
1656  goto retry;
1657 
1658  /* Trouble, so assume we don't know the file position anymore */
1659  vfdP->seekPos = FileUnknownPos;
1660  }
1661 
1662  return returnCode;
1663 }
1664 
1665 int
1666 FileWrite(File file, char *buffer, int amount)
1667 {
1668  int returnCode;
1669  Vfd *vfdP;
1670 
1671  Assert(FileIsValid(file));
1672 
1673  DO_DB(elog(LOG, "FileWrite: %d (%s) " INT64_FORMAT " %d %p",
1674  file, VfdCache[file].fileName,
1675  (int64) VfdCache[file].seekPos,
1676  amount, buffer));
1677 
1678  returnCode = FileAccess(file);
1679  if (returnCode < 0)
1680  return returnCode;
1681 
1682  vfdP = &VfdCache[file];
1683 
1684  /*
1685  * If enforcing temp_file_limit and it's a temp file, check to see if the
1686  * write would overrun temp_file_limit, and throw error if so. Note: it's
1687  * really a modularity violation to throw error here; we should set errno
1688  * and return -1. However, there's no way to report a suitable error
1689  * message if we do that. All current callers would just throw error
1690  * immediately anyway, so this is safe at present.
1691  */
1692  if (temp_file_limit >= 0 && (vfdP->fdstate & FD_TEMPORARY))
1693  {
1694  off_t newPos;
1695 
1696  /*
1697  * Normally we should know the seek position, but if for some reason
1698  * we have lost track of it, try again to get it. Here, it's fine to
1699  * throw an error if we still can't get it.
1700  */
1701  if (FilePosIsUnknown(vfdP->seekPos))
1702  {
1703  vfdP->seekPos = lseek(vfdP->fd, (off_t) 0, SEEK_CUR);
1704  if (FilePosIsUnknown(vfdP->seekPos))
1705  elog(ERROR, "could not seek file \"%s\": %m", vfdP->fileName);
1706  }
1707 
1708  newPos = vfdP->seekPos + amount;
1709  if (newPos > vfdP->fileSize)
1710  {
1711  uint64 newTotal = temporary_files_size;
1712 
1713  newTotal += newPos - vfdP->fileSize;
1714  if (newTotal > (uint64) temp_file_limit * (uint64) 1024)
1715  ereport(ERROR,
1716  (errcode(ERRCODE_CONFIGURATION_LIMIT_EXCEEDED),
1717  errmsg("temporary file size exceeds temp_file_limit (%dkB)",
1718  temp_file_limit)));
1719  }
1720  }
1721 
1722 retry:
1723  errno = 0;
1724  returnCode = write(vfdP->fd, buffer, amount);
1725 
1726  /* if write didn't set errno, assume problem is no disk space */
1727  if (returnCode != amount && errno == 0)
1728  errno = ENOSPC;
1729 
1730  if (returnCode >= 0)
1731  {
1732  /* if seekPos is unknown, leave it that way */
1733  if (!FilePosIsUnknown(vfdP->seekPos))
1734  vfdP->seekPos += returnCode;
1735 
1736  /*
1737  * Maintain fileSize and temporary_files_size if it's a temp file.
1738  *
1739  * If seekPos is -1 (unknown), this will do nothing; but we could only
1740  * get here in that state if we're not enforcing temporary_files_size,
1741  * so we don't care.
1742  */
1743  if (vfdP->fdstate & FD_TEMPORARY)
1744  {
1745  off_t newPos = vfdP->seekPos;
1746 
1747  if (newPos > vfdP->fileSize)
1748  {
1749  temporary_files_size += newPos - vfdP->fileSize;
1750  vfdP->fileSize = newPos;
1751  }
1752  }
1753  }
1754  else
1755  {
1756  /*
1757  * See comments in FileRead()
1758  */
1759 #ifdef WIN32
1760  DWORD error = GetLastError();
1761 
1762  switch (error)
1763  {
1764  case ERROR_NO_SYSTEM_RESOURCES:
1765  pg_usleep(1000L);
1766  errno = EINTR;
1767  break;
1768  default:
1769  _dosmaperr(error);
1770  break;
1771  }
1772 #endif
1773  /* OK to retry if interrupted */
1774  if (errno == EINTR)
1775  goto retry;
1776 
1777  /* Trouble, so assume we don't know the file position anymore */
1778  vfdP->seekPos = FileUnknownPos;
1779  }
1780 
1781  return returnCode;
1782 }
1783 
1784 int
1786 {
1787  int returnCode;
1788 
1789  Assert(FileIsValid(file));
1790 
1791  DO_DB(elog(LOG, "FileSync: %d (%s)",
1792  file, VfdCache[file].fileName));
1793 
1794  returnCode = FileAccess(file);
1795  if (returnCode < 0)
1796  return returnCode;
1797 
1798  return pg_fsync(VfdCache[file].fd);
1799 }
1800 
1801 off_t
1802 FileSeek(File file, off_t offset, int whence)
1803 {
1804  Vfd *vfdP;
1805 
1806  Assert(FileIsValid(file));
1807 
1808  DO_DB(elog(LOG, "FileSeek: %d (%s) " INT64_FORMAT " " INT64_FORMAT " %d",
1809  file, VfdCache[file].fileName,
1810  (int64) VfdCache[file].seekPos,
1811  (int64) offset, whence));
1812 
1813  vfdP = &VfdCache[file];
1814 
1815  if (FileIsNotOpen(file))
1816  {
1817  switch (whence)
1818  {
1819  case SEEK_SET:
1820  if (offset < 0)
1821  {
1822  errno = EINVAL;
1823  return (off_t) -1;
1824  }
1825  vfdP->seekPos = offset;
1826  break;
1827  case SEEK_CUR:
1828  if (FilePosIsUnknown(vfdP->seekPos) ||
1829  vfdP->seekPos + offset < 0)
1830  {
1831  errno = EINVAL;
1832  return (off_t) -1;
1833  }
1834  vfdP->seekPos += offset;
1835  break;
1836  case SEEK_END:
1837  if (FileAccess(file) < 0)
1838  return (off_t) -1;
1839  vfdP->seekPos = lseek(vfdP->fd, offset, whence);
1840  break;
1841  default:
1842  elog(ERROR, "invalid whence: %d", whence);
1843  break;
1844  }
1845  }
1846  else
1847  {
1848  switch (whence)
1849  {
1850  case SEEK_SET:
1851  if (offset < 0)
1852  {
1853  errno = EINVAL;
1854  return (off_t) -1;
1855  }
1856  if (vfdP->seekPos != offset)
1857  vfdP->seekPos = lseek(vfdP->fd, offset, whence);
1858  break;
1859  case SEEK_CUR:
1860  if (offset != 0 || FilePosIsUnknown(vfdP->seekPos))
1861  vfdP->seekPos = lseek(vfdP->fd, offset, whence);
1862  break;
1863  case SEEK_END:
1864  vfdP->seekPos = lseek(vfdP->fd, offset, whence);
1865  break;
1866  default:
1867  elog(ERROR, "invalid whence: %d", whence);
1868  break;
1869  }
1870  }
1871 
1872  return vfdP->seekPos;
1873 }
1874 
1875 /*
1876  * XXX not actually used but here for completeness
1877  */
1878 #ifdef NOT_USED
1879 off_t
1880 FileTell(File file)
1881 {
1882  Assert(FileIsValid(file));
1883  DO_DB(elog(LOG, "FileTell %d (%s)",
1884  file, VfdCache[file].fileName));
1885  return VfdCache[file].seekPos;
1886 }
1887 #endif
1888 
1889 int
1890 FileTruncate(File file, off_t offset)
1891 {
1892  int returnCode;
1893 
1894  Assert(FileIsValid(file));
1895 
1896  DO_DB(elog(LOG, "FileTruncate %d (%s)",
1897  file, VfdCache[file].fileName));
1898 
1899  returnCode = FileAccess(file);
1900  if (returnCode < 0)
1901  return returnCode;
1902 
1903  returnCode = ftruncate(VfdCache[file].fd, offset);
1904 
1905  if (returnCode == 0 && VfdCache[file].fileSize > offset)
1906  {
1907  /* adjust our state for truncation of a temp file */
1908  Assert(VfdCache[file].fdstate & FD_TEMPORARY);
1909  temporary_files_size -= VfdCache[file].fileSize - offset;
1910  VfdCache[file].fileSize = offset;
1911  }
1912 
1913  return returnCode;
1914 }
1915 
1916 /*
1917  * Return the pathname associated with an open file.
1918  *
1919  * The returned string points to an internal buffer, which is valid until
1920  * the file is closed.
1921  */
1922 char *
1924 {
1925  Assert(FileIsValid(file));
1926 
1927  return VfdCache[file].fileName;
1928 }
1929 
1930 /*
1931  * Return the raw file descriptor of an opened file.
1932  *
1933  * The returned file descriptor will be valid until the file is closed, but
1934  * there are a lot of things that can make that happen. So the caller should
1935  * be careful not to do much of anything else before it finishes using the
1936  * returned file descriptor.
1937  */
1938 int
1940 {
1941  Assert(FileIsValid(file));
1942  return VfdCache[file].fd;
1943 }
1944 
1945 /*
1946  * FileGetRawFlags - returns the file flags on open(2)
1947  */
1948 int
1950 {
1951  Assert(FileIsValid(file));
1952  return VfdCache[file].fileFlags;
1953 }
1954 
1955 /*
1956  * FileGetRawMode - returns the mode bitmask passed to open(2)
1957  */
1958 int
1960 {
1961  Assert(FileIsValid(file));
1962  return VfdCache[file].fileMode;
1963 }
1964 
1965 /*
1966  * Make room for another allocatedDescs[] array entry if needed and possible.
1967  * Returns true if an array element is available.
1968  */
1969 static bool
1971 {
1972  AllocateDesc *newDescs;
1973  int newMax;
1974 
1975  /* Quick out if array already has a free slot. */
1977  return true;
1978 
1979  /*
1980  * If the array hasn't yet been created in the current process, initialize
1981  * it with FD_MINFREE / 2 elements. In many scenarios this is as many as
1982  * we will ever need, anyway. We don't want to look at max_safe_fds
1983  * immediately because set_max_safe_fds() may not have run yet.
1984  */
1985  if (allocatedDescs == NULL)
1986  {
1987  newMax = FD_MINFREE / 2;
1988  newDescs = (AllocateDesc *) malloc(newMax * sizeof(AllocateDesc));
1989  /* Out of memory already? Treat as fatal error. */
1990  if (newDescs == NULL)
1991  ereport(ERROR,
1992  (errcode(ERRCODE_OUT_OF_MEMORY),
1993  errmsg("out of memory")));
1994  allocatedDescs = newDescs;
1995  maxAllocatedDescs = newMax;
1996  return true;
1997  }
1998 
1999  /*
2000  * Consider enlarging the array beyond the initial allocation used above.
2001  * By the time this happens, max_safe_fds should be known accurately.
2002  *
2003  * We mustn't let allocated descriptors hog all the available FDs, and in
2004  * practice we'd better leave a reasonable number of FDs for VFD use. So
2005  * set the maximum to max_safe_fds / 2. (This should certainly be at
2006  * least as large as the initial size, FD_MINFREE / 2.)
2007  */
2008  newMax = max_safe_fds / 2;
2009  if (newMax > maxAllocatedDescs)
2010  {
2011  newDescs = (AllocateDesc *) realloc(allocatedDescs,
2012  newMax * sizeof(AllocateDesc));
2013  /* Treat out-of-memory as a non-fatal error. */
2014  if (newDescs == NULL)
2015  return false;
2016  allocatedDescs = newDescs;
2017  maxAllocatedDescs = newMax;
2018  return true;
2019  }
2020 
2021  /* Can't enlarge allocatedDescs[] any more. */
2022  return false;
2023 }
2024 
2025 /*
2026  * Routines that want to use stdio (ie, FILE*) should use AllocateFile
2027  * rather than plain fopen(). This lets fd.c deal with freeing FDs if
2028  * necessary to open the file. When done, call FreeFile rather than fclose.
2029  *
2030  * Note that files that will be open for any significant length of time
2031  * should NOT be handled this way, since they cannot share kernel file
2032  * descriptors with other files; there is grave risk of running out of FDs
2033  * if anyone locks down too many FDs. Most callers of this routine are
2034  * simply reading a config file that they will read and close immediately.
2035  *
2036  * fd.c will automatically close all files opened with AllocateFile at
2037  * transaction commit or abort; this prevents FD leakage if a routine
2038  * that calls AllocateFile is terminated prematurely by ereport(ERROR).
2039  *
2040  * Ideally this should be the *only* direct call of fopen() in the backend.
2041  */
2042 FILE *
2043 AllocateFile(const char *name, const char *mode)
2044 {
2045  FILE *file;
2046 
2047  DO_DB(elog(LOG, "AllocateFile: Allocated %d (%s)",
2048  numAllocatedDescs, name));
2049 
2050  /* Can we allocate another non-virtual FD? */
2051  if (!reserveAllocatedDesc())
2052  ereport(ERROR,
2053  (errcode(ERRCODE_INSUFFICIENT_RESOURCES),
2054  errmsg("exceeded maxAllocatedDescs (%d) while trying to open file \"%s\"",
2055  maxAllocatedDescs, name)));
2056 
2057  /* Close excess kernel FDs. */
2058  ReleaseLruFiles();
2059 
2060 TryAgain:
2061  if ((file = fopen(name, mode)) != NULL)
2062  {
2063  AllocateDesc *desc = &allocatedDescs[numAllocatedDescs];
2064 
2065  desc->kind = AllocateDescFile;
2066  desc->desc.file = file;
2069  return desc->desc.file;
2070  }
2071 
2072  if (errno == EMFILE || errno == ENFILE)
2073  {
2074  int save_errno = errno;
2075 
2076  ereport(LOG,
2077  (errcode(ERRCODE_INSUFFICIENT_RESOURCES),
2078  errmsg("out of file descriptors: %m; release and retry")));
2079  errno = 0;
2080  if (ReleaseLruFile())
2081  goto TryAgain;
2082  errno = save_errno;
2083  }
2084 
2085  return NULL;
2086 }
2087 
2088 
2089 /*
2090  * Like AllocateFile, but returns an unbuffered fd like open(2)
2091  */
2092 int
2093 OpenTransientFile(FileName fileName, int fileFlags, int fileMode)
2094 {
2095  int fd;
2096 
2097  DO_DB(elog(LOG, "OpenTransientFile: Allocated %d (%s)",
2098  numAllocatedDescs, fileName));
2099 
2100  /* Can we allocate another non-virtual FD? */
2101  if (!reserveAllocatedDesc())
2102  ereport(ERROR,
2103  (errcode(ERRCODE_INSUFFICIENT_RESOURCES),
2104  errmsg("exceeded maxAllocatedDescs (%d) while trying to open file \"%s\"",
2105  maxAllocatedDescs, fileName)));
2106 
2107  /* Close excess kernel FDs. */
2108  ReleaseLruFiles();
2109 
2110  fd = BasicOpenFile(fileName, fileFlags, fileMode);
2111 
2112  if (fd >= 0)
2113  {
2114  AllocateDesc *desc = &allocatedDescs[numAllocatedDescs];
2115 
2116  desc->kind = AllocateDescRawFD;
2117  desc->desc.fd = fd;
2120 
2121  return fd;
2122  }
2123 
2124  return -1; /* failure */
2125 }
2126 
2127 /*
2128  * Routines that want to initiate a pipe stream should use OpenPipeStream
2129  * rather than plain popen(). This lets fd.c deal with freeing FDs if
2130  * necessary. When done, call ClosePipeStream rather than pclose.
2131  */
2132 FILE *
2133 OpenPipeStream(const char *command, const char *mode)
2134 {
2135  FILE *file;
2136 
2137  DO_DB(elog(LOG, "OpenPipeStream: Allocated %d (%s)",
2138  numAllocatedDescs, command));
2139 
2140  /* Can we allocate another non-virtual FD? */
2141  if (!reserveAllocatedDesc())
2142  ereport(ERROR,
2143  (errcode(ERRCODE_INSUFFICIENT_RESOURCES),
2144  errmsg("exceeded maxAllocatedDescs (%d) while trying to execute command \"%s\"",
2145  maxAllocatedDescs, command)));
2146 
2147  /* Close excess kernel FDs. */
2148  ReleaseLruFiles();
2149 
2150 TryAgain:
2151  fflush(stdout);
2152  fflush(stderr);
2153  errno = 0;
2154  if ((file = popen(command, mode)) != NULL)
2155  {
2156  AllocateDesc *desc = &allocatedDescs[numAllocatedDescs];
2157 
2158  desc->kind = AllocateDescPipe;
2159  desc->desc.file = file;
2162  return desc->desc.file;
2163  }
2164 
2165  if (errno == EMFILE || errno == ENFILE)
2166  {
2167  int save_errno = errno;
2168 
2169  ereport(LOG,
2170  (errcode(ERRCODE_INSUFFICIENT_RESOURCES),
2171  errmsg("out of file descriptors: %m; release and retry")));
2172  errno = 0;
2173  if (ReleaseLruFile())
2174  goto TryAgain;
2175  errno = save_errno;
2176  }
2177 
2178  return NULL;
2179 }
2180 
2181 /*
2182  * Free an AllocateDesc of any type.
2183  *
2184  * The argument *must* point into the allocatedDescs[] array.
2185  */
2186 static int
2188 {
2189  int result;
2190 
2191  /* Close the underlying object */
2192  switch (desc->kind)
2193  {
2194  case AllocateDescFile:
2195  result = fclose(desc->desc.file);
2196  break;
2197  case AllocateDescPipe:
2198  result = pclose(desc->desc.file);
2199  break;
2200  case AllocateDescDir:
2201  result = closedir(desc->desc.dir);
2202  break;
2203  case AllocateDescRawFD:
2204  result = close(desc->desc.fd);
2205  break;
2206  default:
2207  elog(ERROR, "AllocateDesc kind not recognized");
2208  result = 0; /* keep compiler quiet */
2209  break;
2210  }
2211 
2212  /* Compact storage in the allocatedDescs array */
2214  *desc = allocatedDescs[numAllocatedDescs];
2215 
2216  return result;
2217 }
2218 
2219 /*
2220  * Close a file returned by AllocateFile.
2221  *
2222  * Note we do not check fclose's return value --- it is up to the caller
2223  * to handle close errors.
2224  */
2225 int
2226 FreeFile(FILE *file)
2227 {
2228  int i;
2229 
2230  DO_DB(elog(LOG, "FreeFile: Allocated %d", numAllocatedDescs));
2231 
2232  /* Remove file from list of allocated files, if it's present */
2233  for (i = numAllocatedDescs; --i >= 0;)
2234  {
2235  AllocateDesc *desc = &allocatedDescs[i];
2236 
2237  if (desc->kind == AllocateDescFile && desc->desc.file == file)
2238  return FreeDesc(desc);
2239  }
2240 
2241  /* Only get here if someone passes us a file not in allocatedDescs */
2242  elog(WARNING, "file passed to FreeFile was not obtained from AllocateFile");
2243 
2244  return fclose(file);
2245 }
2246 
2247 /*
2248  * Close a file returned by OpenTransientFile.
2249  *
2250  * Note we do not check close's return value --- it is up to the caller
2251  * to handle close errors.
2252  */
2253 int
2255 {
2256  int i;
2257 
2258  DO_DB(elog(LOG, "CloseTransientFile: Allocated %d", numAllocatedDescs));
2259 
2260  /* Remove fd from list of allocated files, if it's present */
2261  for (i = numAllocatedDescs; --i >= 0;)
2262  {
2263  AllocateDesc *desc = &allocatedDescs[i];
2264 
2265  if (desc->kind == AllocateDescRawFD && desc->desc.fd == fd)
2266  return FreeDesc(desc);
2267  }
2268 
2269  /* Only get here if someone passes us a file not in allocatedDescs */
2270  elog(WARNING, "fd passed to CloseTransientFile was not obtained from OpenTransientFile");
2271 
2272  return close(fd);
2273 }
2274 
2275 /*
2276  * Routines that want to use <dirent.h> (ie, DIR*) should use AllocateDir
2277  * rather than plain opendir(). This lets fd.c deal with freeing FDs if
2278  * necessary to open the directory, and with closing it after an elog.
2279  * When done, call FreeDir rather than closedir.
2280  *
2281  * Ideally this should be the *only* direct call of opendir() in the backend.
2282  */
2283 DIR *
2284 AllocateDir(const char *dirname)
2285 {
2286  DIR *dir;
2287 
2288  DO_DB(elog(LOG, "AllocateDir: Allocated %d (%s)",
2289  numAllocatedDescs, dirname));
2290 
2291  /* Can we allocate another non-virtual FD? */
2292  if (!reserveAllocatedDesc())
2293  ereport(ERROR,
2294  (errcode(ERRCODE_INSUFFICIENT_RESOURCES),
2295  errmsg("exceeded maxAllocatedDescs (%d) while trying to open directory \"%s\"",
2296  maxAllocatedDescs, dirname)));
2297 
2298  /* Close excess kernel FDs. */
2299  ReleaseLruFiles();
2300 
2301 TryAgain:
2302  if ((dir = opendir(dirname)) != NULL)
2303  {
2304  AllocateDesc *desc = &allocatedDescs[numAllocatedDescs];
2305 
2306  desc->kind = AllocateDescDir;
2307  desc->desc.dir = dir;
2310  return desc->desc.dir;
2311  }
2312 
2313  if (errno == EMFILE || errno == ENFILE)
2314  {
2315  int save_errno = errno;
2316 
2317  ereport(LOG,
2318  (errcode(ERRCODE_INSUFFICIENT_RESOURCES),
2319  errmsg("out of file descriptors: %m; release and retry")));
2320  errno = 0;
2321  if (ReleaseLruFile())
2322  goto TryAgain;
2323  errno = save_errno;
2324  }
2325 
2326  return NULL;
2327 }
2328 
2329 /*
2330  * Read a directory opened with AllocateDir, ereport'ing any error.
2331  *
2332  * This is easier to use than raw readdir() since it takes care of some
2333  * otherwise rather tedious and error-prone manipulation of errno. Also,
2334  * if you are happy with a generic error message for AllocateDir failure,
2335  * you can just do
2336  *
2337  * dir = AllocateDir(path);
2338  * while ((dirent = ReadDir(dir, path)) != NULL)
2339  * process dirent;
2340  * FreeDir(dir);
2341  *
2342  * since a NULL dir parameter is taken as indicating AllocateDir failed.
2343  * (Make sure errno hasn't been changed since AllocateDir if you use this
2344  * shortcut.)
2345  *
2346  * The pathname passed to AllocateDir must be passed to this routine too,
2347  * but it is only used for error reporting.
2348  */
2349 struct dirent *
2350 ReadDir(DIR *dir, const char *dirname)
2351 {
2352  return ReadDirExtended(dir, dirname, ERROR);
2353 }
2354 
2355 /*
2356  * Alternate version that allows caller to specify the elevel for any
2357  * error report. If elevel < ERROR, returns NULL on any error.
2358  */
2359 static struct dirent *
2360 ReadDirExtended(DIR *dir, const char *dirname, int elevel)
2361 {
2362  struct dirent *dent;
2363 
2364  /* Give a generic message for AllocateDir failure, if caller didn't */
2365  if (dir == NULL)
2366  {
2367  ereport(elevel,
2369  errmsg("could not open directory \"%s\": %m",
2370  dirname)));
2371  return NULL;
2372  }
2373 
2374  errno = 0;
2375  if ((dent = readdir(dir)) != NULL)
2376  return dent;
2377 
2378  if (errno)
2379  ereport(elevel,
2381  errmsg("could not read directory \"%s\": %m",
2382  dirname)));
2383  return NULL;
2384 }
2385 
2386 /*
2387  * Close a directory opened with AllocateDir.
2388  *
2389  * Note we do not check closedir's return value --- it is up to the caller
2390  * to handle close errors.
2391  */
2392 int
2394 {
2395  int i;
2396 
2397  DO_DB(elog(LOG, "FreeDir: Allocated %d", numAllocatedDescs));
2398 
2399  /* Remove dir from list of allocated dirs, if it's present */
2400  for (i = numAllocatedDescs; --i >= 0;)
2401  {
2402  AllocateDesc *desc = &allocatedDescs[i];
2403 
2404  if (desc->kind == AllocateDescDir && desc->desc.dir == dir)
2405  return FreeDesc(desc);
2406  }
2407 
2408  /* Only get here if someone passes us a dir not in allocatedDescs */
2409  elog(WARNING, "dir passed to FreeDir was not obtained from AllocateDir");
2410 
2411  return closedir(dir);
2412 }
2413 
2414 
2415 /*
2416  * Close a pipe stream returned by OpenPipeStream.
2417  */
2418 int
2419 ClosePipeStream(FILE *file)
2420 {
2421  int i;
2422 
2423  DO_DB(elog(LOG, "ClosePipeStream: Allocated %d", numAllocatedDescs));
2424 
2425  /* Remove file from list of allocated files, if it's present */
2426  for (i = numAllocatedDescs; --i >= 0;)
2427  {
2428  AllocateDesc *desc = &allocatedDescs[i];
2429 
2430  if (desc->kind == AllocateDescPipe && desc->desc.file == file)
2431  return FreeDesc(desc);
2432  }
2433 
2434  /* Only get here if someone passes us a file not in allocatedDescs */
2435  elog(WARNING, "file passed to ClosePipeStream was not obtained from OpenPipeStream");
2436 
2437  return pclose(file);
2438 }
2439 
2440 /*
2441  * closeAllVfds
2442  *
2443  * Force all VFDs into the physically-closed state, so that the fewest
2444  * possible number of kernel file descriptors are in use. There is no
2445  * change in the logical state of the VFDs.
2446  */
2447 void
2449 {
2450  Index i;
2451 
2452  if (SizeVfdCache > 0)
2453  {
2454  Assert(FileIsNotOpen(0)); /* Make sure ring not corrupted */
2455  for (i = 1; i < SizeVfdCache; i++)
2456  {
2457  if (!FileIsNotOpen(i))
2458  LruDelete(i);
2459  }
2460  }
2461 }
2462 
2463 
2464 /*
2465  * SetTempTablespaces
2466  *
2467  * Define a list (actually an array) of OIDs of tablespaces to use for
2468  * temporary files. This list will be used until end of transaction,
2469  * unless this function is called again before then. It is caller's
2470  * responsibility that the passed-in array has adequate lifespan (typically
2471  * it'd be allocated in TopTransactionContext).
2472  */
2473 void
2474 SetTempTablespaces(Oid *tableSpaces, int numSpaces)
2475 {
2476  Assert(numSpaces >= 0);
2477  tempTableSpaces = tableSpaces;
2478  numTempTableSpaces = numSpaces;
2479 
2480  /*
2481  * Select a random starting point in the list. This is to minimize
2482  * conflicts between backends that are most likely sharing the same list
2483  * of temp tablespaces. Note that if we create multiple temp files in the
2484  * same transaction, we'll advance circularly through the list --- this
2485  * ensures that large temporary sort files are nicely spread across all
2486  * available tablespaces.
2487  */
2488  if (numSpaces > 1)
2489  nextTempTableSpace = random() % numSpaces;
2490  else
2491  nextTempTableSpace = 0;
2492 }
2493 
2494 /*
2495  * TempTablespacesAreSet
2496  *
2497  * Returns TRUE if SetTempTablespaces has been called in current transaction.
2498  * (This is just so that tablespaces.c doesn't need its own per-transaction
2499  * state.)
2500  */
2501 bool
2503 {
2504  return (numTempTableSpaces >= 0);
2505 }
2506 
2507 /*
2508  * GetNextTempTableSpace
2509  *
2510  * Select the next temp tablespace to use. A result of InvalidOid means
2511  * to use the current database's default tablespace.
2512  */
2513 Oid
2515 {
2516  if (numTempTableSpaces > 0)
2517  {
2518  /* Advance nextTempTableSpace counter with wraparound */
2520  nextTempTableSpace = 0;
2522  }
2523  return InvalidOid;
2524 }
2525 
2526 
2527 /*
2528  * AtEOSubXact_Files
2529  *
2530  * Take care of subtransaction commit/abort. At abort, we close temp files
2531  * that the subtransaction may have opened. At commit, we reassign the
2532  * files that were opened to the parent subtransaction.
2533  */
2534 void
2535 AtEOSubXact_Files(bool isCommit, SubTransactionId mySubid,
2536  SubTransactionId parentSubid)
2537 {
2538  Index i;
2539 
2540  for (i = 0; i < numAllocatedDescs; i++)
2541  {
2542  if (allocatedDescs[i].create_subid == mySubid)
2543  {
2544  if (isCommit)
2545  allocatedDescs[i].create_subid = parentSubid;
2546  else
2547  {
2548  /* have to recheck the item after FreeDesc (ugly) */
2549  FreeDesc(&allocatedDescs[i--]);
2550  }
2551  }
2552  }
2553 }
2554 
2555 /*
2556  * AtEOXact_Files
2557  *
2558  * This routine is called during transaction commit or abort (it doesn't
2559  * particularly care which). All still-open per-transaction temporary file
2560  * VFDs are closed, which also causes the underlying files to be deleted
2561  * (although they should've been closed already by the ResourceOwner
2562  * cleanup). Furthermore, all "allocated" stdio files are closed. We also
2563  * forget any transaction-local temp tablespace list.
2564  */
2565 void
2567 {
2568  CleanupTempFiles(false);
2570  numTempTableSpaces = -1;
2571 }
2572 
2573 /*
2574  * AtProcExit_Files
2575  *
2576  * on_proc_exit hook to clean up temp files during backend shutdown.
2577  * Here, we want to clean up *all* temp files including interXact ones.
2578  */
2579 static void
2581 {
2582  CleanupTempFiles(true);
2583 }
2584 
2585 /*
2586  * Close temporary files and delete their underlying files.
2587  *
2588  * isProcExit: if true, this is being called as the backend process is
2589  * exiting. If that's the case, we should remove all temporary files; if
2590  * that's not the case, we are being called for transaction commit/abort
2591  * and should only remove transaction-local temp files. In either case,
2592  * also clean up "allocated" stdio files, dirs and fds.
2593  */
2594 static void
2595 CleanupTempFiles(bool isProcExit)
2596 {
2597  Index i;
2598 
2599  /*
2600  * Careful here: at proc_exit we need extra cleanup, not just
2601  * xact_temporary files.
2602  */
2603  if (isProcExit || have_xact_temporary_files)
2604  {
2605  Assert(FileIsNotOpen(0)); /* Make sure ring not corrupted */
2606  for (i = 1; i < SizeVfdCache; i++)
2607  {
2608  unsigned short fdstate = VfdCache[i].fdstate;
2609 
2610  if ((fdstate & FD_TEMPORARY) && VfdCache[i].fileName != NULL)
2611  {
2612  /*
2613  * If we're in the process of exiting a backend process, close
2614  * all temporary files. Otherwise, only close temporary files
2615  * local to the current transaction. They should be closed by
2616  * the ResourceOwner mechanism already, so this is just a
2617  * debugging cross-check.
2618  */
2619  if (isProcExit)
2620  FileClose(i);
2621  else if (fdstate & FD_XACT_TEMPORARY)
2622  {
2623  elog(WARNING,
2624  "temporary file %s not closed at end-of-transaction",
2625  VfdCache[i].fileName);
2626  FileClose(i);
2627  }
2628  }
2629  }
2630 
2631  have_xact_temporary_files = false;
2632  }
2633 
2634  /* Clean up "allocated" stdio files, dirs and fds. */
2635  while (numAllocatedDescs > 0)
2636  FreeDesc(&allocatedDescs[0]);
2637 }
2638 
2639 
2640 /*
2641  * Remove temporary and temporary relation files left over from a prior
2642  * postmaster session
2643  *
2644  * This should be called during postmaster startup. It will forcibly
2645  * remove any leftover files created by OpenTemporaryFile and any leftover
2646  * temporary relation files created by mdcreate.
2647  *
2648  * NOTE: we could, but don't, call this during a post-backend-crash restart
2649  * cycle. The argument for not doing it is that someone might want to examine
2650  * the temp files for debugging purposes. This does however mean that
2651  * OpenTemporaryFile had better allow for collision with an existing temp
2652  * file name.
2653  */
2654 void
2656 {
2657  char temp_path[MAXPGPATH];
2658  DIR *spc_dir;
2659  struct dirent *spc_de;
2660 
2661  /*
2662  * First process temp files in pg_default ($PGDATA/base)
2663  */
2664  snprintf(temp_path, sizeof(temp_path), "base/%s", PG_TEMP_FILES_DIR);
2665  RemovePgTempFilesInDir(temp_path);
2666  RemovePgTempRelationFiles("base");
2667 
2668  /*
2669  * Cycle through temp directories for all non-default tablespaces.
2670  */
2671  spc_dir = AllocateDir("pg_tblspc");
2672 
2673  while ((spc_de = ReadDir(spc_dir, "pg_tblspc")) != NULL)
2674  {
2675  if (strcmp(spc_de->d_name, ".") == 0 ||
2676  strcmp(spc_de->d_name, "..") == 0)
2677  continue;
2678 
2679  snprintf(temp_path, sizeof(temp_path), "pg_tblspc/%s/%s/%s",
2681  RemovePgTempFilesInDir(temp_path);
2682 
2683  snprintf(temp_path, sizeof(temp_path), "pg_tblspc/%s/%s",
2685  RemovePgTempRelationFiles(temp_path);
2686  }
2687 
2688  FreeDir(spc_dir);
2689 
2690  /*
2691  * In EXEC_BACKEND case there is a pgsql_tmp directory at the top level of
2692  * DataDir as well.
2693  */
2694 #ifdef EXEC_BACKEND
2696 #endif
2697 }
2698 
2699 /* Process one pgsql_tmp directory for RemovePgTempFiles */
2700 static void
2701 RemovePgTempFilesInDir(const char *tmpdirname)
2702 {
2703  DIR *temp_dir;
2704  struct dirent *temp_de;
2705  char rm_path[MAXPGPATH];
2706 
2707  temp_dir = AllocateDir(tmpdirname);
2708  if (temp_dir == NULL)
2709  {
2710  /* anything except ENOENT is fishy */
2711  if (errno != ENOENT)
2712  elog(LOG,
2713  "could not open temporary-files directory \"%s\": %m",
2714  tmpdirname);
2715  return;
2716  }
2717 
2718  while ((temp_de = ReadDir(temp_dir, tmpdirname)) != NULL)
2719  {
2720  if (strcmp(temp_de->d_name, ".") == 0 ||
2721  strcmp(temp_de->d_name, "..") == 0)
2722  continue;
2723 
2724  snprintf(rm_path, sizeof(rm_path), "%s/%s",
2725  tmpdirname, temp_de->d_name);
2726 
2727  if (strncmp(temp_de->d_name,
2729  strlen(PG_TEMP_FILE_PREFIX)) == 0)
2730  unlink(rm_path); /* note we ignore any error */
2731  else
2732  elog(LOG,
2733  "unexpected file found in temporary-files directory: \"%s\"",
2734  rm_path);
2735  }
2736 
2737  FreeDir(temp_dir);
2738 }
2739 
2740 /* Process one tablespace directory, look for per-DB subdirectories */
2741 static void
2742 RemovePgTempRelationFiles(const char *tsdirname)
2743 {
2744  DIR *ts_dir;
2745  struct dirent *de;
2746  char dbspace_path[MAXPGPATH];
2747 
2748  ts_dir = AllocateDir(tsdirname);
2749  if (ts_dir == NULL)
2750  {
2751  /* anything except ENOENT is fishy */
2752  if (errno != ENOENT)
2753  elog(LOG,
2754  "could not open tablespace directory \"%s\": %m",
2755  tsdirname);
2756  return;
2757  }
2758 
2759  while ((de = ReadDir(ts_dir, tsdirname)) != NULL)
2760  {
2761  int i = 0;
2762 
2763  /*
2764  * We're only interested in the per-database directories, which have
2765  * numeric names. Note that this code will also (properly) ignore "."
2766  * and "..".
2767  */
2768  while (isdigit((unsigned char) de->d_name[i]))
2769  ++i;
2770  if (de->d_name[i] != '\0' || i == 0)
2771  continue;
2772 
2773  snprintf(dbspace_path, sizeof(dbspace_path), "%s/%s",
2774  tsdirname, de->d_name);
2775  RemovePgTempRelationFilesInDbspace(dbspace_path);
2776  }
2777 
2778  FreeDir(ts_dir);
2779 }
2780 
2781 /* Process one per-dbspace directory for RemovePgTempRelationFiles */
2782 static void
2783 RemovePgTempRelationFilesInDbspace(const char *dbspacedirname)
2784 {
2785  DIR *dbspace_dir;
2786  struct dirent *de;
2787  char rm_path[MAXPGPATH];
2788 
2789  dbspace_dir = AllocateDir(dbspacedirname);
2790  if (dbspace_dir == NULL)
2791  {
2792  /* we just saw this directory, so it really ought to be there */
2793  elog(LOG,
2794  "could not open dbspace directory \"%s\": %m",
2795  dbspacedirname);
2796  return;
2797  }
2798 
2799  while ((de = ReadDir(dbspace_dir, dbspacedirname)) != NULL)
2800  {
2801  if (!looks_like_temp_rel_name(de->d_name))
2802  continue;
2803 
2804  snprintf(rm_path, sizeof(rm_path), "%s/%s",
2805  dbspacedirname, de->d_name);
2806 
2807  unlink(rm_path); /* note we ignore any error */
2808  }
2809 
2810  FreeDir(dbspace_dir);
2811 }
2812 
2813 /* t<digits>_<digits>, or t<digits>_<digits>_<forkname> */
2814 static bool
2816 {
2817  int pos;
2818  int savepos;
2819 
2820  /* Must start with "t". */
2821  if (name[0] != 't')
2822  return false;
2823 
2824  /* Followed by a non-empty string of digits and then an underscore. */
2825  for (pos = 1; isdigit((unsigned char) name[pos]); ++pos)
2826  ;
2827  if (pos == 1 || name[pos] != '_')
2828  return false;
2829 
2830  /* Followed by another nonempty string of digits. */
2831  for (savepos = ++pos; isdigit((unsigned char) name[pos]); ++pos)
2832  ;
2833  if (savepos == pos)
2834  return false;
2835 
2836  /* We might have _forkname or .segment or both. */
2837  if (name[pos] == '_')
2838  {
2839  int forkchar = forkname_chars(&name[pos + 1], NULL);
2840 
2841  if (forkchar <= 0)
2842  return false;
2843  pos += forkchar + 1;
2844  }
2845  if (name[pos] == '.')
2846  {
2847  int segchar;
2848 
2849  for (segchar = 1; isdigit((unsigned char) name[pos + segchar]); ++segchar)
2850  ;
2851  if (segchar <= 1)
2852  return false;
2853  pos += segchar;
2854  }
2855 
2856  /* Now we should be at the end. */
2857  if (name[pos] != '\0')
2858  return false;
2859  return true;
2860 }
2861 
2862 
2863 /*
2864  * Issue fsync recursively on PGDATA and all its contents.
2865  *
2866  * We fsync regular files and directories wherever they are, but we
2867  * follow symlinks only for pg_wal and immediately under pg_tblspc.
2868  * Other symlinks are presumed to point at files we're not responsible
2869  * for fsyncing, and might not have privileges to write at all.
2870  *
2871  * Errors are logged but not considered fatal; that's because this is used
2872  * only during database startup, to deal with the possibility that there are
2873  * issued-but-unsynced writes pending against the data directory. We want to
2874  * ensure that such writes reach disk before anything that's done in the new
2875  * run. However, aborting on error would result in failure to start for
2876  * harmless cases such as read-only files in the data directory, and that's
2877  * not good either.
2878  *
2879  * Note we assume we're chdir'd into PGDATA to begin with.
2880  */
2881 void
2883 {
2884  bool xlog_is_symlink;
2885 
2886  /* We can skip this whole thing if fsync is disabled. */
2887  if (!enableFsync)
2888  return;
2889 
2890  /*
2891  * If pg_wal is a symlink, we'll need to recurse into it separately,
2892  * because the first walkdir below will ignore it.
2893  */
2894  xlog_is_symlink = false;
2895 
2896 #ifndef WIN32
2897  {
2898  struct stat st;
2899 
2900  if (lstat("pg_wal", &st) < 0)
2901  ereport(LOG,
2903  errmsg("could not stat file \"%s\": %m",
2904  "pg_wal")));
2905  else if (S_ISLNK(st.st_mode))
2906  xlog_is_symlink = true;
2907  }
2908 #else
2909  if (pgwin32_is_junction("pg_wal"))
2910  xlog_is_symlink = true;
2911 #endif
2912 
2913  /*
2914  * If possible, hint to the kernel that we're soon going to fsync the data
2915  * directory and its contents. Errors in this step are even less
2916  * interesting than normal, so log them only at DEBUG1.
2917  */
2918 #ifdef PG_FLUSH_DATA_WORKS
2919  walkdir(".", pre_sync_fname, false, DEBUG1);
2920  if (xlog_is_symlink)
2921  walkdir("pg_wal", pre_sync_fname, false, DEBUG1);
2922  walkdir("pg_tblspc", pre_sync_fname, true, DEBUG1);
2923 #endif
2924 
2925  /*
2926  * Now we do the fsync()s in the same order.
2927  *
2928  * The main call ignores symlinks, so in addition to specially processing
2929  * pg_wal if it's a symlink, pg_tblspc has to be visited separately with
2930  * process_symlinks = true. Note that if there are any plain directories
2931  * in pg_tblspc, they'll get fsync'd twice. That's not an expected case
2932  * so we don't worry about optimizing it.
2933  */
2934  walkdir(".", datadir_fsync_fname, false, LOG);
2935  if (xlog_is_symlink)
2936  walkdir("pg_wal", datadir_fsync_fname, false, LOG);
2937  walkdir("pg_tblspc", datadir_fsync_fname, true, LOG);
2938 }
2939 
2940 /*
2941  * walkdir: recursively walk a directory, applying the action to each
2942  * regular file and directory (including the named directory itself).
2943  *
2944  * If process_symlinks is true, the action and recursion are also applied
2945  * to regular files and directories that are pointed to by symlinks in the
2946  * given directory; otherwise symlinks are ignored. Symlinks are always
2947  * ignored in subdirectories, ie we intentionally don't pass down the
2948  * process_symlinks flag to recursive calls.
2949  *
2950  * Errors are reported at level elevel, which might be ERROR or less.
2951  *
2952  * See also walkdir in initdb.c, which is a frontend version of this logic.
2953  */
2954 static void
2955 walkdir(const char *path,
2956  void (*action) (const char *fname, bool isdir, int elevel),
2957  bool process_symlinks,
2958  int elevel)
2959 {
2960  DIR *dir;
2961  struct dirent *de;
2962 
2963  dir = AllocateDir(path);
2964  if (dir == NULL)
2965  {
2966  ereport(elevel,
2968  errmsg("could not open directory \"%s\": %m", path)));
2969  return;
2970  }
2971 
2972  while ((de = ReadDirExtended(dir, path, elevel)) != NULL)
2973  {
2974  char subpath[MAXPGPATH];
2975  struct stat fst;
2976  int sret;
2977 
2979 
2980  if (strcmp(de->d_name, ".") == 0 ||
2981  strcmp(de->d_name, "..") == 0)
2982  continue;
2983 
2984  snprintf(subpath, MAXPGPATH, "%s/%s", path, de->d_name);
2985 
2986  if (process_symlinks)
2987  sret = stat(subpath, &fst);
2988  else
2989  sret = lstat(subpath, &fst);
2990 
2991  if (sret < 0)
2992  {
2993  ereport(elevel,
2995  errmsg("could not stat file \"%s\": %m", subpath)));
2996  continue;
2997  }
2998 
2999  if (S_ISREG(fst.st_mode))
3000  (*action) (subpath, false, elevel);
3001  else if (S_ISDIR(fst.st_mode))
3002  walkdir(subpath, action, false, elevel);
3003  }
3004 
3005  FreeDir(dir); /* we ignore any error here */
3006 
3007  /*
3008  * It's important to fsync the destination directory itself as individual
3009  * file fsyncs don't guarantee that the directory entry for the file is
3010  * synced.
3011  */
3012  (*action) (path, true, elevel);
3013 }
3014 
3015 
3016 /*
3017  * Hint to the OS that it should get ready to fsync() this file.
3018  *
3019  * Ignores errors trying to open unreadable files, and logs other errors at a
3020  * caller-specified level.
3021  */
3022 #ifdef PG_FLUSH_DATA_WORKS
3023 
3024 static void
3025 pre_sync_fname(const char *fname, bool isdir, int elevel)
3026 {
3027  int fd;
3028 
3029  /* Don't try to flush directories, it'll likely just fail */
3030  if (isdir)
3031  return;
3032 
3033  fd = OpenTransientFile((char *) fname, O_RDONLY | PG_BINARY, 0);
3034 
3035  if (fd < 0)
3036  {
3037  if (errno == EACCES)
3038  return;
3039  ereport(elevel,
3041  errmsg("could not open file \"%s\": %m", fname)));
3042  return;
3043  }
3044 
3045  /*
3046  * pg_flush_data() ignores errors, which is ok because this is only a
3047  * hint.
3048  */
3049  pg_flush_data(fd, 0, 0);
3050 
3051  (void) CloseTransientFile(fd);
3052 }
3053 
3054 #endif /* PG_FLUSH_DATA_WORKS */
3055 
3056 static void
3057 datadir_fsync_fname(const char *fname, bool isdir, int elevel)
3058 {
3059  /*
3060  * We want to silently ignoring errors about unreadable files. Pass that
3061  * desire on to fsync_fname_ext().
3062  */
3063  fsync_fname_ext(fname, isdir, true, elevel);
3064 }
3065 
3066 /*
3067  * fsync_fname_ext -- Try to fsync a file or directory
3068  *
3069  * If ignore_perm is true, ignore errors upon trying to open unreadable
3070  * files. Logs other errors at a caller-specified level.
3071  *
3072  * Returns 0 if the operation succeeded, -1 otherwise.
3073  */
3074 static int
3075 fsync_fname_ext(const char *fname, bool isdir, bool ignore_perm, int elevel)
3076 {
3077  int fd;
3078  int flags;
3079  int returncode;
3080 
3081  /*
3082  * Some OSs require directories to be opened read-only whereas other
3083  * systems don't allow us to fsync files opened read-only; so we need both
3084  * cases here. Using O_RDWR will cause us to fail to fsync files that are
3085  * not writable by our userid, but we assume that's OK.
3086  */
3087  flags = PG_BINARY;
3088  if (!isdir)
3089  flags |= O_RDWR;
3090  else
3091  flags |= O_RDONLY;
3092 
3093  fd = OpenTransientFile((char *) fname, flags, 0);
3094 
3095  /*
3096  * Some OSs don't allow us to open directories at all (Windows returns
3097  * EACCES), just ignore the error in that case. If desired also silently
3098  * ignoring errors about unreadable files. Log others.
3099  */
3100  if (fd < 0 && isdir && (errno == EISDIR || errno == EACCES))
3101  return 0;
3102  else if (fd < 0 && ignore_perm && errno == EACCES)
3103  return 0;
3104  else if (fd < 0)
3105  {
3106  ereport(elevel,
3108  errmsg("could not open file \"%s\": %m", fname)));
3109  return -1;
3110  }
3111 
3112  returncode = pg_fsync(fd);
3113 
3114  /*
3115  * Some OSes don't allow us to fsync directories at all, so we can ignore
3116  * those errors. Anything else needs to be logged.
3117  */
3118  if (returncode != 0 && !(isdir && errno == EBADF))
3119  {
3120  int save_errno;
3121 
3122  /* close file upon error, might not be in transaction context */
3123  save_errno = errno;
3124  (void) CloseTransientFile(fd);
3125  errno = save_errno;
3126 
3127  ereport(elevel,
3129  errmsg("could not fsync file \"%s\": %m", fname)));
3130  return -1;
3131  }
3132 
3133  (void) CloseTransientFile(fd);
3134 
3135  return 0;
3136 }
3137 
3138 /*
3139  * fsync_parent_path -- fsync the parent path of a file or directory
3140  *
3141  * This is aimed at making file operations persistent on disk in case of
3142  * an OS crash or power failure.
3143  */
3144 static int
3145 fsync_parent_path(const char *fname, int elevel)
3146 {
3147  char parentpath[MAXPGPATH];
3148 
3149  strlcpy(parentpath, fname, MAXPGPATH);
3150  get_parent_directory(parentpath);
3151 
3152  /*
3153  * get_parent_directory() returns an empty string if the input argument is
3154  * just a file name (see comments in path.c), so handle that as being the
3155  * current directory.
3156  */
3157  if (strlen(parentpath) == 0)
3158  strlcpy(parentpath, ".", MAXPGPATH);
3159 
3160  if (fsync_fname_ext(parentpath, true, false, elevel) != 0)
3161  return -1;
3162 
3163  return 0;
3164 }
int FileWrite(File file, char *buffer, int amount)
Definition: fd.c:1666
File lruLessRecently
Definition: fd.c:183
void FileWriteback(File file, off_t offset, off_t nbytes)
Definition: fd.c:1579
void closeAllVfds(void)
Definition: fd.c:2448
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
#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:2580
#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:2955
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:802
void fsync_fname(const char *fname, bool isdir)
Definition: fd.c:567
int log_temp_files
Definition: guc.c:456
#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 FileSync(File file)
Definition: fd.c:1785
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:853
int pg_fsync_no_writethrough(int fd)
Definition: fd.c:350
static void RemovePgTempRelationFilesInDbspace(const char *dbspacedirname)
Definition: fd.c:2783
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:1449
static bool reserveAllocatedDesc(void)
Definition: fd.c:1970
uint32 SubTransactionId
Definition: c.h:398
#define LOG
Definition: elog.h:26
static void RemovePgTempFilesInDir(const char *tmpdirname)
Definition: fd.c:2701
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:1923
Definition: dirent.h:9
#define OidIsValid(objectId)
Definition: c.h:534
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:2419
#define malloc(a)
Definition: header.h:45
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:2502
static int FreeDesc(AllocateDesc *desc)
Definition: fd.c:2187
void pfree(void *pointer)
Definition: mcxt.c:992
static void RemovePgTempRelationFiles(const char *tsdirname)
Definition: fd.c:2742
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:2566
#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
#define DEBUG2
Definition: elog.h:24
int FileTruncate(File file, off_t offset)
Definition: fd.c:1890
char * fileName
Definition: fd.c:186
static struct dirent * ReadDirExtended(DIR *dir, const char *dirname, int elevel)
Definition: fd.c:2360
static char * buf
Definition: pg_test_fsync.c:65
Oid GetNextTempTableSpace(void)
Definition: fd.c:2514
void ResourceOwnerRememberFile(ResourceOwner owner, File file)
Definition: resowner.c:1200
static void CleanupTempFiles(bool isProcExit)
Definition: fd.c:2595
#define DEFAULTTABLESPACE_OID
Definition: pg_tablespace.h:63
int OpenTransientFile(FileName fileName, int fileFlags, int fileMode)
Definition: fd.c:2093
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:2043
static int nfile
Definition: fd.c:203
void SyncDataDirectory(void)
Definition: fd.c:2882
DIR * AllocateDir(const char *dirname)
Definition: fd.c:2284
int FilePrefetch(File file, off_t offset, int amount)
Definition: fd.c:1553
static int nextTempTableSpace
Definition: fd.c:259
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:2133
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 link(const char *fromname, const char *toname)
void SetTempTablespaces(Oid *tableSpaces, int numSpaces)
Definition: fd.c:2474
#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:3057
int CloseTransientFile(int fd)
Definition: fd.c:2254
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:136
#define FD_TEMPORARY
Definition: fd.c:173
#define FD_XACT_TEMPORARY
Definition: fd.c:174
struct vfd Vfd
uintptr_t Datum
Definition: postgres.h:374
void AtEOSubXact_Files(bool isCommit, SubTransactionId mySubid, SubTransactionId parentSubid)
Definition: fd.c:2535
#define EINTR
Definition: win32.h:295
unsigned int Index
Definition: c.h:362
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:2815
#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:60
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
#define NULL
Definition: c.h:226
static int FileAccess(File file)
Definition: fd.c:1213
#define Assert(condition)
Definition: c.h:671
void _dosmaperr(unsigned long)
Definition: win32error.c:171
SubTransactionId GetCurrentSubTransactionId(void)
Definition: xact.c:648
struct dirent * ReadDir(DIR *dir, const char *dirname)
Definition: fd.c:2350
File lruMoreRecently
Definition: fd.c:182
void RemovePgTempFiles(void)
Definition: fd.c:2655
SubTransactionId create_subid
Definition: fd.c:234
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:353
int sync_method
Definition: xlog.c:102
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:55
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:1021
#define INT64_FORMAT
Definition: c.h:312
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:2226
void set_max_safe_fds(void)
Definition: fd.c:844
union AllocateDesc::@25 desc
bool enableFsync
Definition: globals.c:110
static Oid * tempTableSpaces
Definition: fd.c:257
void * palloc(Size size)
Definition: mcxt.c:891
int errmsg(const char *fmt,...)
Definition: elog.c:797
int FileGetRawFlags(File file)
Definition: fd.c:1949
void ResourceOwnerEnlargeFiles(ResourceOwner owner)
Definition: resowner.c:1189
int FileGetRawMode(File file)
Definition: fd.c:1959
static int fsync_fname_ext(const char *fname, bool isdir, bool ignore_perm, int elevel)
Definition: fd.c:3075
int i
void * arg
int FileGetRawDesc(File file)
Definition: fd.c:1939
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:1802
#define lstat(path, sb)
Definition: win32.h:272
void ResourceOwnerForgetFile(ResourceOwner owner, File file)
Definition: resowner.c:1209
#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:3145
int File
Definition: fd.h:51
#define read(a, b, c)
Definition: win32.h:18
int FreeDir(DIR *dir)
Definition: fd.c:2393
int temp_file_limit
Definition: guc.c:459
Datum subpath(PG_FUNCTION_ARGS)
Definition: ltree_op.c:234
void InitFileAccess(void)
Definition: fd.c:727
int FileRead(File file, char *buffer, int amount)
Definition: fd.c:1604
static int numAllocatedDescs
Definition: fd.c:243
int BasicOpenFile(FileName fileName, int fileFlags, int fileMode)
Definition: fd.c:899