PostgreSQL Source Code  git master
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-2021, 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 1024 on many modern
20  * operating systems, but may be lower 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  * PathName(Create|Open|Delete)Temporary(File|Dir) are used to manage
43  * temporary files that have names so that they can be shared between
44  * backends. Such files are automatically closed and count against the
45  * temporary file limit of the backend that creates them, but unlike anonymous
46  * files they are not automatically deleted. See sharedfileset.c for a shared
47  * ownership mechanism that provides automatic cleanup for shared files when
48  * the last of a group of backends detaches.
49  *
50  * AllocateFile, AllocateDir, OpenPipeStream and OpenTransientFile are
51  * wrappers around fopen(3), opendir(3), popen(3) and open(2), respectively.
52  * They behave like the corresponding native functions, except that the handle
53  * is registered with the current subtransaction, and will be automatically
54  * closed at abort. These are intended mainly for short operations like
55  * reading a configuration file; there is a limit on the number of files that
56  * can be opened using these functions at any one time.
57  *
58  * Finally, BasicOpenFile is just a thin wrapper around open() that can
59  * release file descriptors in use by the virtual file descriptors if
60  * necessary. There is no automatic cleanup of file descriptors returned by
61  * BasicOpenFile, it is solely the caller's responsibility to close the file
62  * descriptor by calling close(2).
63  *
64  * If a non-virtual file descriptor needs to be held open for any length of
65  * time, report it to fd.c by calling AcquireExternalFD or ReserveExternalFD
66  * (and eventually ReleaseExternalFD), so that we can take it into account
67  * while deciding how many VFDs can be open. This applies to FDs obtained
68  * with BasicOpenFile as well as those obtained without use of any fd.c API.
69  *
70  *-------------------------------------------------------------------------
71  */
72 
73 #include "postgres.h"
74 
75 #include <dirent.h>
76 #include <sys/file.h>
77 #include <sys/param.h>
78 #include <sys/stat.h>
79 #include <sys/types.h>
80 #ifndef WIN32
81 #include <sys/mman.h>
82 #endif
83 #include <limits.h>
84 #include <unistd.h>
85 #include <fcntl.h>
86 #ifdef HAVE_SYS_RESOURCE_H
87 #include <sys/resource.h> /* for getrlimit */
88 #endif
89 
90 #include "access/xact.h"
91 #include "access/xlog.h"
92 #include "catalog/pg_tablespace.h"
93 #include "common/file_perm.h"
94 #include "common/file_utils.h"
95 #include "miscadmin.h"
96 #include "pgstat.h"
97 #include "port/pg_iovec.h"
98 #include "portability/mem.h"
99 #include "storage/fd.h"
100 #include "storage/ipc.h"
101 #include "utils/guc.h"
102 #include "utils/resowner_private.h"
103 
104 /* Define PG_FLUSH_DATA_WORKS if we have an implementation for pg_flush_data */
105 #if defined(HAVE_SYNC_FILE_RANGE)
106 #define PG_FLUSH_DATA_WORKS 1
107 #elif !defined(WIN32) && defined(MS_ASYNC)
108 #define PG_FLUSH_DATA_WORKS 1
109 #elif defined(USE_POSIX_FADVISE) && defined(POSIX_FADV_DONTNEED)
110 #define PG_FLUSH_DATA_WORKS 1
111 #endif
112 
113 /*
114  * We must leave some file descriptors free for system(), the dynamic loader,
115  * and other code that tries to open files without consulting fd.c. This
116  * is the number left free. (While we try fairly hard to prevent EMFILE
117  * errors, there's never any guarantee that we won't get ENFILE due to
118  * other processes chewing up FDs. So it's a bad idea to try to open files
119  * without consulting fd.c. Nonetheless we cannot control all code.)
120  *
121  * Because this is just a fixed setting, we are effectively assuming that
122  * no such code will leave FDs open over the long term; otherwise the slop
123  * is likely to be insufficient. Note in particular that we expect that
124  * loading a shared library does not result in any permanent increase in
125  * the number of open files. (This appears to be true on most if not
126  * all platforms as of Feb 2004.)
127  */
128 #define NUM_RESERVED_FDS 10
129 
130 /*
131  * If we have fewer than this many usable FDs after allowing for the reserved
132  * ones, choke. (This value is chosen to work with "ulimit -n 64", but not
133  * much less than that. Note that this value ensures numExternalFDs can be
134  * at least 16; as of this writing, the contrib/postgres_fdw regression tests
135  * will not pass unless that can grow to at least 14.)
136  */
137 #define FD_MINFREE 48
138 
139 /*
140  * A number of platforms allow individual processes to open many more files
141  * than they can really support when *many* processes do the same thing.
142  * This GUC parameter lets the DBA limit max_safe_fds to something less than
143  * what the postmaster's initial probe suggests will work.
144  */
146 
147 /*
148  * Maximum number of file descriptors to open for operations that fd.c knows
149  * about (VFDs, AllocateFile etc, or "external" FDs). This is initialized
150  * to a conservative value, and remains that way indefinitely in bootstrap or
151  * standalone-backend cases. In normal postmaster operation, the postmaster
152  * calls set_max_safe_fds() late in initialization to update the value, and
153  * that value is then inherited by forked subprocesses.
154  *
155  * Note: the value of max_files_per_process is taken into account while
156  * setting this variable, and so need not be tested separately.
157  */
158 int max_safe_fds = FD_MINFREE; /* default if not changed */
159 
160 /* Whether it is safe to continue running after fsync() fails. */
161 bool data_sync_retry = false;
162 
163 /* How SyncDataDirectory() should do its job. */
165 
166 /* Debugging.... */
167 
168 #ifdef FDDEBUG
169 #define DO_DB(A) \
170  do { \
171  int _do_db_save_errno = errno; \
172  A; \
173  errno = _do_db_save_errno; \
174  } while (0)
175 #else
176 #define DO_DB(A) \
177  ((void) 0)
178 #endif
179 
180 #define VFD_CLOSED (-1)
181 
182 #define FileIsValid(file) \
183  ((file) > 0 && (file) < (int) SizeVfdCache && VfdCache[file].fileName != NULL)
184 
185 #define FileIsNotOpen(file) (VfdCache[file].fd == VFD_CLOSED)
186 
187 /* these are the assigned bits in fdstate below: */
188 #define FD_DELETE_AT_CLOSE (1 << 0) /* T = delete when closed */
189 #define FD_CLOSE_AT_EOXACT (1 << 1) /* T = close at eoXact */
190 #define FD_TEMP_FILE_LIMIT (1 << 2) /* T = respect temp_file_limit */
191 
192 typedef struct vfd
193 {
194  int fd; /* current FD, or VFD_CLOSED if none */
195  unsigned short fdstate; /* bitflags for VFD's state */
196  ResourceOwner resowner; /* owner, for automatic cleanup */
197  File nextFree; /* link to next free VFD, if in freelist */
198  File lruMoreRecently; /* doubly linked recency-of-use list */
200  off_t fileSize; /* current size of file (0 if not temporary) */
201  char *fileName; /* name of file, or NULL for unused VFD */
202  /* NB: fileName is malloc'd, and must be free'd when closing the VFD */
203  int fileFlags; /* open(2) flags for (re)opening the file */
204  mode_t fileMode; /* mode to pass to open(2) */
205 } Vfd;
206 
207 /*
208  * Virtual File Descriptor array pointer and size. This grows as
209  * needed. 'File' values are indexes into this array.
210  * Note that VfdCache[0] is not a usable VFD, just a list header.
211  */
212 static Vfd *VfdCache;
213 static Size SizeVfdCache = 0;
214 
215 /*
216  * Number of file descriptors known to be in use by VFD entries.
217  */
218 static int nfile = 0;
219 
220 /*
221  * Flag to tell whether it's worth scanning VfdCache looking for temp files
222  * to close
223  */
224 static bool have_xact_temporary_files = false;
225 
226 /*
227  * Tracks the total size of all temporary files. Note: when temp_file_limit
228  * is being enforced, this cannot overflow since the limit cannot be more
229  * than INT_MAX kilobytes. When not enforcing, it could theoretically
230  * overflow, but we don't care.
231  */
232 static uint64 temporary_files_size = 0;
233 
234 /*
235  * List of OS handles opened with AllocateFile, AllocateDir and
236  * OpenTransientFile.
237  */
238 typedef enum
239 {
245 
246 typedef struct
247 {
250  union
251  {
252  FILE *file;
254  int fd;
255  } desc;
256 } AllocateDesc;
257 
258 static int numAllocatedDescs = 0;
259 static int maxAllocatedDescs = 0;
261 
262 /*
263  * Number of open "external" FDs reported to Reserve/ReleaseExternalFD.
264  */
265 static int numExternalFDs = 0;
266 
267 /*
268  * Number of temporary files opened during the current session;
269  * this is used in generation of tempfile names.
270  */
271 static long tempFileCounter = 0;
272 
273 /*
274  * Array of OIDs of temp tablespaces. (Some entries may be InvalidOid,
275  * indicating that the current database's default tablespace should be used.)
276  * When numTempTableSpaces is -1, this has not been set in the current
277  * transaction.
278  */
279 static Oid *tempTableSpaces = NULL;
280 static int numTempTableSpaces = -1;
281 static int nextTempTableSpace = 0;
282 
283 
284 /*--------------------
285  *
286  * Private Routines
287  *
288  * Delete - delete a file from the Lru ring
289  * LruDelete - remove a file from the Lru ring and close its FD
290  * Insert - put a file at the front of the Lru ring
291  * LruInsert - put a file at the front of the Lru ring and open it
292  * ReleaseLruFile - Release an fd by closing the last entry in the Lru ring
293  * ReleaseLruFiles - Release fd(s) until we're under the max_safe_fds limit
294  * AllocateVfd - grab a free (or new) file record (from VfdCache)
295  * FreeVfd - free a file record
296  *
297  * The Least Recently Used ring is a doubly linked list that begins and
298  * ends on element zero. Element zero is special -- it doesn't represent
299  * a file and its "fd" field always == VFD_CLOSED. Element zero is just an
300  * anchor that shows us the beginning/end of the ring.
301  * Only VFD elements that are currently really open (have an FD assigned) are
302  * in the Lru ring. Elements that are "virtually" open can be recognized
303  * by having a non-null fileName field.
304  *
305  * example:
306  *
307  * /--less----\ /---------\
308  * v \ v \
309  * #0 --more---> LeastRecentlyUsed --more-\ \
310  * ^\ | |
311  * \\less--> MostRecentlyUsedFile <---/ |
312  * \more---/ \--less--/
313  *
314  *--------------------
315  */
316 static void Delete(File file);
317 static void LruDelete(File file);
318 static void Insert(File file);
319 static int LruInsert(File file);
320 static bool ReleaseLruFile(void);
321 static void ReleaseLruFiles(void);
322 static File AllocateVfd(void);
323 static void FreeVfd(File file);
324 
325 static int FileAccess(File file);
326 static File OpenTemporaryFileInTablespace(Oid tblspcOid, bool rejectError);
327 static bool reserveAllocatedDesc(void);
328 static int FreeDesc(AllocateDesc *desc);
329 
330 static void AtProcExit_Files(int code, Datum arg);
331 static void CleanupTempFiles(bool isCommit, bool isProcExit);
332 static void RemovePgTempRelationFiles(const char *tsdirname);
333 static void RemovePgTempRelationFilesInDbspace(const char *dbspacedirname);
334 
335 static void walkdir(const char *path,
336  void (*action) (const char *fname, bool isdir, int elevel),
337  bool process_symlinks,
338  int elevel);
339 #ifdef PG_FLUSH_DATA_WORKS
340 static void pre_sync_fname(const char *fname, bool isdir, int elevel);
341 #endif
342 static void datadir_fsync_fname(const char *fname, bool isdir, int elevel);
343 static void unlink_if_exists_fname(const char *fname, bool isdir, int elevel);
344 
345 static int fsync_parent_path(const char *fname, int elevel);
346 
347 
348 /*
349  * pg_fsync --- do fsync with or without writethrough
350  */
351 int
353 {
354 #if !defined(WIN32) && defined(USE_ASSERT_CHECKING)
355  struct stat st;
356 
357  /*
358  * Some operating system implementations of fsync() have requirements
359  * about the file access modes that were used when their file descriptor
360  * argument was opened, and these requirements differ depending on whether
361  * the file descriptor is for a directory.
362  *
363  * For any file descriptor that may eventually be handed to fsync(), we
364  * should have opened it with access modes that are compatible with
365  * fsync() on all supported systems, otherwise the code may not be
366  * portable, even if it runs ok on the current system.
367  *
368  * We assert here that a descriptor for a file was opened with write
369  * permissions (either O_RDWR or O_WRONLY) and for a directory without
370  * write permissions (O_RDONLY).
371  *
372  * Ignore any fstat errors and let the follow-up fsync() do its work.
373  * Doing this sanity check here counts for the case where fsync() is
374  * disabled.
375  */
376  if (fstat(fd, &st) == 0)
377  {
378  int desc_flags = fcntl(fd, F_GETFL);
379 
380  /*
381  * O_RDONLY is historically 0, so just make sure that for directories
382  * no write flags are used.
383  */
384  if (S_ISDIR(st.st_mode))
385  Assert((desc_flags & (O_RDWR | O_WRONLY)) == 0);
386  else
387  Assert((desc_flags & (O_RDWR | O_WRONLY)) != 0);
388  }
389  errno = 0;
390 #endif
391 
392  /* #if is to skip the sync_method test if there's no need for it */
393 #if defined(HAVE_FSYNC_WRITETHROUGH) && !defined(FSYNC_WRITETHROUGH_IS_FSYNC)
395  return pg_fsync_writethrough(fd);
396  else
397 #endif
398  return pg_fsync_no_writethrough(fd);
399 }
400 
401 
402 /*
403  * pg_fsync_no_writethrough --- same as fsync except does nothing if
404  * enableFsync is off
405  */
406 int
408 {
409  if (enableFsync)
410  return fsync(fd);
411  else
412  return 0;
413 }
414 
415 /*
416  * pg_fsync_writethrough
417  */
418 int
420 {
421  if (enableFsync)
422  {
423 #ifdef WIN32
424  return _commit(fd);
425 #elif defined(F_FULLFSYNC)
426  return (fcntl(fd, F_FULLFSYNC, 0) == -1) ? -1 : 0;
427 #else
428  errno = ENOSYS;
429  return -1;
430 #endif
431  }
432  else
433  return 0;
434 }
435 
436 /*
437  * pg_fdatasync --- same as fdatasync except does nothing if enableFsync is off
438  *
439  * Not all platforms have fdatasync; treat as fsync if not available.
440  */
441 int
443 {
444  if (enableFsync)
445  {
446 #ifdef HAVE_FDATASYNC
447  return fdatasync(fd);
448 #else
449  return fsync(fd);
450 #endif
451  }
452  else
453  return 0;
454 }
455 
456 /*
457  * pg_flush_data --- advise OS that the described dirty data should be flushed
458  *
459  * offset of 0 with nbytes 0 means that the entire file should be flushed
460  */
461 void
462 pg_flush_data(int fd, off_t offset, off_t nbytes)
463 {
464  /*
465  * Right now file flushing is primarily used to avoid making later
466  * fsync()/fdatasync() calls have less impact. Thus don't trigger flushes
467  * if fsyncs are disabled - that's a decision we might want to make
468  * configurable at some point.
469  */
470  if (!enableFsync)
471  return;
472 
473  /*
474  * We compile all alternatives that are supported on the current platform,
475  * to find portability problems more easily.
476  */
477 #if defined(HAVE_SYNC_FILE_RANGE)
478  {
479  int rc;
480  static bool not_implemented_by_kernel = false;
481 
482  if (not_implemented_by_kernel)
483  return;
484 
485  /*
486  * sync_file_range(SYNC_FILE_RANGE_WRITE), currently linux specific,
487  * tells the OS that writeback for the specified blocks should be
488  * started, but that we don't want to wait for completion. Note that
489  * this call might block if too much dirty data exists in the range.
490  * This is the preferable method on OSs supporting it, as it works
491  * reliably when available (contrast to msync()) and doesn't flush out
492  * clean data (like FADV_DONTNEED).
493  */
494  rc = sync_file_range(fd, offset, nbytes,
495  SYNC_FILE_RANGE_WRITE);
496  if (rc != 0)
497  {
498  int elevel;
499 
500  /*
501  * For systems that don't have an implementation of
502  * sync_file_range() such as Windows WSL, generate only one
503  * warning and then suppress all further attempts by this process.
504  */
505  if (errno == ENOSYS)
506  {
507  elevel = WARNING;
508  not_implemented_by_kernel = true;
509  }
510  else
511  elevel = data_sync_elevel(WARNING);
512 
513  ereport(elevel,
515  errmsg("could not flush dirty data: %m")));
516  }
517 
518  return;
519  }
520 #endif
521 #if !defined(WIN32) && defined(MS_ASYNC)
522  {
523  void *p;
524  static int pagesize = 0;
525 
526  /*
527  * On several OSs msync(MS_ASYNC) on a mmap'ed file triggers
528  * writeback. On linux it only does so if MS_SYNC is specified, but
529  * then it does the writeback synchronously. Luckily all common linux
530  * systems have sync_file_range(). This is preferable over
531  * FADV_DONTNEED because it doesn't flush out clean data.
532  *
533  * We map the file (mmap()), tell the kernel to sync back the contents
534  * (msync()), and then remove the mapping again (munmap()).
535  */
536 
537  /* mmap() needs actual length if we want to map whole file */
538  if (offset == 0 && nbytes == 0)
539  {
540  nbytes = lseek(fd, 0, SEEK_END);
541  if (nbytes < 0)
542  {
545  errmsg("could not determine dirty data size: %m")));
546  return;
547  }
548  }
549 
550  /*
551  * Some platforms reject partial-page mmap() attempts. To deal with
552  * that, just truncate the request to a page boundary. If any extra
553  * bytes don't get flushed, well, it's only a hint anyway.
554  */
555 
556  /* fetch pagesize only once */
557  if (pagesize == 0)
558  pagesize = sysconf(_SC_PAGESIZE);
559 
560  /* align length to pagesize, dropping any fractional page */
561  if (pagesize > 0)
562  nbytes = (nbytes / pagesize) * pagesize;
563 
564  /* fractional-page request is a no-op */
565  if (nbytes <= 0)
566  return;
567 
568  /*
569  * mmap could well fail, particularly on 32-bit platforms where there
570  * may simply not be enough address space. If so, silently fall
571  * through to the next implementation.
572  */
573  if (nbytes <= (off_t) SSIZE_MAX)
574  p = mmap(NULL, nbytes, PROT_READ, MAP_SHARED, fd, offset);
575  else
576  p = MAP_FAILED;
577 
578  if (p != MAP_FAILED)
579  {
580  int rc;
581 
582  rc = msync(p, (size_t) nbytes, MS_ASYNC);
583  if (rc != 0)
584  {
587  errmsg("could not flush dirty data: %m")));
588  /* NB: need to fall through to munmap()! */
589  }
590 
591  rc = munmap(p, (size_t) nbytes);
592  if (rc != 0)
593  {
594  /* FATAL error because mapping would remain */
595  ereport(FATAL,
597  errmsg("could not munmap() while flushing data: %m")));
598  }
599 
600  return;
601  }
602  }
603 #endif
604 #if defined(USE_POSIX_FADVISE) && defined(POSIX_FADV_DONTNEED)
605  {
606  int rc;
607 
608  /*
609  * Signal the kernel that the passed in range should not be cached
610  * anymore. This has the, desired, side effect of writing out dirty
611  * data, and the, undesired, side effect of likely discarding useful
612  * clean cached blocks. For the latter reason this is the least
613  * preferable method.
614  */
615 
616  rc = posix_fadvise(fd, offset, nbytes, POSIX_FADV_DONTNEED);
617 
618  if (rc != 0)
619  {
620  /* don't error out, this is just a performance optimization */
623  errmsg("could not flush dirty data: %m")));
624  }
625 
626  return;
627  }
628 #endif
629 }
630 
631 /*
632  * Truncate a file to a given length by name.
633  */
634 int
635 pg_truncate(const char *path, off_t length)
636 {
637 #ifdef WIN32
638  int save_errno;
639  int ret;
640  int fd;
641 
642  fd = OpenTransientFile(path, O_RDWR | PG_BINARY);
643  if (fd >= 0)
644  {
645  ret = ftruncate(fd, 0);
646  save_errno = errno;
647  CloseTransientFile(fd);
648  errno = save_errno;
649  }
650  else
651  ret = -1;
652 
653  return ret;
654 #else
655  return truncate(path, length);
656 #endif
657 }
658 
659 /*
660  * fsync_fname -- fsync a file or directory, handling errors properly
661  *
662  * Try to fsync a file or directory. When doing the latter, ignore errors that
663  * indicate the OS just doesn't allow/require fsyncing directories.
664  */
665 void
666 fsync_fname(const char *fname, bool isdir)
667 {
668  fsync_fname_ext(fname, isdir, false, data_sync_elevel(ERROR));
669 }
670 
671 /*
672  * durable_rename -- rename(2) wrapper, issuing fsyncs required for durability
673  *
674  * This routine ensures that, after returning, the effect of renaming file
675  * persists in case of a crash. A crash while this routine is running will
676  * leave you with either the pre-existing or the moved file in place of the
677  * new file; no mixed state or truncated files are possible.
678  *
679  * It does so by using fsync on the old filename and the possibly existing
680  * target filename before the rename, and the target file and directory after.
681  *
682  * Note that rename() cannot be used across arbitrary directories, as they
683  * might not be on the same filesystem. Therefore this routine does not
684  * support renaming across directories.
685  *
686  * Log errors with the caller specified severity.
687  *
688  * Returns 0 if the operation succeeded, -1 otherwise. Note that errno is not
689  * valid upon return.
690  */
691 int
692 durable_rename(const char *oldfile, const char *newfile, int elevel)
693 {
694  int fd;
695 
696  /*
697  * First fsync the old and target path (if it exists), to ensure that they
698  * are properly persistent on disk. Syncing the target file is not
699  * strictly necessary, but it makes it easier to reason about crashes;
700  * because it's then guaranteed that either source or target file exists
701  * after a crash.
702  */
703  if (fsync_fname_ext(oldfile, false, false, elevel) != 0)
704  return -1;
705 
706  fd = OpenTransientFile(newfile, PG_BINARY | O_RDWR);
707  if (fd < 0)
708  {
709  if (errno != ENOENT)
710  {
711  ereport(elevel,
713  errmsg("could not open file \"%s\": %m", newfile)));
714  return -1;
715  }
716  }
717  else
718  {
719  if (pg_fsync(fd) != 0)
720  {
721  int save_errno;
722 
723  /* close file upon error, might not be in transaction context */
724  save_errno = errno;
725  CloseTransientFile(fd);
726  errno = save_errno;
727 
728  ereport(elevel,
730  errmsg("could not fsync file \"%s\": %m", newfile)));
731  return -1;
732  }
733 
734  if (CloseTransientFile(fd) != 0)
735  {
736  ereport(elevel,
738  errmsg("could not close file \"%s\": %m", newfile)));
739  return -1;
740  }
741  }
742 
743  /* Time to do the real deal... */
744  if (rename(oldfile, newfile) < 0)
745  {
746  ereport(elevel,
748  errmsg("could not rename file \"%s\" to \"%s\": %m",
749  oldfile, newfile)));
750  return -1;
751  }
752 
753  /*
754  * To guarantee renaming the file is persistent, fsync the file with its
755  * new name, and its containing directory.
756  */
757  if (fsync_fname_ext(newfile, false, false, elevel) != 0)
758  return -1;
759 
760  if (fsync_parent_path(newfile, elevel) != 0)
761  return -1;
762 
763  return 0;
764 }
765 
766 /*
767  * durable_unlink -- remove a file in a durable manner
768  *
769  * This routine ensures that, after returning, the effect of removing file
770  * persists in case of a crash. A crash while this routine is running will
771  * leave the system in no mixed state.
772  *
773  * It does so by using fsync on the parent directory of the file after the
774  * actual removal is done.
775  *
776  * Log errors with the severity specified by caller.
777  *
778  * Returns 0 if the operation succeeded, -1 otherwise. Note that errno is not
779  * valid upon return.
780  */
781 int
782 durable_unlink(const char *fname, int elevel)
783 {
784  if (unlink(fname) < 0)
785  {
786  ereport(elevel,
788  errmsg("could not remove file \"%s\": %m",
789  fname)));
790  return -1;
791  }
792 
793  /*
794  * To guarantee that the removal of the file is persistent, fsync its
795  * parent directory.
796  */
797  if (fsync_parent_path(fname, elevel) != 0)
798  return -1;
799 
800  return 0;
801 }
802 
803 /*
804  * durable_rename_excl -- rename a file in a durable manner.
805  *
806  * Similar to durable_rename(), except that this routine tries (but does not
807  * guarantee) not to overwrite the target file.
808  *
809  * Note that a crash in an unfortunate moment can leave you with two links to
810  * the target file.
811  *
812  * Log errors with the caller specified severity.
813  *
814  * On Windows, using a hard link followed by unlink() causes concurrency
815  * issues, while a simple rename() does not cause that, so be careful when
816  * changing the logic of this routine.
817  *
818  * Returns 0 if the operation succeeded, -1 otherwise. Note that errno is not
819  * valid upon return.
820  */
821 int
822 durable_rename_excl(const char *oldfile, const char *newfile, int elevel)
823 {
824  /*
825  * Ensure that, if we crash directly after the rename/link, a file with
826  * valid contents is moved into place.
827  */
828  if (fsync_fname_ext(oldfile, false, false, elevel) != 0)
829  return -1;
830 
831 #ifdef HAVE_WORKING_LINK
832  if (link(oldfile, newfile) < 0)
833  {
834  ereport(elevel,
836  errmsg("could not link file \"%s\" to \"%s\": %m",
837  oldfile, newfile)));
838  return -1;
839  }
840  unlink(oldfile);
841 #else
842  if (rename(oldfile, newfile) < 0)
843  {
844  ereport(elevel,
846  errmsg("could not rename file \"%s\" to \"%s\": %m",
847  oldfile, newfile)));
848  return -1;
849  }
850 #endif
851 
852  /*
853  * Make change persistent in case of an OS crash, both the new entry and
854  * its parent directory need to be flushed.
855  */
856  if (fsync_fname_ext(newfile, false, false, elevel) != 0)
857  return -1;
858 
859  /* Same for parent directory */
860  if (fsync_parent_path(newfile, elevel) != 0)
861  return -1;
862 
863  return 0;
864 }
865 
866 /*
867  * InitFileAccess --- initialize this module during backend startup
868  *
869  * This is called during either normal or standalone backend start.
870  * It is *not* called in the postmaster.
871  */
872 void
874 {
875  Assert(SizeVfdCache == 0); /* call me only once */
876 
877  /* initialize cache header entry */
878  VfdCache = (Vfd *) malloc(sizeof(Vfd));
879  if (VfdCache == NULL)
880  ereport(FATAL,
881  (errcode(ERRCODE_OUT_OF_MEMORY),
882  errmsg("out of memory")));
883 
884  MemSet((char *) &(VfdCache[0]), 0, sizeof(Vfd));
885  VfdCache->fd = VFD_CLOSED;
886 
887  SizeVfdCache = 1;
888 
889  /* register proc-exit hook to ensure temp files are dropped at exit */
891 }
892 
893 /*
894  * count_usable_fds --- count how many FDs the system will let us open,
895  * and estimate how many are already open.
896  *
897  * We stop counting if usable_fds reaches max_to_probe. Note: a small
898  * value of max_to_probe might result in an underestimate of already_open;
899  * we must fill in any "gaps" in the set of used FDs before the calculation
900  * of already_open will give the right answer. In practice, max_to_probe
901  * of a couple of dozen should be enough to ensure good results.
902  *
903  * We assume stdin (FD 0) is available for dup'ing
904  */
905 static void
906 count_usable_fds(int max_to_probe, int *usable_fds, int *already_open)
907 {
908  int *fd;
909  int size;
910  int used = 0;
911  int highestfd = 0;
912  int j;
913 
914 #ifdef HAVE_GETRLIMIT
915  struct rlimit rlim;
916  int getrlimit_status;
917 #endif
918 
919  size = 1024;
920  fd = (int *) palloc(size * sizeof(int));
921 
922 #ifdef HAVE_GETRLIMIT
923 #ifdef RLIMIT_NOFILE /* most platforms use RLIMIT_NOFILE */
924  getrlimit_status = getrlimit(RLIMIT_NOFILE, &rlim);
925 #else /* but BSD doesn't ... */
926  getrlimit_status = getrlimit(RLIMIT_OFILE, &rlim);
927 #endif /* RLIMIT_NOFILE */
928  if (getrlimit_status != 0)
929  ereport(WARNING, (errmsg("getrlimit failed: %m")));
930 #endif /* HAVE_GETRLIMIT */
931 
932  /* dup until failure or probe limit reached */
933  for (;;)
934  {
935  int thisfd;
936 
937 #ifdef HAVE_GETRLIMIT
938 
939  /*
940  * don't go beyond RLIMIT_NOFILE; causes irritating kernel logs on
941  * some platforms
942  */
943  if (getrlimit_status == 0 && highestfd >= rlim.rlim_cur - 1)
944  break;
945 #endif
946 
947  thisfd = dup(0);
948  if (thisfd < 0)
949  {
950  /* Expect EMFILE or ENFILE, else it's fishy */
951  if (errno != EMFILE && errno != ENFILE)
952  elog(WARNING, "dup(0) failed after %d successes: %m", used);
953  break;
954  }
955 
956  if (used >= size)
957  {
958  size *= 2;
959  fd = (int *) repalloc(fd, size * sizeof(int));
960  }
961  fd[used++] = thisfd;
962 
963  if (highestfd < thisfd)
964  highestfd = thisfd;
965 
966  if (used >= max_to_probe)
967  break;
968  }
969 
970  /* release the files we opened */
971  for (j = 0; j < used; j++)
972  close(fd[j]);
973 
974  pfree(fd);
975 
976  /*
977  * Return results. usable_fds is just the number of successful dups. We
978  * assume that the system limit is highestfd+1 (remember 0 is a legal FD
979  * number) and so already_open is highestfd+1 - usable_fds.
980  */
981  *usable_fds = used;
982  *already_open = highestfd + 1 - used;
983 }
984 
985 /*
986  * set_max_safe_fds
987  * Determine number of file descriptors that fd.c is allowed to use
988  */
989 void
991 {
992  int usable_fds;
993  int already_open;
994 
995  /*----------
996  * We want to set max_safe_fds to
997  * MIN(usable_fds, max_files_per_process - already_open)
998  * less the slop factor for files that are opened without consulting
999  * fd.c. This ensures that we won't exceed either max_files_per_process
1000  * or the experimentally-determined EMFILE limit.
1001  *----------
1002  */
1004  &usable_fds, &already_open);
1005 
1006  max_safe_fds = Min(usable_fds, max_files_per_process - already_open);
1007 
1008  /*
1009  * Take off the FDs reserved for system() etc.
1010  */
1012 
1013  /*
1014  * Make sure we still have enough to get by.
1015  */
1016  if (max_safe_fds < FD_MINFREE)
1017  ereport(FATAL,
1018  (errcode(ERRCODE_INSUFFICIENT_RESOURCES),
1019  errmsg("insufficient file descriptors available to start server process"),
1020  errdetail("System allows %d, we need at least %d.",
1023 
1024  elog(DEBUG2, "max_safe_fds = %d, usable_fds = %d, already_open = %d",
1025  max_safe_fds, usable_fds, already_open);
1026 }
1027 
1028 /*
1029  * Open a file with BasicOpenFilePerm() and pass default file mode for the
1030  * fileMode parameter.
1031  */
1032 int
1034 {
1035  return BasicOpenFilePerm(fileName, fileFlags, pg_file_create_mode);
1036 }
1037 
1038 /*
1039  * BasicOpenFilePerm --- same as open(2) except can free other FDs if needed
1040  *
1041  * This is exported for use by places that really want a plain kernel FD,
1042  * but need to be proof against running out of FDs. Once an FD has been
1043  * successfully returned, it is the caller's responsibility to ensure that
1044  * it will not be leaked on ereport()! Most users should *not* call this
1045  * routine directly, but instead use the VFD abstraction level, which
1046  * provides protection against descriptor leaks as well as management of
1047  * files that need to be open for more than a short period of time.
1048  *
1049  * Ideally this should be the *only* direct call of open() in the backend.
1050  * In practice, the postmaster calls open() directly, and there are some
1051  * direct open() calls done early in backend startup. Those are OK since
1052  * this module wouldn't have any open files to close at that point anyway.
1053  */
1054 int
1056 {
1057  int fd;
1058 
1059 tryAgain:
1060  fd = open(fileName, fileFlags, fileMode);
1061 
1062  if (fd >= 0)
1063  return fd; /* success! */
1064 
1065  if (errno == EMFILE || errno == ENFILE)
1066  {
1067  int save_errno = errno;
1068 
1069  ereport(LOG,
1070  (errcode(ERRCODE_INSUFFICIENT_RESOURCES),
1071  errmsg("out of file descriptors: %m; release and retry")));
1072  errno = 0;
1073  if (ReleaseLruFile())
1074  goto tryAgain;
1075  errno = save_errno;
1076  }
1077 
1078  return -1; /* failure */
1079 }
1080 
1081 /*
1082  * AcquireExternalFD - attempt to reserve an external file descriptor
1083  *
1084  * This should be used by callers that need to hold a file descriptor open
1085  * over more than a short interval, but cannot use any of the other facilities
1086  * provided by this module.
1087  *
1088  * The difference between this and the underlying ReserveExternalFD function
1089  * is that this will report failure (by setting errno and returning false)
1090  * if "too many" external FDs are already reserved. This should be used in
1091  * any code where the total number of FDs to be reserved is not predictable
1092  * and small.
1093  */
1094 bool
1096 {
1097  /*
1098  * We don't want more than max_safe_fds / 3 FDs to be consumed for
1099  * "external" FDs.
1100  */
1101  if (numExternalFDs < max_safe_fds / 3)
1102  {
1104  return true;
1105  }
1106  errno = EMFILE;
1107  return false;
1108 }
1109 
1110 /*
1111  * ReserveExternalFD - report external consumption of a file descriptor
1112  *
1113  * This should be used by callers that need to hold a file descriptor open
1114  * over more than a short interval, but cannot use any of the other facilities
1115  * provided by this module. This just tracks the use of the FD and closes
1116  * VFDs if needed to ensure we keep NUM_RESERVED_FDS FDs available.
1117  *
1118  * Call this directly only in code where failure to reserve the FD would be
1119  * fatal; for example, the WAL-writing code does so, since the alternative is
1120  * session failure. Also, it's very unwise to do so in code that could
1121  * consume more than one FD per process.
1122  *
1123  * Note: as long as everybody plays nice so that NUM_RESERVED_FDS FDs remain
1124  * available, it doesn't matter too much whether this is called before or
1125  * after actually opening the FD; but doing so beforehand reduces the risk of
1126  * an EMFILE failure if not everybody played nice. In any case, it's solely
1127  * caller's responsibility to keep the external-FD count in sync with reality.
1128  */
1129 void
1131 {
1132  /*
1133  * Release VFDs if needed to stay safe. Because we do this before
1134  * incrementing numExternalFDs, the final state will be as desired, i.e.,
1135  * nfile + numAllocatedDescs + numExternalFDs <= max_safe_fds.
1136  */
1137  ReleaseLruFiles();
1138 
1139  numExternalFDs++;
1140 }
1141 
1142 /*
1143  * ReleaseExternalFD - report release of an external file descriptor
1144  *
1145  * This is guaranteed not to change errno, so it can be used in failure paths.
1146  */
1147 void
1149 {
1150  Assert(numExternalFDs > 0);
1151  numExternalFDs--;
1152 }
1153 
1154 
1155 #if defined(FDDEBUG)
1156 
1157 static void
1158 _dump_lru(void)
1159 {
1160  int mru = VfdCache[0].lruLessRecently;
1161  Vfd *vfdP = &VfdCache[mru];
1162  char buf[2048];
1163 
1164  snprintf(buf, sizeof(buf), "LRU: MOST %d ", mru);
1165  while (mru != 0)
1166  {
1167  mru = vfdP->lruLessRecently;
1168  vfdP = &VfdCache[mru];
1169  snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%d ", mru);
1170  }
1171  snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "LEAST");
1172  elog(LOG, "%s", buf);
1173 }
1174 #endif /* FDDEBUG */
1175 
1176 static void
1178 {
1179  Vfd *vfdP;
1180 
1181  Assert(file != 0);
1182 
1183  DO_DB(elog(LOG, "Delete %d (%s)",
1184  file, VfdCache[file].fileName));
1185  DO_DB(_dump_lru());
1186 
1187  vfdP = &VfdCache[file];
1188 
1189  VfdCache[vfdP->lruLessRecently].lruMoreRecently = vfdP->lruMoreRecently;
1190  VfdCache[vfdP->lruMoreRecently].lruLessRecently = vfdP->lruLessRecently;
1191 
1192  DO_DB(_dump_lru());
1193 }
1194 
1195 static void
1197 {
1198  Vfd *vfdP;
1199 
1200  Assert(file != 0);
1201 
1202  DO_DB(elog(LOG, "LruDelete %d (%s)",
1203  file, VfdCache[file].fileName));
1204 
1205  vfdP = &VfdCache[file];
1206 
1207  /*
1208  * Close the file. We aren't expecting this to fail; if it does, better
1209  * to leak the FD than to mess up our internal state.
1210  */
1211  if (close(vfdP->fd) != 0)
1213  "could not close file \"%s\": %m", vfdP->fileName);
1214  vfdP->fd = VFD_CLOSED;
1215  --nfile;
1216 
1217  /* delete the vfd record from the LRU ring */
1218  Delete(file);
1219 }
1220 
1221 static void
1223 {
1224  Vfd *vfdP;
1225 
1226  Assert(file != 0);
1227 
1228  DO_DB(elog(LOG, "Insert %d (%s)",
1229  file, VfdCache[file].fileName));
1230  DO_DB(_dump_lru());
1231 
1232  vfdP = &VfdCache[file];
1233 
1234  vfdP->lruMoreRecently = 0;
1235  vfdP->lruLessRecently = VfdCache[0].lruLessRecently;
1236  VfdCache[0].lruLessRecently = file;
1237  VfdCache[vfdP->lruLessRecently].lruMoreRecently = file;
1238 
1239  DO_DB(_dump_lru());
1240 }
1241 
1242 /* returns 0 on success, -1 on re-open failure (with errno set) */
1243 static int
1245 {
1246  Vfd *vfdP;
1247 
1248  Assert(file != 0);
1249 
1250  DO_DB(elog(LOG, "LruInsert %d (%s)",
1251  file, VfdCache[file].fileName));
1252 
1253  vfdP = &VfdCache[file];
1254 
1255  if (FileIsNotOpen(file))
1256  {
1257  /* Close excess kernel FDs. */
1258  ReleaseLruFiles();
1259 
1260  /*
1261  * The open could still fail for lack of file descriptors, eg due to
1262  * overall system file table being full. So, be prepared to release
1263  * another FD if necessary...
1264  */
1265  vfdP->fd = BasicOpenFilePerm(vfdP->fileName, vfdP->fileFlags,
1266  vfdP->fileMode);
1267  if (vfdP->fd < 0)
1268  {
1269  DO_DB(elog(LOG, "re-open failed: %m"));
1270  return -1;
1271  }
1272  else
1273  {
1274  ++nfile;
1275  }
1276  }
1277 
1278  /*
1279  * put it at the head of the Lru ring
1280  */
1281 
1282  Insert(file);
1283 
1284  return 0;
1285 }
1286 
1287 /*
1288  * Release one kernel FD by closing the least-recently-used VFD.
1289  */
1290 static bool
1292 {
1293  DO_DB(elog(LOG, "ReleaseLruFile. Opened %d", nfile));
1294 
1295  if (nfile > 0)
1296  {
1297  /*
1298  * There are opened files and so there should be at least one used vfd
1299  * in the ring.
1300  */
1301  Assert(VfdCache[0].lruMoreRecently != 0);
1302  LruDelete(VfdCache[0].lruMoreRecently);
1303  return true; /* freed a file */
1304  }
1305  return false; /* no files available to free */
1306 }
1307 
1308 /*
1309  * Release kernel FDs as needed to get under the max_safe_fds limit.
1310  * After calling this, it's OK to try to open another file.
1311  */
1312 static void
1314 {
1316  {
1317  if (!ReleaseLruFile())
1318  break;
1319  }
1320 }
1321 
1322 static File
1324 {
1325  Index i;
1326  File file;
1327 
1328  DO_DB(elog(LOG, "AllocateVfd. Size %zu", SizeVfdCache));
1329 
1330  Assert(SizeVfdCache > 0); /* InitFileAccess not called? */
1331 
1332  if (VfdCache[0].nextFree == 0)
1333  {
1334  /*
1335  * The free list is empty so it is time to increase the size of the
1336  * array. We choose to double it each time this happens. However,
1337  * there's not much point in starting *real* small.
1338  */
1339  Size newCacheSize = SizeVfdCache * 2;
1340  Vfd *newVfdCache;
1341 
1342  if (newCacheSize < 32)
1343  newCacheSize = 32;
1344 
1345  /*
1346  * Be careful not to clobber VfdCache ptr if realloc fails.
1347  */
1348  newVfdCache = (Vfd *) realloc(VfdCache, sizeof(Vfd) * newCacheSize);
1349  if (newVfdCache == NULL)
1350  ereport(ERROR,
1351  (errcode(ERRCODE_OUT_OF_MEMORY),
1352  errmsg("out of memory")));
1353  VfdCache = newVfdCache;
1354 
1355  /*
1356  * Initialize the new entries and link them into the free list.
1357  */
1358  for (i = SizeVfdCache; i < newCacheSize; i++)
1359  {
1360  MemSet((char *) &(VfdCache[i]), 0, sizeof(Vfd));
1361  VfdCache[i].nextFree = i + 1;
1362  VfdCache[i].fd = VFD_CLOSED;
1363  }
1364  VfdCache[newCacheSize - 1].nextFree = 0;
1365  VfdCache[0].nextFree = SizeVfdCache;
1366 
1367  /*
1368  * Record the new size
1369  */
1370  SizeVfdCache = newCacheSize;
1371  }
1372 
1373  file = VfdCache[0].nextFree;
1374 
1375  VfdCache[0].nextFree = VfdCache[file].nextFree;
1376 
1377  return file;
1378 }
1379 
1380 static void
1382 {
1383  Vfd *vfdP = &VfdCache[file];
1384 
1385  DO_DB(elog(LOG, "FreeVfd: %d (%s)",
1386  file, vfdP->fileName ? vfdP->fileName : ""));
1387 
1388  if (vfdP->fileName != NULL)
1389  {
1390  free(vfdP->fileName);
1391  vfdP->fileName = NULL;
1392  }
1393  vfdP->fdstate = 0x0;
1394 
1395  vfdP->nextFree = VfdCache[0].nextFree;
1396  VfdCache[0].nextFree = file;
1397 }
1398 
1399 /* returns 0 on success, -1 on re-open failure (with errno set) */
1400 static int
1402 {
1403  int returnValue;
1404 
1405  DO_DB(elog(LOG, "FileAccess %d (%s)",
1406  file, VfdCache[file].fileName));
1407 
1408  /*
1409  * Is the file open? If not, open it and put it at the head of the LRU
1410  * ring (possibly closing the least recently used file to get an FD).
1411  */
1412 
1413  if (FileIsNotOpen(file))
1414  {
1415  returnValue = LruInsert(file);
1416  if (returnValue != 0)
1417  return returnValue;
1418  }
1419  else if (VfdCache[0].lruLessRecently != file)
1420  {
1421  /*
1422  * We now know that the file is open and that it is not the last one
1423  * accessed, so we need to move it to the head of the Lru ring.
1424  */
1425 
1426  Delete(file);
1427  Insert(file);
1428  }
1429 
1430  return 0;
1431 }
1432 
1433 /*
1434  * Called whenever a temporary file is deleted to report its size.
1435  */
1436 static void
1437 ReportTemporaryFileUsage(const char *path, off_t size)
1438 {
1439  pgstat_report_tempfile(size);
1440 
1441  if (log_temp_files >= 0)
1442  {
1443  if ((size / 1024) >= log_temp_files)
1444  ereport(LOG,
1445  (errmsg("temporary file: path \"%s\", size %lu",
1446  path, (unsigned long) size)));
1447  }
1448 }
1449 
1450 /*
1451  * Called to register a temporary file for automatic close.
1452  * ResourceOwnerEnlargeFiles(CurrentResourceOwner) must have been called
1453  * before the file was opened.
1454  */
1455 static void
1457 {
1459  VfdCache[file].resowner = CurrentResourceOwner;
1460 
1461  /* Backup mechanism for closing at end of xact. */
1462  VfdCache[file].fdstate |= FD_CLOSE_AT_EOXACT;
1464 }
1465 
1466 /*
1467  * Called when we get a shared invalidation message on some relation.
1468  */
1469 #ifdef NOT_USED
1470 void
1471 FileInvalidate(File file)
1472 {
1473  Assert(FileIsValid(file));
1474  if (!FileIsNotOpen(file))
1475  LruDelete(file);
1476 }
1477 #endif
1478 
1479 /*
1480  * Open a file with PathNameOpenFilePerm() and pass default file mode for the
1481  * fileMode parameter.
1482  */
1483 File
1485 {
1486  return PathNameOpenFilePerm(fileName, fileFlags, pg_file_create_mode);
1487 }
1488 
1489 /*
1490  * open a file in an arbitrary directory
1491  *
1492  * NB: if the passed pathname is relative (which it usually is),
1493  * it will be interpreted relative to the process' working directory
1494  * (which should always be $PGDATA when this code is running).
1495  */
1496 File
1498 {
1499  char *fnamecopy;
1500  File file;
1501  Vfd *vfdP;
1502 
1503  DO_DB(elog(LOG, "PathNameOpenFilePerm: %s %x %o",
1504  fileName, fileFlags, fileMode));
1505 
1506  /*
1507  * We need a malloc'd copy of the file name; fail cleanly if no room.
1508  */
1509  fnamecopy = strdup(fileName);
1510  if (fnamecopy == NULL)
1511  ereport(ERROR,
1512  (errcode(ERRCODE_OUT_OF_MEMORY),
1513  errmsg("out of memory")));
1514 
1515  file = AllocateVfd();
1516  vfdP = &VfdCache[file];
1517 
1518  /* Close excess kernel FDs. */
1519  ReleaseLruFiles();
1520 
1521  vfdP->fd = BasicOpenFilePerm(fileName, fileFlags, fileMode);
1522 
1523  if (vfdP->fd < 0)
1524  {
1525  int save_errno = errno;
1526 
1527  FreeVfd(file);
1528  free(fnamecopy);
1529  errno = save_errno;
1530  return -1;
1531  }
1532  ++nfile;
1533  DO_DB(elog(LOG, "PathNameOpenFile: success %d",
1534  vfdP->fd));
1535 
1536  vfdP->fileName = fnamecopy;
1537  /* Saved flags are adjusted to be OK for re-opening file */
1538  vfdP->fileFlags = fileFlags & ~(O_CREAT | O_TRUNC | O_EXCL);
1539  vfdP->fileMode = fileMode;
1540  vfdP->fileSize = 0;
1541  vfdP->fdstate = 0x0;
1542  vfdP->resowner = NULL;
1543 
1544  Insert(file);
1545 
1546  return file;
1547 }
1548 
1549 /*
1550  * Create directory 'directory'. If necessary, create 'basedir', which must
1551  * be the directory above it. This is designed for creating the top-level
1552  * temporary directory on demand before creating a directory underneath it.
1553  * Do nothing if the directory already exists.
1554  *
1555  * Directories created within the top-level temporary directory should begin
1556  * with PG_TEMP_FILE_PREFIX, so that they can be identified as temporary and
1557  * deleted at startup by RemovePgTempFiles(). Further subdirectories below
1558  * that do not need any particular prefix.
1559 */
1560 void
1562 {
1563  if (MakePGDirectory(directory) < 0)
1564  {
1565  if (errno == EEXIST)
1566  return;
1567 
1568  /*
1569  * Failed. Try to create basedir first in case it's missing. Tolerate
1570  * EEXIST to close a race against another process following the same
1571  * algorithm.
1572  */
1573  if (MakePGDirectory(basedir) < 0 && errno != EEXIST)
1574  ereport(ERROR,
1576  errmsg("cannot create temporary directory \"%s\": %m",
1577  basedir)));
1578 
1579  /* Try again. */
1580  if (MakePGDirectory(directory) < 0 && errno != EEXIST)
1581  ereport(ERROR,
1583  errmsg("cannot create temporary subdirectory \"%s\": %m",
1584  directory)));
1585  }
1586 }
1587 
1588 /*
1589  * Delete a directory and everything in it, if it exists.
1590  */
1591 void
1592 PathNameDeleteTemporaryDir(const char *dirname)
1593 {
1594  struct stat statbuf;
1595 
1596  /* Silently ignore missing directory. */
1597  if (stat(dirname, &statbuf) != 0 && errno == ENOENT)
1598  return;
1599 
1600  /*
1601  * Currently, walkdir doesn't offer a way for our passed in function to
1602  * maintain state. Perhaps it should, so that we could tell the caller
1603  * whether this operation succeeded or failed. Since this operation is
1604  * used in a cleanup path, we wouldn't actually behave differently: we'll
1605  * just log failures.
1606  */
1607  walkdir(dirname, unlink_if_exists_fname, false, LOG);
1608 }
1609 
1610 /*
1611  * Open a temporary file that will disappear when we close it.
1612  *
1613  * This routine takes care of generating an appropriate tempfile name.
1614  * There's no need to pass in fileFlags or fileMode either, since only
1615  * one setting makes any sense for a temp file.
1616  *
1617  * Unless interXact is true, the file is remembered by CurrentResourceOwner
1618  * to ensure it's closed and deleted when it's no longer needed, typically at
1619  * the end-of-transaction. In most cases, you don't want temporary files to
1620  * outlive the transaction that created them, so this should be false -- but
1621  * if you need "somewhat" temporary storage, this might be useful. In either
1622  * case, the file is removed when the File is explicitly closed.
1623  */
1624 File
1625 OpenTemporaryFile(bool interXact)
1626 {
1627  File file = 0;
1628 
1629  /*
1630  * Make sure the current resource owner has space for this File before we
1631  * open it, if we'll be registering it below.
1632  */
1633  if (!interXact)
1635 
1636  /*
1637  * If some temp tablespace(s) have been given to us, try to use the next
1638  * one. If a given tablespace can't be found, we silently fall back to
1639  * the database's default tablespace.
1640  *
1641  * BUT: if the temp file is slated to outlive the current transaction,
1642  * force it into the database's default tablespace, so that it will not
1643  * pose a threat to possible tablespace drop attempts.
1644  */
1645  if (numTempTableSpaces > 0 && !interXact)
1646  {
1647  Oid tblspcOid = GetNextTempTableSpace();
1648 
1649  if (OidIsValid(tblspcOid))
1650  file = OpenTemporaryFileInTablespace(tblspcOid, false);
1651  }
1652 
1653  /*
1654  * If not, or if tablespace is bad, create in database's default
1655  * tablespace. MyDatabaseTableSpace should normally be set before we get
1656  * here, but just in case it isn't, fall back to pg_default tablespace.
1657  */
1658  if (file <= 0)
1661  DEFAULTTABLESPACE_OID,
1662  true);
1663 
1664  /* Mark it for deletion at close and temporary file size limit */
1665  VfdCache[file].fdstate |= FD_DELETE_AT_CLOSE | FD_TEMP_FILE_LIMIT;
1666 
1667  /* Register it with the current resource owner */
1668  if (!interXact)
1669  RegisterTemporaryFile(file);
1670 
1671  return file;
1672 }
1673 
1674 /*
1675  * Return the path of the temp directory in a given tablespace.
1676  */
1677 void
1679 {
1680  /*
1681  * Identify the tempfile directory for this tablespace.
1682  *
1683  * If someone tries to specify pg_global, use pg_default instead.
1684  */
1685  if (tablespace == InvalidOid ||
1686  tablespace == DEFAULTTABLESPACE_OID ||
1687  tablespace == GLOBALTABLESPACE_OID)
1688  snprintf(path, MAXPGPATH, "base/%s", PG_TEMP_FILES_DIR);
1689  else
1690  {
1691  /* All other tablespaces are accessed via symlinks */
1692  snprintf(path, MAXPGPATH, "pg_tblspc/%u/%s/%s",
1693  tablespace, TABLESPACE_VERSION_DIRECTORY,
1695  }
1696 }
1697 
1698 /*
1699  * Open a temporary file in a specific tablespace.
1700  * Subroutine for OpenTemporaryFile, which see for details.
1701  */
1702 static File
1703 OpenTemporaryFileInTablespace(Oid tblspcOid, bool rejectError)
1704 {
1705  char tempdirpath[MAXPGPATH];
1706  char tempfilepath[MAXPGPATH];
1707  File file;
1708 
1709  TempTablespacePath(tempdirpath, tblspcOid);
1710 
1711  /*
1712  * Generate a tempfile name that should be unique within the current
1713  * database instance.
1714  */
1715  snprintf(tempfilepath, sizeof(tempfilepath), "%s/%s%d.%ld",
1716  tempdirpath, PG_TEMP_FILE_PREFIX, MyProcPid, tempFileCounter++);
1717 
1718  /*
1719  * Open the file. Note: we don't use O_EXCL, in case there is an orphaned
1720  * temp file that can be reused.
1721  */
1722  file = PathNameOpenFile(tempfilepath,
1723  O_RDWR | O_CREAT | O_TRUNC | PG_BINARY);
1724  if (file <= 0)
1725  {
1726  /*
1727  * We might need to create the tablespace's tempfile directory, if no
1728  * one has yet done so.
1729  *
1730  * Don't check for an error from MakePGDirectory; it could fail if
1731  * someone else just did the same thing. If it doesn't work then
1732  * we'll bomb out on the second create attempt, instead.
1733  */
1734  (void) MakePGDirectory(tempdirpath);
1735 
1736  file = PathNameOpenFile(tempfilepath,
1737  O_RDWR | O_CREAT | O_TRUNC | PG_BINARY);
1738  if (file <= 0 && rejectError)
1739  elog(ERROR, "could not create temporary file \"%s\": %m",
1740  tempfilepath);
1741  }
1742 
1743  return file;
1744 }
1745 
1746 
1747 /*
1748  * Create a new file. The directory containing it must already exist. Files
1749  * created this way are subject to temp_file_limit and are automatically
1750  * closed at end of transaction, but are not automatically deleted on close
1751  * because they are intended to be shared between cooperating backends.
1752  *
1753  * If the file is inside the top-level temporary directory, its name should
1754  * begin with PG_TEMP_FILE_PREFIX so that it can be identified as temporary
1755  * and deleted at startup by RemovePgTempFiles(). Alternatively, it can be
1756  * inside a directory created with PathNameCreateTemporaryDir(), in which case
1757  * the prefix isn't needed.
1758  */
1759 File
1760 PathNameCreateTemporaryFile(const char *path, bool error_on_failure)
1761 {
1762  File file;
1763 
1765 
1766  /*
1767  * Open the file. Note: we don't use O_EXCL, in case there is an orphaned
1768  * temp file that can be reused.
1769  */
1770  file = PathNameOpenFile(path, O_RDWR | O_CREAT | O_TRUNC | PG_BINARY);
1771  if (file <= 0)
1772  {
1773  if (error_on_failure)
1774  ereport(ERROR,
1776  errmsg("could not create temporary file \"%s\": %m",
1777  path)));
1778  else
1779  return file;
1780  }
1781 
1782  /* Mark it for temp_file_limit accounting. */
1783  VfdCache[file].fdstate |= FD_TEMP_FILE_LIMIT;
1784 
1785  /* Register it for automatic close. */
1786  RegisterTemporaryFile(file);
1787 
1788  return file;
1789 }
1790 
1791 /*
1792  * Open a file that was created with PathNameCreateTemporaryFile, possibly in
1793  * another backend. Files opened this way don't count against the
1794  * temp_file_limit of the caller, are automatically closed at the end of the
1795  * transaction but are not deleted on close.
1796  */
1797 File
1798 PathNameOpenTemporaryFile(const char *path, int mode)
1799 {
1800  File file;
1801 
1803 
1804  file = PathNameOpenFile(path, mode | PG_BINARY);
1805 
1806  /* If no such file, then we don't raise an error. */
1807  if (file <= 0 && errno != ENOENT)
1808  ereport(ERROR,
1810  errmsg("could not open temporary file \"%s\": %m",
1811  path)));
1812 
1813  if (file > 0)
1814  {
1815  /* Register it for automatic close. */
1816  RegisterTemporaryFile(file);
1817  }
1818 
1819  return file;
1820 }
1821 
1822 /*
1823  * Delete a file by pathname. Return true if the file existed, false if
1824  * didn't.
1825  */
1826 bool
1827 PathNameDeleteTemporaryFile(const char *path, bool error_on_failure)
1828 {
1829  struct stat filestats;
1830  int stat_errno;
1831 
1832  /* Get the final size for pgstat reporting. */
1833  if (stat(path, &filestats) != 0)
1834  stat_errno = errno;
1835  else
1836  stat_errno = 0;
1837 
1838  /*
1839  * Unlike FileClose's automatic file deletion code, we tolerate
1840  * non-existence to support BufFileDeleteShared which doesn't know how
1841  * many segments it has to delete until it runs out.
1842  */
1843  if (stat_errno == ENOENT)
1844  return false;
1845 
1846  if (unlink(path) < 0)
1847  {
1848  if (errno != ENOENT)
1849  ereport(error_on_failure ? ERROR : LOG,
1851  errmsg("could not unlink temporary file \"%s\": %m",
1852  path)));
1853  return false;
1854  }
1855 
1856  if (stat_errno == 0)
1857  ReportTemporaryFileUsage(path, filestats.st_size);
1858  else
1859  {
1860  errno = stat_errno;
1861  ereport(LOG,
1863  errmsg("could not stat file \"%s\": %m", path)));
1864  }
1865 
1866  return true;
1867 }
1868 
1869 /*
1870  * close a file when done with it
1871  */
1872 void
1874 {
1875  Vfd *vfdP;
1876 
1877  Assert(FileIsValid(file));
1878 
1879  DO_DB(elog(LOG, "FileClose: %d (%s)",
1880  file, VfdCache[file].fileName));
1881 
1882  vfdP = &VfdCache[file];
1883 
1884  if (!FileIsNotOpen(file))
1885  {
1886  /* close the file */
1887  if (close(vfdP->fd) != 0)
1888  {
1889  /*
1890  * We may need to panic on failure to close non-temporary files;
1891  * see LruDelete.
1892  */
1894  "could not close file \"%s\": %m", vfdP->fileName);
1895  }
1896 
1897  --nfile;
1898  vfdP->fd = VFD_CLOSED;
1899 
1900  /* remove the file from the lru ring */
1901  Delete(file);
1902  }
1903 
1904  if (vfdP->fdstate & FD_TEMP_FILE_LIMIT)
1905  {
1906  /* Subtract its size from current usage (do first in case of error) */
1907  temporary_files_size -= vfdP->fileSize;
1908  vfdP->fileSize = 0;
1909  }
1910 
1911  /*
1912  * Delete the file if it was temporary, and make a log entry if wanted
1913  */
1914  if (vfdP->fdstate & FD_DELETE_AT_CLOSE)
1915  {
1916  struct stat filestats;
1917  int stat_errno;
1918 
1919  /*
1920  * If we get an error, as could happen within the ereport/elog calls,
1921  * we'll come right back here during transaction abort. Reset the
1922  * flag to ensure that we can't get into an infinite loop. This code
1923  * is arranged to ensure that the worst-case consequence is failing to
1924  * emit log message(s), not failing to attempt the unlink.
1925  */
1926  vfdP->fdstate &= ~FD_DELETE_AT_CLOSE;
1927 
1928 
1929  /* first try the stat() */
1930  if (stat(vfdP->fileName, &filestats))
1931  stat_errno = errno;
1932  else
1933  stat_errno = 0;
1934 
1935  /* in any case do the unlink */
1936  if (unlink(vfdP->fileName))
1937  ereport(LOG,
1939  errmsg("could not delete file \"%s\": %m", vfdP->fileName)));
1940 
1941  /* and last report the stat results */
1942  if (stat_errno == 0)
1943  ReportTemporaryFileUsage(vfdP->fileName, filestats.st_size);
1944  else
1945  {
1946  errno = stat_errno;
1947  ereport(LOG,
1949  errmsg("could not stat file \"%s\": %m", vfdP->fileName)));
1950  }
1951  }
1952 
1953  /* Unregister it from the resource owner */
1954  if (vfdP->resowner)
1955  ResourceOwnerForgetFile(vfdP->resowner, file);
1956 
1957  /*
1958  * Return the Vfd slot to the free list
1959  */
1960  FreeVfd(file);
1961 }
1962 
1963 /*
1964  * FilePrefetch - initiate asynchronous read of a given range of the file.
1965  *
1966  * Currently the only implementation of this function is using posix_fadvise
1967  * which is the simplest standardized interface that accomplishes this.
1968  * We could add an implementation using libaio in the future; but note that
1969  * this API is inappropriate for libaio, which wants to have a buffer provided
1970  * to read into.
1971  */
1972 int
1973 FilePrefetch(File file, off_t offset, int amount, uint32 wait_event_info)
1974 {
1975 #if defined(USE_POSIX_FADVISE) && defined(POSIX_FADV_WILLNEED)
1976  int returnCode;
1977 
1978  Assert(FileIsValid(file));
1979 
1980  DO_DB(elog(LOG, "FilePrefetch: %d (%s) " INT64_FORMAT " %d",
1981  file, VfdCache[file].fileName,
1982  (int64) offset, amount));
1983 
1984  returnCode = FileAccess(file);
1985  if (returnCode < 0)
1986  return returnCode;
1987 
1988  pgstat_report_wait_start(wait_event_info);
1989  returnCode = posix_fadvise(VfdCache[file].fd, offset, amount,
1990  POSIX_FADV_WILLNEED);
1992 
1993  return returnCode;
1994 #else
1995  Assert(FileIsValid(file));
1996  return 0;
1997 #endif
1998 }
1999 
2000 void
2001 FileWriteback(File file, off_t offset, off_t nbytes, uint32 wait_event_info)
2002 {
2003  int returnCode;
2004 
2005  Assert(FileIsValid(file));
2006 
2007  DO_DB(elog(LOG, "FileWriteback: %d (%s) " INT64_FORMAT " " INT64_FORMAT,
2008  file, VfdCache[file].fileName,
2009  (int64) offset, (int64) nbytes));
2010 
2011  if (nbytes <= 0)
2012  return;
2013 
2014  returnCode = FileAccess(file);
2015  if (returnCode < 0)
2016  return;
2017 
2018  pgstat_report_wait_start(wait_event_info);
2019  pg_flush_data(VfdCache[file].fd, offset, nbytes);
2021 }
2022 
2023 int
2024 FileRead(File file, char *buffer, int amount, off_t offset,
2025  uint32 wait_event_info)
2026 {
2027  int returnCode;
2028  Vfd *vfdP;
2029 
2030  Assert(FileIsValid(file));
2031 
2032  DO_DB(elog(LOG, "FileRead: %d (%s) " INT64_FORMAT " %d %p",
2033  file, VfdCache[file].fileName,
2034  (int64) offset,
2035  amount, buffer));
2036 
2037  returnCode = FileAccess(file);
2038  if (returnCode < 0)
2039  return returnCode;
2040 
2041  vfdP = &VfdCache[file];
2042 
2043 retry:
2044  pgstat_report_wait_start(wait_event_info);
2045  returnCode = pg_pread(vfdP->fd, buffer, amount, offset);
2047 
2048  if (returnCode < 0)
2049  {
2050  /*
2051  * Windows may run out of kernel buffers and return "Insufficient
2052  * system resources" error. Wait a bit and retry to solve it.
2053  *
2054  * It is rumored that EINTR is also possible on some Unix filesystems,
2055  * in which case immediate retry is indicated.
2056  */
2057 #ifdef WIN32
2058  DWORD error = GetLastError();
2059 
2060  switch (error)
2061  {
2062  case ERROR_NO_SYSTEM_RESOURCES:
2063  pg_usleep(1000L);
2064  errno = EINTR;
2065  break;
2066  default:
2067  _dosmaperr(error);
2068  break;
2069  }
2070 #endif
2071  /* OK to retry if interrupted */
2072  if (errno == EINTR)
2073  goto retry;
2074  }
2075 
2076  return returnCode;
2077 }
2078 
2079 int
2080 FileWrite(File file, char *buffer, int amount, off_t offset,
2081  uint32 wait_event_info)
2082 {
2083  int returnCode;
2084  Vfd *vfdP;
2085 
2086  Assert(FileIsValid(file));
2087 
2088  DO_DB(elog(LOG, "FileWrite: %d (%s) " INT64_FORMAT " %d %p",
2089  file, VfdCache[file].fileName,
2090  (int64) offset,
2091  amount, buffer));
2092 
2093  returnCode = FileAccess(file);
2094  if (returnCode < 0)
2095  return returnCode;
2096 
2097  vfdP = &VfdCache[file];
2098 
2099  /*
2100  * If enforcing temp_file_limit and it's a temp file, check to see if the
2101  * write would overrun temp_file_limit, and throw error if so. Note: it's
2102  * really a modularity violation to throw error here; we should set errno
2103  * and return -1. However, there's no way to report a suitable error
2104  * message if we do that. All current callers would just throw error
2105  * immediately anyway, so this is safe at present.
2106  */
2107  if (temp_file_limit >= 0 && (vfdP->fdstate & FD_TEMP_FILE_LIMIT))
2108  {
2109  off_t past_write = offset + amount;
2110 
2111  if (past_write > vfdP->fileSize)
2112  {
2113  uint64 newTotal = temporary_files_size;
2114 
2115  newTotal += past_write - vfdP->fileSize;
2116  if (newTotal > (uint64) temp_file_limit * (uint64) 1024)
2117  ereport(ERROR,
2118  (errcode(ERRCODE_CONFIGURATION_LIMIT_EXCEEDED),
2119  errmsg("temporary file size exceeds temp_file_limit (%dkB)",
2120  temp_file_limit)));
2121  }
2122  }
2123 
2124 retry:
2125  errno = 0;
2126  pgstat_report_wait_start(wait_event_info);
2127  returnCode = pg_pwrite(VfdCache[file].fd, buffer, amount, offset);
2129 
2130  /* if write didn't set errno, assume problem is no disk space */
2131  if (returnCode != amount && errno == 0)
2132  errno = ENOSPC;
2133 
2134  if (returnCode >= 0)
2135  {
2136  /*
2137  * Maintain fileSize and temporary_files_size if it's a temp file.
2138  */
2139  if (vfdP->fdstate & FD_TEMP_FILE_LIMIT)
2140  {
2141  off_t past_write = offset + amount;
2142 
2143  if (past_write > vfdP->fileSize)
2144  {
2145  temporary_files_size += past_write - vfdP->fileSize;
2146  vfdP->fileSize = past_write;
2147  }
2148  }
2149  }
2150  else
2151  {
2152  /*
2153  * See comments in FileRead()
2154  */
2155 #ifdef WIN32
2156  DWORD error = GetLastError();
2157 
2158  switch (error)
2159  {
2160  case ERROR_NO_SYSTEM_RESOURCES:
2161  pg_usleep(1000L);
2162  errno = EINTR;
2163  break;
2164  default:
2165  _dosmaperr(error);
2166  break;
2167  }
2168 #endif
2169  /* OK to retry if interrupted */
2170  if (errno == EINTR)
2171  goto retry;
2172  }
2173 
2174  return returnCode;
2175 }
2176 
2177 int
2178 FileSync(File file, uint32 wait_event_info)
2179 {
2180  int returnCode;
2181 
2182  Assert(FileIsValid(file));
2183 
2184  DO_DB(elog(LOG, "FileSync: %d (%s)",
2185  file, VfdCache[file].fileName));
2186 
2187  returnCode = FileAccess(file);
2188  if (returnCode < 0)
2189  return returnCode;
2190 
2191  pgstat_report_wait_start(wait_event_info);
2192  returnCode = pg_fsync(VfdCache[file].fd);
2194 
2195  return returnCode;
2196 }
2197 
2198 off_t
2200 {
2201  Assert(FileIsValid(file));
2202 
2203  DO_DB(elog(LOG, "FileSize %d (%s)",
2204  file, VfdCache[file].fileName));
2205 
2206  if (FileIsNotOpen(file))
2207  {
2208  if (FileAccess(file) < 0)
2209  return (off_t) -1;
2210  }
2211 
2212  return lseek(VfdCache[file].fd, 0, SEEK_END);
2213 }
2214 
2215 int
2216 FileTruncate(File file, off_t offset, uint32 wait_event_info)
2217 {
2218  int returnCode;
2219 
2220  Assert(FileIsValid(file));
2221 
2222  DO_DB(elog(LOG, "FileTruncate %d (%s)",
2223  file, VfdCache[file].fileName));
2224 
2225  returnCode = FileAccess(file);
2226  if (returnCode < 0)
2227  return returnCode;
2228 
2229  pgstat_report_wait_start(wait_event_info);
2230  returnCode = ftruncate(VfdCache[file].fd, offset);
2232 
2233  if (returnCode == 0 && VfdCache[file].fileSize > offset)
2234  {
2235  /* adjust our state for truncation of a temp file */
2236  Assert(VfdCache[file].fdstate & FD_TEMP_FILE_LIMIT);
2237  temporary_files_size -= VfdCache[file].fileSize - offset;
2238  VfdCache[file].fileSize = offset;
2239  }
2240 
2241  return returnCode;
2242 }
2243 
2244 /*
2245  * Return the pathname associated with an open file.
2246  *
2247  * The returned string points to an internal buffer, which is valid until
2248  * the file is closed.
2249  */
2250 char *
2252 {
2253  Assert(FileIsValid(file));
2254 
2255  return VfdCache[file].fileName;
2256 }
2257 
2258 /*
2259  * Return the raw file descriptor of an opened file.
2260  *
2261  * The returned file descriptor will be valid until the file is closed, but
2262  * there are a lot of things that can make that happen. So the caller should
2263  * be careful not to do much of anything else before it finishes using the
2264  * returned file descriptor.
2265  */
2266 int
2268 {
2269  Assert(FileIsValid(file));
2270  return VfdCache[file].fd;
2271 }
2272 
2273 /*
2274  * FileGetRawFlags - returns the file flags on open(2)
2275  */
2276 int
2278 {
2279  Assert(FileIsValid(file));
2280  return VfdCache[file].fileFlags;
2281 }
2282 
2283 /*
2284  * FileGetRawMode - returns the mode bitmask passed to open(2)
2285  */
2286 mode_t
2288 {
2289  Assert(FileIsValid(file));
2290  return VfdCache[file].fileMode;
2291 }
2292 
2293 /*
2294  * Make room for another allocatedDescs[] array entry if needed and possible.
2295  * Returns true if an array element is available.
2296  */
2297 static bool
2299 {
2300  AllocateDesc *newDescs;
2301  int newMax;
2302 
2303  /* Quick out if array already has a free slot. */
2305  return true;
2306 
2307  /*
2308  * If the array hasn't yet been created in the current process, initialize
2309  * it with FD_MINFREE / 3 elements. In many scenarios this is as many as
2310  * we will ever need, anyway. We don't want to look at max_safe_fds
2311  * immediately because set_max_safe_fds() may not have run yet.
2312  */
2313  if (allocatedDescs == NULL)
2314  {
2315  newMax = FD_MINFREE / 3;
2316  newDescs = (AllocateDesc *) malloc(newMax * sizeof(AllocateDesc));
2317  /* Out of memory already? Treat as fatal error. */
2318  if (newDescs == NULL)
2319  ereport(ERROR,
2320  (errcode(ERRCODE_OUT_OF_MEMORY),
2321  errmsg("out of memory")));
2322  allocatedDescs = newDescs;
2323  maxAllocatedDescs = newMax;
2324  return true;
2325  }
2326 
2327  /*
2328  * Consider enlarging the array beyond the initial allocation used above.
2329  * By the time this happens, max_safe_fds should be known accurately.
2330  *
2331  * We mustn't let allocated descriptors hog all the available FDs, and in
2332  * practice we'd better leave a reasonable number of FDs for VFD use. So
2333  * set the maximum to max_safe_fds / 3. (This should certainly be at
2334  * least as large as the initial size, FD_MINFREE / 3, so we aren't
2335  * tightening the restriction here.) Recall that "external" FDs are
2336  * allowed to consume another third of max_safe_fds.
2337  */
2338  newMax = max_safe_fds / 3;
2339  if (newMax > maxAllocatedDescs)
2340  {
2341  newDescs = (AllocateDesc *) realloc(allocatedDescs,
2342  newMax * sizeof(AllocateDesc));
2343  /* Treat out-of-memory as a non-fatal error. */
2344  if (newDescs == NULL)
2345  return false;
2346  allocatedDescs = newDescs;
2347  maxAllocatedDescs = newMax;
2348  return true;
2349  }
2350 
2351  /* Can't enlarge allocatedDescs[] any more. */
2352  return false;
2353 }
2354 
2355 /*
2356  * Routines that want to use stdio (ie, FILE*) should use AllocateFile
2357  * rather than plain fopen(). This lets fd.c deal with freeing FDs if
2358  * necessary to open the file. When done, call FreeFile rather than fclose.
2359  *
2360  * Note that files that will be open for any significant length of time
2361  * should NOT be handled this way, since they cannot share kernel file
2362  * descriptors with other files; there is grave risk of running out of FDs
2363  * if anyone locks down too many FDs. Most callers of this routine are
2364  * simply reading a config file that they will read and close immediately.
2365  *
2366  * fd.c will automatically close all files opened with AllocateFile at
2367  * transaction commit or abort; this prevents FD leakage if a routine
2368  * that calls AllocateFile is terminated prematurely by ereport(ERROR).
2369  *
2370  * Ideally this should be the *only* direct call of fopen() in the backend.
2371  */
2372 FILE *
2373 AllocateFile(const char *name, const char *mode)
2374 {
2375  FILE *file;
2376 
2377  DO_DB(elog(LOG, "AllocateFile: Allocated %d (%s)",
2378  numAllocatedDescs, name));
2379 
2380  /* Can we allocate another non-virtual FD? */
2381  if (!reserveAllocatedDesc())
2382  ereport(ERROR,
2383  (errcode(ERRCODE_INSUFFICIENT_RESOURCES),
2384  errmsg("exceeded maxAllocatedDescs (%d) while trying to open file \"%s\"",
2385  maxAllocatedDescs, name)));
2386 
2387  /* Close excess kernel FDs. */
2388  ReleaseLruFiles();
2389 
2390 TryAgain:
2391  if ((file = fopen(name, mode)) != NULL)
2392  {
2393  AllocateDesc *desc = &allocatedDescs[numAllocatedDescs];
2394 
2395  desc->kind = AllocateDescFile;
2396  desc->desc.file = file;
2399  return desc->desc.file;
2400  }
2401 
2402  if (errno == EMFILE || errno == ENFILE)
2403  {
2404  int save_errno = errno;
2405 
2406  ereport(LOG,
2407  (errcode(ERRCODE_INSUFFICIENT_RESOURCES),
2408  errmsg("out of file descriptors: %m; release and retry")));
2409  errno = 0;
2410  if (ReleaseLruFile())
2411  goto TryAgain;
2412  errno = save_errno;
2413  }
2414 
2415  return NULL;
2416 }
2417 
2418 /*
2419  * Open a file with OpenTransientFilePerm() and pass default file mode for
2420  * the fileMode parameter.
2421  */
2422 int
2424 {
2425  return OpenTransientFilePerm(fileName, fileFlags, pg_file_create_mode);
2426 }
2427 
2428 /*
2429  * Like AllocateFile, but returns an unbuffered fd like open(2)
2430  */
2431 int
2433 {
2434  int fd;
2435 
2436  DO_DB(elog(LOG, "OpenTransientFile: Allocated %d (%s)",
2437  numAllocatedDescs, fileName));
2438 
2439  /* Can we allocate another non-virtual FD? */
2440  if (!reserveAllocatedDesc())
2441  ereport(ERROR,
2442  (errcode(ERRCODE_INSUFFICIENT_RESOURCES),
2443  errmsg("exceeded maxAllocatedDescs (%d) while trying to open file \"%s\"",
2444  maxAllocatedDescs, fileName)));
2445 
2446  /* Close excess kernel FDs. */
2447  ReleaseLruFiles();
2448 
2449  fd = BasicOpenFilePerm(fileName, fileFlags, fileMode);
2450 
2451  if (fd >= 0)
2452  {
2453  AllocateDesc *desc = &allocatedDescs[numAllocatedDescs];
2454 
2455  desc->kind = AllocateDescRawFD;
2456  desc->desc.fd = fd;
2459 
2460  return fd;
2461  }
2462 
2463  return -1; /* failure */
2464 }
2465 
2466 /*
2467  * Routines that want to initiate a pipe stream should use OpenPipeStream
2468  * rather than plain popen(). This lets fd.c deal with freeing FDs if
2469  * necessary. When done, call ClosePipeStream rather than pclose.
2470  *
2471  * This function also ensures that the popen'd program is run with default
2472  * SIGPIPE processing, rather than the SIG_IGN setting the backend normally
2473  * uses. This ensures desirable response to, eg, closing a read pipe early.
2474  */
2475 FILE *
2476 OpenPipeStream(const char *command, const char *mode)
2477 {
2478  FILE *file;
2479  int save_errno;
2480 
2481  DO_DB(elog(LOG, "OpenPipeStream: Allocated %d (%s)",
2482  numAllocatedDescs, command));
2483 
2484  /* Can we allocate another non-virtual FD? */
2485  if (!reserveAllocatedDesc())
2486  ereport(ERROR,
2487  (errcode(ERRCODE_INSUFFICIENT_RESOURCES),
2488  errmsg("exceeded maxAllocatedDescs (%d) while trying to execute command \"%s\"",
2489  maxAllocatedDescs, command)));
2490 
2491  /* Close excess kernel FDs. */
2492  ReleaseLruFiles();
2493 
2494 TryAgain:
2495  fflush(stdout);
2496  fflush(stderr);
2498  errno = 0;
2499  file = popen(command, mode);
2500  save_errno = errno;
2502  errno = save_errno;
2503  if (file != NULL)
2504  {
2505  AllocateDesc *desc = &allocatedDescs[numAllocatedDescs];
2506 
2507  desc->kind = AllocateDescPipe;
2508  desc->desc.file = file;
2511  return desc->desc.file;
2512  }
2513 
2514  if (errno == EMFILE || errno == ENFILE)
2515  {
2516  ereport(LOG,
2517  (errcode(ERRCODE_INSUFFICIENT_RESOURCES),
2518  errmsg("out of file descriptors: %m; release and retry")));
2519  if (ReleaseLruFile())
2520  goto TryAgain;
2521  errno = save_errno;
2522  }
2523 
2524  return NULL;
2525 }
2526 
2527 /*
2528  * Free an AllocateDesc of any type.
2529  *
2530  * The argument *must* point into the allocatedDescs[] array.
2531  */
2532 static int
2534 {
2535  int result;
2536 
2537  /* Close the underlying object */
2538  switch (desc->kind)
2539  {
2540  case AllocateDescFile:
2541  result = fclose(desc->desc.file);
2542  break;
2543  case AllocateDescPipe:
2544  result = pclose(desc->desc.file);
2545  break;
2546  case AllocateDescDir:
2547  result = closedir(desc->desc.dir);
2548  break;
2549  case AllocateDescRawFD:
2550  result = close(desc->desc.fd);
2551  break;
2552  default:
2553  elog(ERROR, "AllocateDesc kind not recognized");
2554  result = 0; /* keep compiler quiet */
2555  break;
2556  }
2557 
2558  /* Compact storage in the allocatedDescs array */
2560  *desc = allocatedDescs[numAllocatedDescs];
2561 
2562  return result;
2563 }
2564 
2565 /*
2566  * Close a file returned by AllocateFile.
2567  *
2568  * Note we do not check fclose's return value --- it is up to the caller
2569  * to handle close errors.
2570  */
2571 int
2572 FreeFile(FILE *file)
2573 {
2574  int i;
2575 
2576  DO_DB(elog(LOG, "FreeFile: Allocated %d", numAllocatedDescs));
2577 
2578  /* Remove file from list of allocated files, if it's present */
2579  for (i = numAllocatedDescs; --i >= 0;)
2580  {
2581  AllocateDesc *desc = &allocatedDescs[i];
2582 
2583  if (desc->kind == AllocateDescFile && desc->desc.file == file)
2584  return FreeDesc(desc);
2585  }
2586 
2587  /* Only get here if someone passes us a file not in allocatedDescs */
2588  elog(WARNING, "file passed to FreeFile was not obtained from AllocateFile");
2589 
2590  return fclose(file);
2591 }
2592 
2593 /*
2594  * Close a file returned by OpenTransientFile.
2595  *
2596  * Note we do not check close's return value --- it is up to the caller
2597  * to handle close errors.
2598  */
2599 int
2601 {
2602  int i;
2603 
2604  DO_DB(elog(LOG, "CloseTransientFile: Allocated %d", numAllocatedDescs));
2605 
2606  /* Remove fd from list of allocated files, if it's present */
2607  for (i = numAllocatedDescs; --i >= 0;)
2608  {
2609  AllocateDesc *desc = &allocatedDescs[i];
2610 
2611  if (desc->kind == AllocateDescRawFD && desc->desc.fd == fd)
2612  return FreeDesc(desc);
2613  }
2614 
2615  /* Only get here if someone passes us a file not in allocatedDescs */
2616  elog(WARNING, "fd passed to CloseTransientFile was not obtained from OpenTransientFile");
2617 
2618  return close(fd);
2619 }
2620 
2621 /*
2622  * Routines that want to use <dirent.h> (ie, DIR*) should use AllocateDir
2623  * rather than plain opendir(). This lets fd.c deal with freeing FDs if
2624  * necessary to open the directory, and with closing it after an elog.
2625  * When done, call FreeDir rather than closedir.
2626  *
2627  * Returns NULL, with errno set, on failure. Note that failure detection
2628  * is commonly left to the following call of ReadDir or ReadDirExtended;
2629  * see the comments for ReadDir.
2630  *
2631  * Ideally this should be the *only* direct call of opendir() in the backend.
2632  */
2633 DIR *
2634 AllocateDir(const char *dirname)
2635 {
2636  DIR *dir;
2637 
2638  DO_DB(elog(LOG, "AllocateDir: Allocated %d (%s)",
2639  numAllocatedDescs, dirname));
2640 
2641  /* Can we allocate another non-virtual FD? */
2642  if (!reserveAllocatedDesc())
2643  ereport(ERROR,
2644  (errcode(ERRCODE_INSUFFICIENT_RESOURCES),
2645  errmsg("exceeded maxAllocatedDescs (%d) while trying to open directory \"%s\"",
2646  maxAllocatedDescs, dirname)));
2647 
2648  /* Close excess kernel FDs. */
2649  ReleaseLruFiles();
2650 
2651 TryAgain:
2652  if ((dir = opendir(dirname)) != NULL)
2653  {
2654  AllocateDesc *desc = &allocatedDescs[numAllocatedDescs];
2655 
2656  desc->kind = AllocateDescDir;
2657  desc->desc.dir = dir;
2660  return desc->desc.dir;
2661  }
2662 
2663  if (errno == EMFILE || errno == ENFILE)
2664  {
2665  int save_errno = errno;
2666 
2667  ereport(LOG,
2668  (errcode(ERRCODE_INSUFFICIENT_RESOURCES),
2669  errmsg("out of file descriptors: %m; release and retry")));
2670  errno = 0;
2671  if (ReleaseLruFile())
2672  goto TryAgain;
2673  errno = save_errno;
2674  }
2675 
2676  return NULL;
2677 }
2678 
2679 /*
2680  * Read a directory opened with AllocateDir, ereport'ing any error.
2681  *
2682  * This is easier to use than raw readdir() since it takes care of some
2683  * otherwise rather tedious and error-prone manipulation of errno. Also,
2684  * if you are happy with a generic error message for AllocateDir failure,
2685  * you can just do
2686  *
2687  * dir = AllocateDir(path);
2688  * while ((dirent = ReadDir(dir, path)) != NULL)
2689  * process dirent;
2690  * FreeDir(dir);
2691  *
2692  * since a NULL dir parameter is taken as indicating AllocateDir failed.
2693  * (Make sure errno isn't changed between AllocateDir and ReadDir if you
2694  * use this shortcut.)
2695  *
2696  * The pathname passed to AllocateDir must be passed to this routine too,
2697  * but it is only used for error reporting.
2698  */
2699 struct dirent *
2700 ReadDir(DIR *dir, const char *dirname)
2701 {
2702  return ReadDirExtended(dir, dirname, ERROR);
2703 }
2704 
2705 /*
2706  * Alternate version of ReadDir that allows caller to specify the elevel
2707  * for any error report (whether it's reporting an initial failure of
2708  * AllocateDir or a subsequent directory read failure).
2709  *
2710  * If elevel < ERROR, returns NULL after any error. With the normal coding
2711  * pattern, this will result in falling out of the loop immediately as
2712  * though the directory contained no (more) entries.
2713  */
2714 struct dirent *
2715 ReadDirExtended(DIR *dir, const char *dirname, int elevel)
2716 {
2717  struct dirent *dent;
2718 
2719  /* Give a generic message for AllocateDir failure, if caller didn't */
2720  if (dir == NULL)
2721  {
2722  ereport(elevel,
2724  errmsg("could not open directory \"%s\": %m",
2725  dirname)));
2726  return NULL;
2727  }
2728 
2729  errno = 0;
2730  if ((dent = readdir(dir)) != NULL)
2731  return dent;
2732 
2733  if (errno)
2734  ereport(elevel,
2736  errmsg("could not read directory \"%s\": %m",
2737  dirname)));
2738  return NULL;
2739 }
2740 
2741 /*
2742  * Close a directory opened with AllocateDir.
2743  *
2744  * Returns closedir's return value (with errno set if it's not 0).
2745  * Note we do not check the return value --- it is up to the caller
2746  * to handle close errors if wanted.
2747  *
2748  * Does nothing if dir == NULL; we assume that directory open failure was
2749  * already reported if desired.
2750  */
2751 int
2753 {
2754  int i;
2755 
2756  /* Nothing to do if AllocateDir failed */
2757  if (dir == NULL)
2758  return 0;
2759 
2760  DO_DB(elog(LOG, "FreeDir: Allocated %d", numAllocatedDescs));
2761 
2762  /* Remove dir from list of allocated dirs, if it's present */
2763  for (i = numAllocatedDescs; --i >= 0;)
2764  {
2765  AllocateDesc *desc = &allocatedDescs[i];
2766 
2767  if (desc->kind == AllocateDescDir && desc->desc.dir == dir)
2768  return FreeDesc(desc);
2769  }
2770 
2771  /* Only get here if someone passes us a dir not in allocatedDescs */
2772  elog(WARNING, "dir passed to FreeDir was not obtained from AllocateDir");
2773 
2774  return closedir(dir);
2775 }
2776 
2777 
2778 /*
2779  * Close a pipe stream returned by OpenPipeStream.
2780  */
2781 int
2782 ClosePipeStream(FILE *file)
2783 {
2784  int i;
2785 
2786  DO_DB(elog(LOG, "ClosePipeStream: Allocated %d", numAllocatedDescs));
2787 
2788  /* Remove file from list of allocated files, if it's present */
2789  for (i = numAllocatedDescs; --i >= 0;)
2790  {
2791  AllocateDesc *desc = &allocatedDescs[i];
2792 
2793  if (desc->kind == AllocateDescPipe && desc->desc.file == file)
2794  return FreeDesc(desc);
2795  }
2796 
2797  /* Only get here if someone passes us a file not in allocatedDescs */
2798  elog(WARNING, "file passed to ClosePipeStream was not obtained from OpenPipeStream");
2799 
2800  return pclose(file);
2801 }
2802 
2803 /*
2804  * closeAllVfds
2805  *
2806  * Force all VFDs into the physically-closed state, so that the fewest
2807  * possible number of kernel file descriptors are in use. There is no
2808  * change in the logical state of the VFDs.
2809  */
2810 void
2812 {
2813  Index i;
2814 
2815  if (SizeVfdCache > 0)
2816  {
2817  Assert(FileIsNotOpen(0)); /* Make sure ring not corrupted */
2818  for (i = 1; i < SizeVfdCache; i++)
2819  {
2820  if (!FileIsNotOpen(i))
2821  LruDelete(i);
2822  }
2823  }
2824 }
2825 
2826 
2827 /*
2828  * SetTempTablespaces
2829  *
2830  * Define a list (actually an array) of OIDs of tablespaces to use for
2831  * temporary files. This list will be used until end of transaction,
2832  * unless this function is called again before then. It is caller's
2833  * responsibility that the passed-in array has adequate lifespan (typically
2834  * it'd be allocated in TopTransactionContext).
2835  *
2836  * Some entries of the array may be InvalidOid, indicating that the current
2837  * database's default tablespace should be used.
2838  */
2839 void
2840 SetTempTablespaces(Oid *tableSpaces, int numSpaces)
2841 {
2842  Assert(numSpaces >= 0);
2843  tempTableSpaces = tableSpaces;
2844  numTempTableSpaces = numSpaces;
2845 
2846  /*
2847  * Select a random starting point in the list. This is to minimize
2848  * conflicts between backends that are most likely sharing the same list
2849  * of temp tablespaces. Note that if we create multiple temp files in the
2850  * same transaction, we'll advance circularly through the list --- this
2851  * ensures that large temporary sort files are nicely spread across all
2852  * available tablespaces.
2853  */
2854  if (numSpaces > 1)
2855  nextTempTableSpace = random() % numSpaces;
2856  else
2857  nextTempTableSpace = 0;
2858 }
2859 
2860 /*
2861  * TempTablespacesAreSet
2862  *
2863  * Returns true if SetTempTablespaces has been called in current transaction.
2864  * (This is just so that tablespaces.c doesn't need its own per-transaction
2865  * state.)
2866  */
2867 bool
2869 {
2870  return (numTempTableSpaces >= 0);
2871 }
2872 
2873 /*
2874  * GetTempTablespaces
2875  *
2876  * Populate an array with the OIDs of the tablespaces that should be used for
2877  * temporary files. (Some entries may be InvalidOid, indicating that the
2878  * current database's default tablespace should be used.) At most numSpaces
2879  * entries will be filled.
2880  * Returns the number of OIDs that were copied into the output array.
2881  */
2882 int
2883 GetTempTablespaces(Oid *tableSpaces, int numSpaces)
2884 {
2885  int i;
2886 
2888  for (i = 0; i < numTempTableSpaces && i < numSpaces; ++i)
2889  tableSpaces[i] = tempTableSpaces[i];
2890 
2891  return i;
2892 }
2893 
2894 /*
2895  * GetNextTempTableSpace
2896  *
2897  * Select the next temp tablespace to use. A result of InvalidOid means
2898  * to use the current database's default tablespace.
2899  */
2900 Oid
2902 {
2903  if (numTempTableSpaces > 0)
2904  {
2905  /* Advance nextTempTableSpace counter with wraparound */
2907  nextTempTableSpace = 0;
2909  }
2910  return InvalidOid;
2911 }
2912 
2913 
2914 /*
2915  * AtEOSubXact_Files
2916  *
2917  * Take care of subtransaction commit/abort. At abort, we close temp files
2918  * that the subtransaction may have opened. At commit, we reassign the
2919  * files that were opened to the parent subtransaction.
2920  */
2921 void
2922 AtEOSubXact_Files(bool isCommit, SubTransactionId mySubid,
2923  SubTransactionId parentSubid)
2924 {
2925  Index i;
2926 
2927  for (i = 0; i < numAllocatedDescs; i++)
2928  {
2929  if (allocatedDescs[i].create_subid == mySubid)
2930  {
2931  if (isCommit)
2932  allocatedDescs[i].create_subid = parentSubid;
2933  else
2934  {
2935  /* have to recheck the item after FreeDesc (ugly) */
2936  FreeDesc(&allocatedDescs[i--]);
2937  }
2938  }
2939  }
2940 }
2941 
2942 /*
2943  * AtEOXact_Files
2944  *
2945  * This routine is called during transaction commit or abort. All still-open
2946  * per-transaction temporary file VFDs are closed, which also causes the
2947  * underlying files to be deleted (although they should've been closed already
2948  * by the ResourceOwner cleanup). Furthermore, all "allocated" stdio files are
2949  * closed. We also forget any transaction-local temp tablespace list.
2950  *
2951  * The isCommit flag is used only to decide whether to emit warnings about
2952  * unclosed files.
2953  */
2954 void
2955 AtEOXact_Files(bool isCommit)
2956 {
2957  CleanupTempFiles(isCommit, false);
2958  tempTableSpaces = NULL;
2959  numTempTableSpaces = -1;
2960 }
2961 
2962 /*
2963  * AtProcExit_Files
2964  *
2965  * on_proc_exit hook to clean up temp files during backend shutdown.
2966  * Here, we want to clean up *all* temp files including interXact ones.
2967  */
2968 static void
2970 {
2971  CleanupTempFiles(false, true);
2972 }
2973 
2974 /*
2975  * Close temporary files and delete their underlying files.
2976  *
2977  * isCommit: if true, this is normal transaction commit, and we don't
2978  * expect any remaining files; warn if there are some.
2979  *
2980  * isProcExit: if true, this is being called as the backend process is
2981  * exiting. If that's the case, we should remove all temporary files; if
2982  * that's not the case, we are being called for transaction commit/abort
2983  * and should only remove transaction-local temp files. In either case,
2984  * also clean up "allocated" stdio files, dirs and fds.
2985  */
2986 static void
2987 CleanupTempFiles(bool isCommit, bool isProcExit)
2988 {
2989  Index i;
2990 
2991  /*
2992  * Careful here: at proc_exit we need extra cleanup, not just
2993  * xact_temporary files.
2994  */
2995  if (isProcExit || have_xact_temporary_files)
2996  {
2997  Assert(FileIsNotOpen(0)); /* Make sure ring not corrupted */
2998  for (i = 1; i < SizeVfdCache; i++)
2999  {
3000  unsigned short fdstate = VfdCache[i].fdstate;
3001 
3002  if (((fdstate & FD_DELETE_AT_CLOSE) || (fdstate & FD_CLOSE_AT_EOXACT)) &&
3003  VfdCache[i].fileName != NULL)
3004  {
3005  /*
3006  * If we're in the process of exiting a backend process, close
3007  * all temporary files. Otherwise, only close temporary files
3008  * local to the current transaction. They should be closed by
3009  * the ResourceOwner mechanism already, so this is just a
3010  * debugging cross-check.
3011  */
3012  if (isProcExit)
3013  FileClose(i);
3014  else if (fdstate & FD_CLOSE_AT_EOXACT)
3015  {
3016  elog(WARNING,
3017  "temporary file %s not closed at end-of-transaction",
3018  VfdCache[i].fileName);
3019  FileClose(i);
3020  }
3021  }
3022  }
3023 
3024  have_xact_temporary_files = false;
3025  }
3026 
3027  /* Complain if any allocated files remain open at commit. */
3028  if (isCommit && numAllocatedDescs > 0)
3029  elog(WARNING, "%d temporary files and directories not closed at end-of-transaction",
3031 
3032  /* Clean up "allocated" stdio files, dirs and fds. */
3033  while (numAllocatedDescs > 0)
3034  FreeDesc(&allocatedDescs[0]);
3035 }
3036 
3037 
3038 /*
3039  * Remove temporary and temporary relation files left over from a prior
3040  * postmaster session
3041  *
3042  * This should be called during postmaster startup. It will forcibly
3043  * remove any leftover files created by OpenTemporaryFile and any leftover
3044  * temporary relation files created by mdcreate.
3045  *
3046  * During post-backend-crash restart cycle, this routine is called when
3047  * remove_temp_files_after_crash GUC is enabled. Multiple crashes while
3048  * queries are using temp files could result in useless storage usage that can
3049  * only be reclaimed by a service restart. The argument against enabling it is
3050  * that someone might want to examine the temporary files for debugging
3051  * purposes. This does however mean that OpenTemporaryFile had better allow for
3052  * collision with an existing temp file name.
3053  *
3054  * NOTE: this function and its subroutines generally report syscall failures
3055  * with ereport(LOG) and keep going. Removing temp files is not so critical
3056  * that we should fail to start the database when we can't do it.
3057  */
3058 void
3060 {
3061  char temp_path[MAXPGPATH + 10 + sizeof(TABLESPACE_VERSION_DIRECTORY) + sizeof(PG_TEMP_FILES_DIR)];
3062  DIR *spc_dir;
3063  struct dirent *spc_de;
3064 
3065  /*
3066  * First process temp files in pg_default ($PGDATA/base)
3067  */
3068  snprintf(temp_path, sizeof(temp_path), "base/%s", PG_TEMP_FILES_DIR);
3069  RemovePgTempFilesInDir(temp_path, true, false);
3070  RemovePgTempRelationFiles("base");
3071 
3072  /*
3073  * Cycle through temp directories for all non-default tablespaces.
3074  */
3075  spc_dir = AllocateDir("pg_tblspc");
3076 
3077  while ((spc_de = ReadDirExtended(spc_dir, "pg_tblspc", LOG)) != NULL)
3078  {
3079  if (strcmp(spc_de->d_name, ".") == 0 ||
3080  strcmp(spc_de->d_name, "..") == 0)
3081  continue;
3082 
3083  snprintf(temp_path, sizeof(temp_path), "pg_tblspc/%s/%s/%s",
3085  RemovePgTempFilesInDir(temp_path, true, false);
3086 
3087  snprintf(temp_path, sizeof(temp_path), "pg_tblspc/%s/%s",
3089  RemovePgTempRelationFiles(temp_path);
3090  }
3091 
3092  FreeDir(spc_dir);
3093 
3094  /*
3095  * In EXEC_BACKEND case there is a pgsql_tmp directory at the top level of
3096  * DataDir as well. However, that is *not* cleaned here because doing so
3097  * would create a race condition. It's done separately, earlier in
3098  * postmaster startup.
3099  */
3100 }
3101 
3102 /*
3103  * Process one pgsql_tmp directory for RemovePgTempFiles.
3104  *
3105  * If missing_ok is true, it's all right for the named directory to not exist.
3106  * Any other problem results in a LOG message. (missing_ok should be true at
3107  * the top level, since pgsql_tmp directories are not created until needed.)
3108  *
3109  * At the top level, this should be called with unlink_all = false, so that
3110  * only files matching the temporary name prefix will be unlinked. When
3111  * recursing it will be called with unlink_all = true to unlink everything
3112  * under a top-level temporary directory.
3113  *
3114  * (These two flags could be replaced by one, but it seems clearer to keep
3115  * them separate.)
3116  */
3117 void
3118 RemovePgTempFilesInDir(const char *tmpdirname, bool missing_ok, bool unlink_all)
3119 {
3120  DIR *temp_dir;
3121  struct dirent *temp_de;
3122  char rm_path[MAXPGPATH * 2];
3123 
3124  temp_dir = AllocateDir(tmpdirname);
3125 
3126  if (temp_dir == NULL && errno == ENOENT && missing_ok)
3127  return;
3128 
3129  while ((temp_de = ReadDirExtended(temp_dir, tmpdirname, LOG)) != NULL)
3130  {
3131  if (strcmp(temp_de->d_name, ".") == 0 ||
3132  strcmp(temp_de->d_name, "..") == 0)
3133  continue;
3134 
3135  snprintf(rm_path, sizeof(rm_path), "%s/%s",
3136  tmpdirname, temp_de->d_name);
3137 
3138  if (unlink_all ||
3139  strncmp(temp_de->d_name,
3141  strlen(PG_TEMP_FILE_PREFIX)) == 0)
3142  {
3143  struct stat statbuf;
3144 
3145  if (lstat(rm_path, &statbuf) < 0)
3146  {
3147  ereport(LOG,
3149  errmsg("could not stat file \"%s\": %m", rm_path)));
3150  continue;
3151  }
3152 
3153  if (S_ISDIR(statbuf.st_mode))
3154  {
3155  /* recursively remove contents, then directory itself */
3156  RemovePgTempFilesInDir(rm_path, false, true);
3157 
3158  if (rmdir(rm_path) < 0)
3159  ereport(LOG,
3161  errmsg("could not remove directory \"%s\": %m",
3162  rm_path)));
3163  }
3164  else
3165  {
3166  if (unlink(rm_path) < 0)
3167  ereport(LOG,
3169  errmsg("could not remove file \"%s\": %m",
3170  rm_path)));
3171  }
3172  }
3173  else
3174  ereport(LOG,
3175  (errmsg("unexpected file found in temporary-files directory: \"%s\"",
3176  rm_path)));
3177  }
3178 
3179  FreeDir(temp_dir);
3180 }
3181 
3182 /* Process one tablespace directory, look for per-DB subdirectories */
3183 static void
3184 RemovePgTempRelationFiles(const char *tsdirname)
3185 {
3186  DIR *ts_dir;
3187  struct dirent *de;
3188  char dbspace_path[MAXPGPATH * 2];
3189 
3190  ts_dir = AllocateDir(tsdirname);
3191 
3192  while ((de = ReadDirExtended(ts_dir, tsdirname, LOG)) != NULL)
3193  {
3194  /*
3195  * We're only interested in the per-database directories, which have
3196  * numeric names. Note that this code will also (properly) ignore "."
3197  * and "..".
3198  */
3199  if (strspn(de->d_name, "0123456789") != strlen(de->d_name))
3200  continue;
3201 
3202  snprintf(dbspace_path, sizeof(dbspace_path), "%s/%s",
3203  tsdirname, de->d_name);
3204  RemovePgTempRelationFilesInDbspace(dbspace_path);
3205  }
3206 
3207  FreeDir(ts_dir);
3208 }
3209 
3210 /* Process one per-dbspace directory for RemovePgTempRelationFiles */
3211 static void
3212 RemovePgTempRelationFilesInDbspace(const char *dbspacedirname)
3213 {
3214  DIR *dbspace_dir;
3215  struct dirent *de;
3216  char rm_path[MAXPGPATH * 2];
3217 
3218  dbspace_dir = AllocateDir(dbspacedirname);
3219 
3220  while ((de = ReadDirExtended(dbspace_dir, dbspacedirname, LOG)) != NULL)
3221  {
3222  if (!looks_like_temp_rel_name(de->d_name))
3223  continue;
3224 
3225  snprintf(rm_path, sizeof(rm_path), "%s/%s",
3226  dbspacedirname, de->d_name);
3227 
3228  if (unlink(rm_path) < 0)
3229  ereport(LOG,
3231  errmsg("could not remove file \"%s\": %m",
3232  rm_path)));
3233  }
3234 
3235  FreeDir(dbspace_dir);
3236 }
3237 
3238 /* t<digits>_<digits>, or t<digits>_<digits>_<forkname> */
3239 bool
3241 {
3242  int pos;
3243  int savepos;
3244 
3245  /* Must start with "t". */
3246  if (name[0] != 't')
3247  return false;
3248 
3249  /* Followed by a non-empty string of digits and then an underscore. */
3250  for (pos = 1; isdigit((unsigned char) name[pos]); ++pos)
3251  ;
3252  if (pos == 1 || name[pos] != '_')
3253  return false;
3254 
3255  /* Followed by another nonempty string of digits. */
3256  for (savepos = ++pos; isdigit((unsigned char) name[pos]); ++pos)
3257  ;
3258  if (savepos == pos)
3259  return false;
3260 
3261  /* We might have _forkname or .segment or both. */
3262  if (name[pos] == '_')
3263  {
3264  int forkchar = forkname_chars(&name[pos + 1], NULL);
3265 
3266  if (forkchar <= 0)
3267  return false;
3268  pos += forkchar + 1;
3269  }
3270  if (name[pos] == '.')
3271  {
3272  int segchar;
3273 
3274  for (segchar = 1; isdigit((unsigned char) name[pos + segchar]); ++segchar)
3275  ;
3276  if (segchar <= 1)
3277  return false;
3278  pos += segchar;
3279  }
3280 
3281  /* Now we should be at the end. */
3282  if (name[pos] != '\0')
3283  return false;
3284  return true;
3285 }
3286 
3287 #ifdef HAVE_SYNCFS
3288 static void
3289 do_syncfs(const char *path)
3290 {
3291  int fd;
3292 
3293  fd = OpenTransientFile(path, O_RDONLY);
3294  if (fd < 0)
3295  {
3296  ereport(LOG,
3298  errmsg("could not open %s: %m", path)));
3299  return;
3300  }
3301  if (syncfs(fd) < 0)
3302  ereport(LOG,
3304  errmsg("could not sync filesystem for \"%s\": %m", path)));
3305  CloseTransientFile(fd);
3306 }
3307 #endif
3308 
3309 /*
3310  * Issue fsync recursively on PGDATA and all its contents, or issue syncfs for
3311  * all potential filesystem, depending on recovery_init_sync_method setting.
3312  *
3313  * We fsync regular files and directories wherever they are, but we
3314  * follow symlinks only for pg_wal and immediately under pg_tblspc.
3315  * Other symlinks are presumed to point at files we're not responsible
3316  * for fsyncing, and might not have privileges to write at all.
3317  *
3318  * Errors are logged but not considered fatal; that's because this is used
3319  * only during database startup, to deal with the possibility that there are
3320  * issued-but-unsynced writes pending against the data directory. We want to
3321  * ensure that such writes reach disk before anything that's done in the new
3322  * run. However, aborting on error would result in failure to start for
3323  * harmless cases such as read-only files in the data directory, and that's
3324  * not good either.
3325  *
3326  * Note that if we previously crashed due to a PANIC on fsync(), we'll be
3327  * rewriting all changes again during recovery.
3328  *
3329  * Note we assume we're chdir'd into PGDATA to begin with.
3330  */
3331 void
3333 {
3334  bool xlog_is_symlink;
3335 
3336  /* We can skip this whole thing if fsync is disabled. */
3337  if (!enableFsync)
3338  return;
3339 
3340  /*
3341  * If pg_wal is a symlink, we'll need to recurse into it separately,
3342  * because the first walkdir below will ignore it.
3343  */
3344  xlog_is_symlink = false;
3345 
3346 #ifndef WIN32
3347  {
3348  struct stat st;
3349 
3350  if (lstat("pg_wal", &st) < 0)
3351  ereport(LOG,
3353  errmsg("could not stat file \"%s\": %m",
3354  "pg_wal")));
3355  else if (S_ISLNK(st.st_mode))
3356  xlog_is_symlink = true;
3357  }
3358 #else
3359  if (pgwin32_is_junction("pg_wal"))
3360  xlog_is_symlink = true;
3361 #endif
3362 
3363 #ifdef HAVE_SYNCFS
3365  {
3366  DIR *dir;
3367  struct dirent *de;
3368 
3369  /*
3370  * On Linux, we don't have to open every single file one by one. We
3371  * can use syncfs() to sync whole filesystems. We only expect
3372  * filesystem boundaries to exist where we tolerate symlinks, namely
3373  * pg_wal and the tablespaces, so we call syncfs() for each of those
3374  * directories.
3375  */
3376 
3377  /* Sync the top level pgdata directory. */
3378  do_syncfs(".");
3379  /* If any tablespaces are configured, sync each of those. */
3380  dir = AllocateDir("pg_tblspc");
3381  while ((de = ReadDirExtended(dir, "pg_tblspc", LOG)))
3382  {
3383  char path[MAXPGPATH];
3384 
3385  if (strcmp(de->d_name, ".") == 0 || strcmp(de->d_name, "..") == 0)
3386  continue;
3387 
3388  snprintf(path, MAXPGPATH, "pg_tblspc/%s", de->d_name);
3389  do_syncfs(path);
3390  }
3391  FreeDir(dir);
3392  /* If pg_wal is a symlink, process that too. */
3393  if (xlog_is_symlink)
3394  do_syncfs("pg_wal");
3395  return;
3396  }
3397 #endif /* !HAVE_SYNCFS */
3398 
3399  /*
3400  * If possible, hint to the kernel that we're soon going to fsync the data
3401  * directory and its contents. Errors in this step are even less
3402  * interesting than normal, so log them only at DEBUG1.
3403  */
3404 #ifdef PG_FLUSH_DATA_WORKS
3405  walkdir(".", pre_sync_fname, false, DEBUG1);
3406  if (xlog_is_symlink)
3407  walkdir("pg_wal", pre_sync_fname, false, DEBUG1);
3408  walkdir("pg_tblspc", pre_sync_fname, true, DEBUG1);
3409 #endif
3410 
3411  /*
3412  * Now we do the fsync()s in the same order.
3413  *
3414  * The main call ignores symlinks, so in addition to specially processing
3415  * pg_wal if it's a symlink, pg_tblspc has to be visited separately with
3416  * process_symlinks = true. Note that if there are any plain directories
3417  * in pg_tblspc, they'll get fsync'd twice. That's not an expected case
3418  * so we don't worry about optimizing it.
3419  */
3420  walkdir(".", datadir_fsync_fname, false, LOG);
3421  if (xlog_is_symlink)
3422  walkdir("pg_wal", datadir_fsync_fname, false, LOG);
3423  walkdir("pg_tblspc", datadir_fsync_fname, true, LOG);
3424 }
3425 
3426 /*
3427  * walkdir: recursively walk a directory, applying the action to each
3428  * regular file and directory (including the named directory itself).
3429  *
3430  * If process_symlinks is true, the action and recursion are also applied
3431  * to regular files and directories that are pointed to by symlinks in the
3432  * given directory; otherwise symlinks are ignored. Symlinks are always
3433  * ignored in subdirectories, ie we intentionally don't pass down the
3434  * process_symlinks flag to recursive calls.
3435  *
3436  * Errors are reported at level elevel, which might be ERROR or less.
3437  *
3438  * See also walkdir in file_utils.c, which is a frontend version of this
3439  * logic.
3440  */
3441 static void
3442 walkdir(const char *path,
3443  void (*action) (const char *fname, bool isdir, int elevel),
3444  bool process_symlinks,
3445  int elevel)
3446 {
3447  DIR *dir;
3448  struct dirent *de;
3449 
3450  dir = AllocateDir(path);
3451 
3452  while ((de = ReadDirExtended(dir, path, elevel)) != NULL)
3453  {
3454  char subpath[MAXPGPATH * 2];
3455 
3457 
3458  if (strcmp(de->d_name, ".") == 0 ||
3459  strcmp(de->d_name, "..") == 0)
3460  continue;
3461 
3462  snprintf(subpath, sizeof(subpath), "%s/%s", path, de->d_name);
3463 
3464  switch (get_dirent_type(subpath, de, process_symlinks, elevel))
3465  {
3466  case PGFILETYPE_REG:
3467  (*action) (subpath, false, elevel);
3468  break;
3469  case PGFILETYPE_DIR:
3470  walkdir(subpath, action, false, elevel);
3471  break;
3472  default:
3473 
3474  /*
3475  * Errors are already reported directly by get_dirent_type(),
3476  * and any remaining symlinks and unknown file types are
3477  * ignored.
3478  */
3479  break;
3480  }
3481  }
3482 
3483  FreeDir(dir); /* we ignore any error here */
3484 
3485  /*
3486  * It's important to fsync the destination directory itself as individual
3487  * file fsyncs don't guarantee that the directory entry for the file is
3488  * synced. However, skip this if AllocateDir failed; the action function
3489  * might not be robust against that.
3490  */
3491  if (dir)
3492  (*action) (path, true, elevel);
3493 }
3494 
3495 
3496 /*
3497  * Hint to the OS that it should get ready to fsync() this file.
3498  *
3499  * Ignores errors trying to open unreadable files, and logs other errors at a
3500  * caller-specified level.
3501  */
3502 #ifdef PG_FLUSH_DATA_WORKS
3503 
3504 static void
3505 pre_sync_fname(const char *fname, bool isdir, int elevel)
3506 {
3507  int fd;
3508 
3509  /* Don't try to flush directories, it'll likely just fail */
3510  if (isdir)
3511  return;
3512 
3513  fd = OpenTransientFile(fname, O_RDONLY | PG_BINARY);
3514 
3515  if (fd < 0)
3516  {
3517  if (errno == EACCES)
3518  return;
3519  ereport(elevel,
3521  errmsg("could not open file \"%s\": %m", fname)));
3522  return;
3523  }
3524 
3525  /*
3526  * pg_flush_data() ignores errors, which is ok because this is only a
3527  * hint.
3528  */
3529  pg_flush_data(fd, 0, 0);
3530 
3531  if (CloseTransientFile(fd) != 0)
3532  ereport(elevel,
3534  errmsg("could not close file \"%s\": %m", fname)));
3535 }
3536 
3537 #endif /* PG_FLUSH_DATA_WORKS */
3538 
3539 static void
3540 datadir_fsync_fname(const char *fname, bool isdir, int elevel)
3541 {
3542  /*
3543  * We want to silently ignoring errors about unreadable files. Pass that
3544  * desire on to fsync_fname_ext().
3545  */
3546  fsync_fname_ext(fname, isdir, true, elevel);
3547 }
3548 
3549 static void
3550 unlink_if_exists_fname(const char *fname, bool isdir, int elevel)
3551 {
3552  if (isdir)
3553  {
3554  if (rmdir(fname) != 0 && errno != ENOENT)
3555  ereport(elevel,
3557  errmsg("could not remove directory \"%s\": %m", fname)));
3558  }
3559  else
3560  {
3561  /* Use PathNameDeleteTemporaryFile to report filesize */
3562  PathNameDeleteTemporaryFile(fname, false);
3563  }
3564 }
3565 
3566 /*
3567  * fsync_fname_ext -- Try to fsync a file or directory
3568  *
3569  * If ignore_perm is true, ignore errors upon trying to open unreadable
3570  * files. Logs other errors at a caller-specified level.
3571  *
3572  * Returns 0 if the operation succeeded, -1 otherwise.
3573  */
3574 int
3575 fsync_fname_ext(const char *fname, bool isdir, bool ignore_perm, int elevel)
3576 {
3577  int fd;
3578  int flags;
3579  int returncode;
3580 
3581  /*
3582  * Some OSs require directories to be opened read-only whereas other
3583  * systems don't allow us to fsync files opened read-only; so we need both
3584  * cases here. Using O_RDWR will cause us to fail to fsync files that are
3585  * not writable by our userid, but we assume that's OK.
3586  */
3587  flags = PG_BINARY;
3588  if (!isdir)
3589  flags |= O_RDWR;
3590  else
3591  flags |= O_RDONLY;
3592 
3593  fd = OpenTransientFile(fname, flags);
3594 
3595  /*
3596  * Some OSs don't allow us to open directories at all (Windows returns
3597  * EACCES), just ignore the error in that case. If desired also silently
3598  * ignoring errors about unreadable files. Log others.
3599  */
3600  if (fd < 0 && isdir && (errno == EISDIR || errno == EACCES))
3601  return 0;
3602  else if (fd < 0 && ignore_perm && errno == EACCES)
3603  return 0;
3604  else if (fd < 0)
3605  {
3606  ereport(elevel,
3608  errmsg("could not open file \"%s\": %m", fname)));
3609  return -1;
3610  }
3611 
3612  returncode = pg_fsync(fd);
3613 
3614  /*
3615  * Some OSes don't allow us to fsync directories at all, so we can ignore
3616  * those errors. Anything else needs to be logged.
3617  */
3618  if (returncode != 0 && !(isdir && (errno == EBADF || errno == EINVAL)))
3619  {
3620  int save_errno;
3621 
3622  /* close file upon error, might not be in transaction context */
3623  save_errno = errno;
3624  (void) CloseTransientFile(fd);
3625  errno = save_errno;
3626 
3627  ereport(elevel,
3629  errmsg("could not fsync file \"%s\": %m", fname)));
3630  return -1;
3631  }
3632 
3633  if (CloseTransientFile(fd) != 0)
3634  {
3635  ereport(elevel,
3637  errmsg("could not close file \"%s\": %m", fname)));
3638  return -1;
3639  }
3640 
3641  return 0;
3642 }
3643 
3644 /*
3645  * fsync_parent_path -- fsync the parent path of a file or directory
3646  *
3647  * This is aimed at making file operations persistent on disk in case of
3648  * an OS crash or power failure.
3649  */
3650 static int
3651 fsync_parent_path(const char *fname, int elevel)
3652 {
3653  char parentpath[MAXPGPATH];
3654 
3655  strlcpy(parentpath, fname, MAXPGPATH);
3656  get_parent_directory(parentpath);
3657 
3658  /*
3659  * get_parent_directory() returns an empty string if the input argument is
3660  * just a file name (see comments in path.c), so handle that as being the
3661  * current directory.
3662  */
3663  if (strlen(parentpath) == 0)
3664  strlcpy(parentpath, ".", MAXPGPATH);
3665 
3666  if (fsync_fname_ext(parentpath, true, false, elevel) != 0)
3667  return -1;
3668 
3669  return 0;
3670 }
3671 
3672 /*
3673  * Create a PostgreSQL data sub-directory
3674  *
3675  * The data directory itself, and most of its sub-directories, are created at
3676  * initdb time, but we do have some occasions when we create directories in
3677  * the backend (CREATE TABLESPACE, for example). In those cases, we want to
3678  * make sure that those directories are created consistently. Today, that means
3679  * making sure that the created directory has the correct permissions, which is
3680  * what pg_dir_create_mode tracks for us.
3681  *
3682  * Note that we also set the umask() based on what we understand the correct
3683  * permissions to be (see file_perm.c).
3684  *
3685  * For permissions other than the default, mkdir() can be used directly, but
3686  * be sure to consider carefully such cases -- a sub-directory with incorrect
3687  * permissions in a PostgreSQL data directory could cause backups and other
3688  * processes to fail.
3689  */
3690 int
3691 MakePGDirectory(const char *directoryName)
3692 {
3693  return mkdir(directoryName, pg_dir_create_mode);
3694 }
3695 
3696 /*
3697  * Return the passed-in error level, or PANIC if data_sync_retry is off.
3698  *
3699  * Failure to fsync any data file is cause for immediate panic, unless
3700  * data_sync_retry is enabled. Data may have been written to the operating
3701  * system and removed from our buffer pool already, and if we are running on
3702  * an operating system that forgets dirty data on write-back failure, there
3703  * may be only one copy of the data remaining: in the WAL. A later attempt to
3704  * fsync again might falsely report success. Therefore we must not allow any
3705  * further checkpoints to be attempted. data_sync_retry can in theory be
3706  * enabled on systems known not to drop dirty buffered data on write-back
3707  * failure (with the likely outcome that checkpoints will continue to fail
3708  * until the underlying problem is fixed).
3709  *
3710  * Any code that reports a failure from fsync() or related functions should
3711  * filter the error level with this function.
3712  */
3713 int
3714 data_sync_elevel(int elevel)
3715 {
3716  return data_sync_retry ? elevel : PANIC;
3717 }
3718 
3719 /*
3720  * A convenience wrapper for pg_pwritev() that retries on partial write. If an
3721  * error is returned, it is unspecified how much has been written.
3722  */
3723 ssize_t
3724 pg_pwritev_with_retry(int fd, const struct iovec *iov, int iovcnt, off_t offset)
3725 {
3726  struct iovec iov_copy[PG_IOV_MAX];
3727  ssize_t sum = 0;
3728  ssize_t part;
3729 
3730  /* We'd better have space to make a copy, in case we need to retry. */
3731  if (iovcnt > PG_IOV_MAX)
3732  {
3733  errno = EINVAL;
3734  return -1;
3735  }
3736 
3737  for (;;)
3738  {
3739  /* Write as much as we can. */
3740  part = pg_pwritev(fd, iov, iovcnt, offset);
3741  if (part < 0)
3742  return -1;
3743 
3744 #ifdef SIMULATE_SHORT_WRITE
3745  part = Min(part, 4096);
3746 #endif
3747 
3748  /* Count our progress. */
3749  sum += part;
3750  offset += part;
3751 
3752  /* Step over iovecs that are done. */
3753  while (iovcnt > 0 && iov->iov_len <= part)
3754  {
3755  part -= iov->iov_len;
3756  ++iov;
3757  --iovcnt;
3758  }
3759 
3760  /* Are they all done? */
3761  if (iovcnt == 0)
3762  {
3763  /* We don't expect the kernel to write more than requested. */
3764  Assert(part == 0);
3765  break;
3766  }
3767 
3768  /*
3769  * Move whatever's left to the front of our mutable copy and adjust
3770  * the leading iovec.
3771  */
3772  Assert(iovcnt > 0);
3773  memmove(iov_copy, iov, sizeof(*iov) * iovcnt);
3774  Assert(iov->iov_len > part);
3775  iov_copy[0].iov_base = (char *) iov_copy[0].iov_base + part;
3776  iov_copy[0].iov_len -= part;
3777  iov = iov_copy;
3778  }
3779 
3780  return sum;
3781 }
size_t iov_len
Definition: pg_iovec.h:27
File PathNameOpenFilePerm(const char *fileName, int fileFlags, mode_t fileMode)
Definition: fd.c:1497
File lruLessRecently
Definition: fd.c:199
void closeAllVfds(void)
Definition: fd.c:2811
static PgChecksumMode mode
Definition: pg_checksums.c:61
union AllocateDesc::@18 desc
File nextFree
Definition: fd.c:197
static void count_usable_fds(int max_to_probe, int *usable_fds, int *already_open)
Definition: fd.c:906
int pg_file_create_mode
Definition: file_perm.c:19
bool PathNameDeleteTemporaryFile(const char *path, bool error_on_failure)
Definition: fd.c:1827
#define MAP_FAILED
Definition: mem.h:45
#define DEBUG1
Definition: elog.h:25
int MyProcPid
Definition: globals.c:43
void * iov_base
Definition: pg_iovec.h:26
File PathNameCreateTemporaryFile(const char *path, bool error_on_failure)
Definition: fd.c:1760
#define NUM_RESERVED_FDS
Definition: fd.c:128
static AllocateDesc * allocatedDescs
Definition: fd.c:260
static void pgstat_report_wait_end(void)
Definition: wait_event.h:277
File PathNameOpenFile(const char *fileName, int fileFlags)
Definition: fd.c:1484
int pg_fdatasync(int fd)
Definition: fd.c:442
static void error(void)
Definition: sql-dyntest.c:147
#define SYNC_METHOD_FSYNC_WRITETHROUGH
Definition: xlog.h:28
AllocateDescKind
Definition: fd.c:238
DIR * dir
Definition: fd.c:253
static File OpenTemporaryFileInTablespace(Oid tblspcOid, bool rejectError)
Definition: fd.c:1703
static void AtProcExit_Files(int code, Datum arg)
Definition: fd.c:2969
static Size SizeVfdCache
Definition: fd.c:213
#define FD_TEMP_FILE_LIMIT
Definition: fd.c:190
void on_proc_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:305
#define DO_DB(A)
Definition: fd.c:176
int GetTempTablespaces(Oid *tableSpaces, int numSpaces)
Definition: fd.c:2883
static void walkdir(const char *path, void(*action)(const char *fname, bool isdir, int elevel), bool process_symlinks, int elevel)
Definition: fd.c:3442
int pg_truncate(const char *path, off_t length)
Definition: fd.c:635
long random(void)
Definition: random.c:22
ResourceOwner CurrentResourceOwner
Definition: resowner.c:146
static int numExternalFDs
Definition: fd.c:265
int pg_fsync_writethrough(int fd)
Definition: fd.c:419
int forkname_chars(const char *str, ForkNumber *fork)
Definition: relpath.c:81
struct dirent * ReadDirExtended(DIR *dir, const char *dirname, int elevel)
Definition: fd.c:2715
int max_safe_fds
Definition: fd.c:158
#define Min(x, y)
Definition: c.h:986
off_t FileSize(File file)
Definition: fd.c:2199
void fsync_fname(const char *fname, bool isdir)
Definition: fd.c:666
int OpenTransientFilePerm(const char *fileName, int fileFlags, mode_t fileMode)
Definition: fd.c:2432
#define FD_DELETE_AT_CLOSE
Definition: fd.c:188
int log_temp_files
Definition: guc.c:571
mode_t FileGetRawMode(File file)
Definition: fd.c:2287
void _dosmaperr(unsigned long)
Definition: win32error.c:171
static Vfd * VfdCache
Definition: fd.c:212
static void Delete(File file)
Definition: fd.c:1177
int closedir(DIR *)
Definition: dirent.c:123
static int numTempTableSpaces
Definition: fd.c:280
#define PG_TEMP_FILES_DIR
Definition: pg_checksums.c:58
int errcode(int sqlerrcode)
Definition: elog.c:698
#define MemSet(start, val, len)
Definition: c.h:1008
void PathNameDeleteTemporaryDir(const char *dirname)
Definition: fd.c:1592
int pg_fsync_no_writethrough(int fd)
Definition: fd.c:407
static void RemovePgTempRelationFilesInDbspace(const char *dbspacedirname)
Definition: fd.c:3212
void pgstat_report_tempfile(size_t filesize)
Definition: pgstat.c:1796
static bool reserveAllocatedDesc(void)
Definition: fd.c:2298
uint32 SubTransactionId
Definition: c.h:591
#define SIGPIPE
Definition: win32_port.h:164
void TempTablespacePath(char *path, Oid tablespace)
Definition: fd.c:1678
#define LOG
Definition: elog.h:26
unsigned int Oid
Definition: postgres_ext.h:31
AllocateDescKind kind
Definition: fd.c:248
char * FilePathName(File file)
Definition: fd.c:2251
Definition: dirent.h:9
#define OidIsValid(objectId)
Definition: c.h:710
#define PANIC
Definition: elog.h:50
#define PG_BINARY
Definition: c.h:1271
static char * basedir
ssize_t pg_pwrite(int fd, const void *buf, size_t nbyte, off_t offset)
Definition: pwrite.c:27
void AtEOXact_Files(bool isCommit)
Definition: fd.c:2955
Oid MyDatabaseTableSpace
Definition: globals.c:90
int ClosePipeStream(FILE *file)
Definition: fd.c:2782
ssize_t pg_pread(int fd, void *buf, size_t nbyte, off_t offset)
Definition: pread.c:27
#define malloc(a)
Definition: header.h:50
static void LruDelete(File file)
Definition: fd.c:1196
void pg_usleep(long microsec)
Definition: signal.c:53
bool TempTablespacesAreSet(void)
Definition: fd.c:2868
#define fstat
Definition: win32_port.h:274
ssize_t pg_pwritev(int fd, const struct iovec *iov, int iovcnt, off_t offset)
Definition: pwritev.c:29
#define fsync(fd)
Definition: win32_port.h:68
static int FreeDesc(AllocateDesc *desc)
Definition: fd.c:2533
void pfree(void *pointer)
Definition: mcxt.c:1169
mode_t fileMode
Definition: fd.c:204
static void RemovePgTempRelationFiles(const char *tsdirname)
Definition: fd.c:3184
static bool ReleaseLruFile(void)
Definition: fd.c:1291
Definition: dirent.c:25
int durable_rename_excl(const char *oldfile, const char *newfile, int elevel)
Definition: fd.c:822
#define ERROR
Definition: elog.h:46
#define PG_TEMP_FILE_PREFIX
Definition: pg_checksums.c:59
int OpenTransientFile(const char *fileName, int fileFlags)
Definition: fd.c:2423
static int LruInsert(File file)
Definition: fd.c:1244
#define FATAL
Definition: elog.h:49
int recovery_init_sync_method
Definition: fd.c:164
static bool have_xact_temporary_files
Definition: fd.c:224
#define MAXPGPATH
void ReserveExternalFD(void)
Definition: fd.c:1130
DIR * opendir(const char *)
Definition: dirent.c:33
int FileSync(File file, uint32 wait_event_info)
Definition: fd.c:2178
#define DEBUG2
Definition: elog.h:24
ssize_t pg_pwritev_with_retry(int fd, const struct iovec *iov, int iovcnt, off_t offset)
Definition: fd.c:3724
#define TABLESPACE_VERSION_DIRECTORY
Definition: relpath.h:26
char * fileName
Definition: fd.c:201
static char * buf
Definition: pg_test_fsync.c:68
Oid GetNextTempTableSpace(void)
Definition: fd.c:2901
void ResourceOwnerRememberFile(ResourceOwner owner, File file)
Definition: resowner.c:1297
static void unlink_if_exists_fname(const char *fname, bool isdir, int elevel)
Definition: fd.c:3550
File PathNameOpenTemporaryFile(const char *path, int mode)
Definition: fd.c:1798
int errdetail(const char *fmt,...)
Definition: elog.c:1042
void RemovePgTempFilesInDir(const char *tmpdirname, bool missing_ok, bool unlink_all)
Definition: fd.c:3118
char * tablespace
Definition: pgbench.c:224
int errcode_for_file_access(void)
Definition: elog.c:721
void get_parent_directory(char *path)
Definition: path.c:854
FILE * AllocateFile(const char *name, const char *mode)
Definition: fd.c:2373
static int nfile
Definition: fd.c:218
unsigned int uint32
Definition: c.h:441
void SyncDataDirectory(void)
Definition: fd.c:3332
DIR * AllocateDir(const char *dirname)
Definition: fd.c:2634
static int nextTempTableSpace
Definition: fd.c:281
__int64 st_size
Definition: win32_port.h:265
PGFileType get_dirent_type(const char *path, const struct dirent *de, bool look_through_symlinks, int elevel)
Definition: file_utils.c:410
int max_files_per_process
Definition: fd.c:145
static File AllocateVfd(void)
Definition: fd.c:1323
FILE * OpenPipeStream(const char *command, const char *mode)
Definition: fd.c:2476
unsigned short fdstate
Definition: fd.c:195
Definition: fd.c:192
off_t fileSize
Definition: fd.c:200
int fd
Definition: fd.c:194
void SetTempTablespaces(Oid *tableSpaces, int numSpaces)
Definition: fd.c:2840
int durable_rename(const char *oldfile, const char *newfile, int elevel)
Definition: fd.c:692
static void Insert(File file)
Definition: fd.c:1222
ResourceOwner resowner
Definition: fd.c:196
static void pgstat_report_wait_start(uint32 wait_event_info)
Definition: wait_event.h:261
bool data_sync_retry
Definition: fd.c:161
static void datadir_fsync_fname(const char *fname, bool isdir, int elevel)
Definition: fd.c:3540
int CloseTransientFile(int fd)
Definition: fd.c:2600
#define SIG_IGN
Definition: win32_port.h:156
static void ReportTemporaryFileUsage(const char *path, off_t size)
Definition: fd.c:1437
static void ReleaseLruFiles(void)
Definition: fd.c:1313
#define WARNING
Definition: elog.h:40
#define FileIsNotOpen(file)
Definition: fd.c:185
int pg_dir_create_mode
Definition: file_perm.c:18
static int elevel
Definition: vacuumlazy.c:400
int FileWrite(File file, char *buffer, int amount, off_t offset, uint32 wait_event_info)
Definition: fd.c:2080
struct vfd Vfd
int data_sync_elevel(int elevel)
Definition: fd.c:3714
uintptr_t Datum
Definition: postgres.h:411
void AtEOSubXact_Files(bool isCommit, SubTransactionId mySubid, SubTransactionId parentSubid)
Definition: fd.c:2922
unsigned short st_mode
Definition: win32_port.h:260
Definition: pg_iovec.h:24
unsigned int Index
Definition: c.h:549
void pg_flush_data(int fd, off_t offset, off_t nbytes)
Definition: fd.c:462
#define FileIsValid(file)
Definition: fd.c:182
bool AcquireExternalFD(void)
Definition: fd.c:1095
FILE * file
Definition: fd.c:252
#define InvalidOid
Definition: postgres_ext.h:36
#define VFD_CLOSED
Definition: fd.c:180
static uint64 temporary_files_size
Definition: fd.c:232
#define ereport(elevel,...)
Definition: elog.h:157
int MakePGDirectory(const char *directoryName)
Definition: fd.c:3691
pqsigfunc pqsignal(int signum, pqsigfunc handler)
Definition: signal.c:170
#define free(a)
Definition: header.h:65
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
static void RegisterTemporaryFile(File file)
Definition: fd.c:1456
void FileClose(File file)
Definition: fd.c:1873
#define SIG_DFL
Definition: win32_port.h:154
int FilePrefetch(File file, off_t offset, int amount, uint32 wait_event_info)
Definition: fd.c:1973
static int FileAccess(File file)
Definition: fd.c:1401
#define Assert(condition)
Definition: c.h:804
SubTransactionId GetCurrentSubTransactionId(void)
Definition: xact.c:723
struct dirent * ReadDir(DIR *dir, const char *dirname)
Definition: fd.c:2700
File lruMoreRecently
Definition: fd.c:198
void FileWriteback(File file, off_t offset, off_t nbytes, uint32 wait_event_info)
Definition: fd.c:2001
void RemovePgTempFiles(void)
Definition: fd.c:3059
SubTransactionId create_subid
Definition: fd.c:249
File OpenTemporaryFile(bool interXact)
Definition: fd.c:1625
size_t Size
Definition: c.h:540
static const char * directory
Definition: zic.c:632
int sync_method
Definition: xlog.c:108
struct dirent * readdir(DIR *)
Definition: dirent.c:78
#define FD_MINFREE
Definition: fd.c:137
bool looks_like_temp_rel_name(const char *name)
Definition: fd.c:3240
#define realloc(a, b)
Definition: header.h:60
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:1182
#define INT64_FORMAT
Definition: c.h:483
const char * name
Definition: encode.c:515
static long tempFileCounter
Definition: fd.c:271
int fd
Definition: fd.c:254
#define S_ISDIR(m)
Definition: win32_port.h:316
#define lstat(path, sb)
Definition: win32_port.h:276
int durable_unlink(const char *fname, int elevel)
Definition: fd.c:782
int BasicOpenFile(const char *fileName, int fileFlags)
Definition: fd.c:1033
int FreeFile(FILE *file)
Definition: fd.c:2572
void set_max_safe_fds(void)
Definition: fd.c:990
bool enableFsync
Definition: globals.c:122
static Oid * tempTableSpaces
Definition: fd.c:279
void ReleaseExternalFD(void)
Definition: fd.c:1148
void * palloc(Size size)
Definition: mcxt.c:1062
int errmsg(const char *fmt,...)
Definition: elog.c:909
int FileGetRawFlags(File file)
Definition: fd.c:2277
void ResourceOwnerEnlargeFiles(ResourceOwner owner)
Definition: resowner.c:1286
int BasicOpenFilePerm(const char *fileName, int fileFlags, mode_t fileMode)
Definition: fd.c:1055
#define elog(elevel,...)
Definition: elog.h:232
int i
#define FD_CLOSE_AT_EOXACT
Definition: fd.c:189
void * arg
int FileGetRawDesc(File file)
Definition: fd.c:2267
static void FreeVfd(File file)
Definition: fd.c:1381
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:102
int pg_fsync(int fd)
Definition: fd.c:352
char d_name[MAX_PATH]
Definition: dirent.h:15
#define mkdir(a, b)
Definition: win32_port.h:63
int link(const char *src, const char *dst)
#define close(a)
Definition: win32.h:12
#define EINTR
Definition: win32_port.h:343
int fileFlags
Definition: fd.c:203
void PathNameCreateTemporaryDir(const char *basedir, const char *directory)
Definition: fd.c:1561
int FileRead(File file, char *buffer, int amount, off_t offset, uint32 wait_event_info)
Definition: fd.c:2024
void ResourceOwnerForgetFile(ResourceOwner owner, File file)
Definition: resowner.c:1306
#define snprintf
Definition: port.h:216
int FileTruncate(File file, off_t offset, uint32 wait_event_info)
Definition: fd.c:2216
int fsync_fname_ext(const char *fname, bool isdir, bool ignore_perm, int elevel)
Definition: fd.c:3575
static int maxAllocatedDescs
Definition: fd.c:259
static void CleanupTempFiles(bool isCommit, bool isProcExit)
Definition: fd.c:2987
static int fsync_parent_path(const char *fname, int elevel)
Definition: fd.c:3651
int File
Definition: fd.h:53
int FreeDir(DIR *dir)
Definition: fd.c:2752
int temp_file_limit
Definition: guc.c:578
Datum subpath(PG_FUNCTION_ARGS)
Definition: ltree_op.c:241
void InitFileAccess(void)
Definition: fd.c:873
#define stat
Definition: win32_port.h:275
static int numAllocatedDescs
Definition: fd.c:258
bool pgwin32_is_junction(const char *path)
#define ftruncate(a, b)
Definition: win32_port.h:65