PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
fd.h File Reference
#include <dirent.h>
Include dependency graph for fd.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Macros

#define PG_TEMP_FILES_DIR   "pgsql_tmp"
 
#define PG_TEMP_FILE_PREFIX   "pgsql_tmp"
 

Typedefs

typedef int File
 

Functions

File PathNameOpenFile (const char *fileName, int fileFlags)
 
File PathNameOpenFilePerm (const char *fileName, int fileFlags, mode_t fileMode)
 
File OpenTemporaryFile (bool interXact)
 
void FileClose (File file)
 
int FilePrefetch (File file, off_t offset, int amount, uint32 wait_event_info)
 
int FileRead (File file, char *buffer, int amount, uint32 wait_event_info)
 
int FileWrite (File file, char *buffer, int amount, uint32 wait_event_info)
 
int FileSync (File file, uint32 wait_event_info)
 
off_t FileSeek (File file, off_t offset, int whence)
 
int FileTruncate (File file, off_t offset, uint32 wait_event_info)
 
void FileWriteback (File file, off_t offset, off_t nbytes, uint32 wait_event_info)
 
char * FilePathName (File file)
 
int FileGetRawDesc (File file)
 
int FileGetRawFlags (File file)
 
mode_t FileGetRawMode (File file)
 
FILE * AllocateFile (const char *name, const char *mode)
 
int FreeFile (FILE *file)
 
FILE * OpenPipeStream (const char *command, const char *mode)
 
int ClosePipeStream (FILE *file)
 
DIRAllocateDir (const char *dirname)
 
struct direntReadDir (DIR *dir, const char *dirname)
 
int FreeDir (DIR *dir)
 
int OpenTransientFile (const char *fileName, int fileFlags)
 
int OpenTransientFilePerm (const char *fileName, int fileFlags, mode_t fileMode)
 
int CloseTransientFile (int fd)
 
int BasicOpenFile (const char *fileName, int fileFlags)
 
int BasicOpenFilePerm (const char *fileName, int fileFlags, mode_t fileMode)
 
void InitFileAccess (void)
 
void set_max_safe_fds (void)
 
void closeAllVfds (void)
 
void SetTempTablespaces (Oid *tableSpaces, int numSpaces)
 
bool TempTablespacesAreSet (void)
 
Oid GetNextTempTableSpace (void)
 
void AtEOXact_Files (void)
 
void AtEOSubXact_Files (bool isCommit, SubTransactionId mySubid, SubTransactionId parentSubid)
 
void RemovePgTempFiles (void)
 
int pg_fsync (int fd)
 
int pg_fsync_no_writethrough (int fd)
 
int pg_fsync_writethrough (int fd)
 
int pg_fdatasync (int fd)
 
void pg_flush_data (int fd, off_t offset, off_t amount)
 
void fsync_fname (const char *fname, bool isdir)
 
int durable_rename (const char *oldfile, const char *newfile, int loglevel)
 
int durable_unlink (const char *fname, int loglevel)
 
int durable_link_or_rename (const char *oldfile, const char *newfile, int loglevel)
 
void SyncDataDirectory (void)
 

Variables

int max_files_per_process
 
int max_safe_fds
 

Macro Definition Documentation

#define PG_TEMP_FILE_PREFIX   "pgsql_tmp"
#define PG_TEMP_FILES_DIR   "pgsql_tmp"

Definition at line 128 of file fd.h.

Referenced by OpenTemporaryFileInTablespace(), process_source_file(), and RemovePgTempFiles().

Typedef Documentation

Definition at line 49 of file fd.h.

Function Documentation

DIR* AllocateDir ( const char *  dirname)

Definition at line 2367 of file fd.c.

References AllocateDescDir, AllocateDesc::create_subid, AllocateDesc::desc, AllocateDesc::dir, DO_DB, elog, ereport, errcode(), errmsg(), ERROR, GetCurrentSubTransactionId(), AllocateDesc::kind, LOG, maxAllocatedDescs, numAllocatedDescs, opendir(), ReleaseLruFile(), ReleaseLruFiles(), and reserveAllocatedDesc().

Referenced by calculate_database_size(), calculate_tablespace_size(), CheckPointLogicalRewriteHeap(), CheckPointSnapBuild(), CleanupBackupHistory(), copydir(), db_dir_size(), DeleteAllExportedSnapshotFiles(), destroy_tablespace_directories(), directory_is_empty(), dsm_cleanup_for_mmap(), get_ext_ver_list(), getInstallationPaths(), movedb(), ParseTzFile(), perform_base_backup(), pg_available_extension_versions(), pg_available_extensions(), pg_logdir_ls(), pg_ls_dir(), pg_ls_dir_files(), pg_start_backup(), pg_tablespace_databases(), pg_tzenumerate_next(), pg_tzenumerate_start(), pgarch_readyXlog(), pgstat_reset_remove_files(), RelationCacheInitFileRemove(), RelationCacheInitFileRemoveInDir(), RemoveNonParentXlogFiles(), RemoveOldXlogFiles(), RemovePgTempFiles(), RemovePgTempFilesInDir(), RemovePgTempRelationFiles(), RemovePgTempRelationFilesInDbspace(), ResetUnloggedRelations(), ResetUnloggedRelationsInDbspaceDir(), ResetUnloggedRelationsInTablespaceDir(), restoreTwoPhaseData(), scan_directory_ci(), SendBaseBackup(), sendDir(), SlruScanDirectory(), StartupReorderBuffer(), StartupReplicationSlots(), UpdateLogicalMappings(), and walkdir().

2368 {
2369  DIR *dir;
2370 
2371  DO_DB(elog(LOG, "AllocateDir: Allocated %d (%s)",
2372  numAllocatedDescs, dirname));
2373 
2374  /* Can we allocate another non-virtual FD? */
2375  if (!reserveAllocatedDesc())
2376  ereport(ERROR,
2377  (errcode(ERRCODE_INSUFFICIENT_RESOURCES),
2378  errmsg("exceeded maxAllocatedDescs (%d) while trying to open directory \"%s\"",
2379  maxAllocatedDescs, dirname)));
2380 
2381  /* Close excess kernel FDs. */
2382  ReleaseLruFiles();
2383 
2384 TryAgain:
2385  if ((dir = opendir(dirname)) != NULL)
2386  {
2388 
2389  desc->kind = AllocateDescDir;
2390  desc->desc.dir = dir;
2393  return desc->desc.dir;
2394  }
2395 
2396  if (errno == EMFILE || errno == ENFILE)
2397  {
2398  int save_errno = errno;
2399 
2400  ereport(LOG,
2401  (errcode(ERRCODE_INSUFFICIENT_RESOURCES),
2402  errmsg("out of file descriptors: %m; release and retry")));
2403  errno = 0;
2404  if (ReleaseLruFile())
2405  goto TryAgain;
2406  errno = save_errno;
2407  }
2408 
2409  return NULL;
2410 }
static AllocateDesc * allocatedDescs
Definition: fd.c:250
DIR * dir
Definition: fd.c:243
#define DO_DB(A)
Definition: fd.c:157
int errcode(int sqlerrcode)
Definition: elog.c:575
static bool reserveAllocatedDesc(void)
Definition: fd.c:2044
#define LOG
Definition: elog.h:26
AllocateDescKind kind
Definition: fd.c:238
static bool ReleaseLruFile(void)
Definition: fd.c:1155
Definition: dirent.c:25
#define ERROR
Definition: elog.h:43
DIR * opendir(const char *)
Definition: dirent.c:33
#define ereport(elevel, rest)
Definition: elog.h:122
static void ReleaseLruFiles(void)
Definition: fd.c:1177
SubTransactionId GetCurrentSubTransactionId(void)
Definition: xact.c:642
SubTransactionId create_subid
Definition: fd.c:239
int errmsg(const char *fmt,...)
Definition: elog.c:797
union AllocateDesc::@27 desc
#define elog
Definition: elog.h:219
static int maxAllocatedDescs
Definition: fd.c:249
static int numAllocatedDescs
Definition: fd.c:248
FILE* AllocateFile ( const char *  name,
const char *  mode 
)

Definition at line 2117 of file fd.c.

References AllocateDescFile, AllocateDesc::create_subid, AllocateDesc::desc, DO_DB, elog, ereport, errcode(), errmsg(), ERROR, AllocateDesc::file, GetCurrentSubTransactionId(), AllocateDesc::kind, LOG, maxAllocatedDescs, numAllocatedDescs, ReleaseLruFile(), ReleaseLruFiles(), and reserveAllocatedDesc().

Referenced by AlterSystemSetConfigFile(), apw_dump_now(), apw_load_buffers(), BeginCopyFrom(), BeginCopyTo(), checkDataDir(), do_pg_start_backup(), do_pg_stop_backup(), entry_reset(), existsTimeLineHistory(), ExportSnapshot(), fill_hba_view(), gc_qtexts(), ImportSnapshot(), load_dh_file(), load_hba(), load_ident(), load_relcache_init_file(), parse_extension_control_file(), ParseTzFile(), perform_base_backup(), pg_backup_start_time(), pg_current_logfile(), pg_file_write(), pgss_shmem_shutdown(), pgss_shmem_startup(), pgstat_read_db_statsfile(), pgstat_read_db_statsfile_timestamp(), pgstat_read_statsfiles(), pgstat_write_db_statsfile(), pgstat_write_statsfiles(), read_backup_label(), read_binary_file(), read_tablespace_map(), read_whole_file(), readRecoveryCommandFile(), readTimeLineHistory(), sendFile(), tokenize_inc_file(), tsearch_readline_begin(), ValidatePgVersion(), write_relcache_init_file(), XLogArchiveForceDone(), and XLogArchiveNotify().

2118 {
2119  FILE *file;
2120 
2121  DO_DB(elog(LOG, "AllocateFile: Allocated %d (%s)",
2123 
2124  /* Can we allocate another non-virtual FD? */
2125  if (!reserveAllocatedDesc())
2126  ereport(ERROR,
2127  (errcode(ERRCODE_INSUFFICIENT_RESOURCES),
2128  errmsg("exceeded maxAllocatedDescs (%d) while trying to open file \"%s\"",
2129  maxAllocatedDescs, name)));
2130 
2131  /* Close excess kernel FDs. */
2132  ReleaseLruFiles();
2133 
2134 TryAgain:
2135  if ((file = fopen(name, mode)) != NULL)
2136  {
2138 
2139  desc->kind = AllocateDescFile;
2140  desc->desc.file = file;
2143  return desc->desc.file;
2144  }
2145 
2146  if (errno == EMFILE || errno == ENFILE)
2147  {
2148  int save_errno = errno;
2149 
2150  ereport(LOG,
2151  (errcode(ERRCODE_INSUFFICIENT_RESOURCES),
2152  errmsg("out of file descriptors: %m; release and retry")));
2153  errno = 0;
2154  if (ReleaseLruFile())
2155  goto TryAgain;
2156  errno = save_errno;
2157  }
2158 
2159  return NULL;
2160 }
static AllocateDesc * allocatedDescs
Definition: fd.c:250
#define DO_DB(A)
Definition: fd.c:157
int errcode(int sqlerrcode)
Definition: elog.c:575
static bool reserveAllocatedDesc(void)
Definition: fd.c:2044
#define LOG
Definition: elog.h:26
AllocateDescKind kind
Definition: fd.c:238
static bool ReleaseLruFile(void)
Definition: fd.c:1155
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:122
static void ReleaseLruFiles(void)
Definition: fd.c:1177
FILE * file
Definition: fd.c:242
SubTransactionId GetCurrentSubTransactionId(void)
Definition: xact.c:642
SubTransactionId create_subid
Definition: fd.c:239
const char * name
Definition: encode.c:521
int errmsg(const char *fmt,...)
Definition: elog.c:797
union AllocateDesc::@27 desc
#define elog
Definition: elog.h:219
static int maxAllocatedDescs
Definition: fd.c:249
static int numAllocatedDescs
Definition: fd.c:248
void AtEOSubXact_Files ( bool  isCommit,
SubTransactionId  mySubid,
SubTransactionId  parentSubid 
)

Definition at line 2618 of file fd.c.

References AllocateDesc::create_subid, FreeDesc(), i, and numAllocatedDescs.

Referenced by AbortSubTransaction(), and CommitSubTransaction().

2620 {
2621  Index i;
2622 
2623  for (i = 0; i < numAllocatedDescs; i++)
2624  {
2625  if (allocatedDescs[i].create_subid == mySubid)
2626  {
2627  if (isCommit)
2628  allocatedDescs[i].create_subid = parentSubid;
2629  else
2630  {
2631  /* have to recheck the item after FreeDesc (ugly) */
2632  FreeDesc(&allocatedDescs[i--]);
2633  }
2634  }
2635  }
2636 }
static AllocateDesc * allocatedDescs
Definition: fd.c:250
static int FreeDesc(AllocateDesc *desc)
Definition: fd.c:2270
unsigned int Index
Definition: c.h:359
SubTransactionId create_subid
Definition: fd.c:239
int i
static int numAllocatedDescs
Definition: fd.c:248
void AtEOXact_Files ( void  )

Definition at line 2649 of file fd.c.

References CleanupTempFiles(), numTempTableSpaces, and tempTableSpaces.

Referenced by AbortTransaction(), AutoVacLauncherMain(), BackgroundWriterMain(), CheckpointerMain(), CommitTransaction(), PrepareTransaction(), and WalWriterMain().

2650 {
2651  CleanupTempFiles(false);
2652  tempTableSpaces = NULL;
2653  numTempTableSpaces = -1;
2654 }
static int numTempTableSpaces
Definition: fd.c:263
static void CleanupTempFiles(bool isProcExit)
Definition: fd.c:2678
static Oid * tempTableSpaces
Definition: fd.c:262
int BasicOpenFile ( const char *  fileName,
int  fileFlags 
)

Definition at line 929 of file fd.c.

References BasicOpenFilePerm(), and PG_FILE_MODE_DEFAULT.

Referenced by AlterSystemSetConfigFile(), GetNewRelFileNode(), ReadControlFile(), UpdateControlFile(), WriteControlFile(), XLogFileInit(), XLogFileOpen(), XLogFileRead(), and XLogRead().

930 {
931  return BasicOpenFilePerm(fileName, fileFlags, PG_FILE_MODE_DEFAULT);
932 }
#define PG_FILE_MODE_DEFAULT
Definition: fd.c:123
int BasicOpenFilePerm(const char *fileName, int fileFlags, mode_t fileMode)
Definition: fd.c:951
int BasicOpenFilePerm ( const char *  fileName,
int  fileFlags,
mode_t  fileMode 
)

Definition at line 951 of file fd.c.

References ereport, errcode(), errmsg(), fd(), LOG, and ReleaseLruFile().

Referenced by BasicOpenFile(), LruInsert(), OpenTransientFilePerm(), and PathNameOpenFilePerm().

952 {
953  int fd;
954 
955 tryAgain:
956  fd = open(fileName, fileFlags, fileMode);
957 
958  if (fd >= 0)
959  return fd; /* success! */
960 
961  if (errno == EMFILE || errno == ENFILE)
962  {
963  int save_errno = errno;
964 
965  ereport(LOG,
966  (errcode(ERRCODE_INSUFFICIENT_RESOURCES),
967  errmsg("out of file descriptors: %m; release and retry")));
968  errno = 0;
969  if (ReleaseLruFile())
970  goto tryAgain;
971  errno = save_errno;
972  }
973 
974  return -1; /* failure */
975 }
int errcode(int sqlerrcode)
Definition: elog.c:575
#define LOG
Definition: elog.h:26
static int fd(const char *x, int i)
Definition: preproc-init.c:105
static bool ReleaseLruFile(void)
Definition: fd.c:1155
#define ereport(elevel, rest)
Definition: elog.h:122
int errmsg(const char *fmt,...)
Definition: elog.c:797
void closeAllVfds ( void  )

Definition at line 2531 of file fd.c.

References Assert, FileIsNotOpen, i, LruDelete(), and SizeVfdCache.

Referenced by standard_ProcessUtility().

2532 {
2533  Index i;
2534 
2535  if (SizeVfdCache > 0)
2536  {
2537  Assert(FileIsNotOpen(0)); /* Make sure ring not corrupted */
2538  for (i = 1; i < SizeVfdCache; i++)
2539  {
2540  if (!FileIsNotOpen(i))
2541  LruDelete(i);
2542  }
2543  }
2544 }
static Size SizeVfdCache
Definition: fd.c:203
static void LruDelete(File file)
Definition: fd.c:1018
#define FileIsNotOpen(file)
Definition: fd.c:166
unsigned int Index
Definition: c.h:359
#define Assert(condition)
Definition: c.h:681
int i
int ClosePipeStream ( FILE *  file)

Definition at line 2502 of file fd.c.

References AllocateDescPipe, AllocateDesc::desc, DO_DB, elog, AllocateDesc::file, FreeDesc(), i, AllocateDesc::kind, LOG, numAllocatedDescs, and WARNING.

Referenced by ClosePipeToProgram(), and pg_import_system_collations().

2503 {
2504  int i;
2505 
2506  DO_DB(elog(LOG, "ClosePipeStream: Allocated %d", numAllocatedDescs));
2507 
2508  /* Remove file from list of allocated files, if it's present */
2509  for (i = numAllocatedDescs; --i >= 0;)
2510  {
2511  AllocateDesc *desc = &allocatedDescs[i];
2512 
2513  if (desc->kind == AllocateDescPipe && desc->desc.file == file)
2514  return FreeDesc(desc);
2515  }
2516 
2517  /* Only get here if someone passes us a file not in allocatedDescs */
2518  elog(WARNING, "file passed to ClosePipeStream was not obtained from OpenPipeStream");
2519 
2520  return pclose(file);
2521 }
static AllocateDesc * allocatedDescs
Definition: fd.c:250
#define DO_DB(A)
Definition: fd.c:157
#define LOG
Definition: elog.h:26
AllocateDescKind kind
Definition: fd.c:238
static int FreeDesc(AllocateDesc *desc)
Definition: fd.c:2270
#define WARNING
Definition: elog.h:40
FILE * file
Definition: fd.c:242
union AllocateDesc::@27 desc
int i
#define elog
Definition: elog.h:219
static int numAllocatedDescs
Definition: fd.c:248
int CloseTransientFile ( int  fd)

Definition at line 2337 of file fd.c.

References AllocateDescRawFD, close, AllocateDesc::desc, DO_DB, elog, AllocateDesc::fd, FreeDesc(), i, AllocateDesc::kind, LOG, numAllocatedDescs, and WARNING.

Referenced by be_lo_export(), CheckPointLogicalRewriteHeap(), CheckPointReplicationOrigin(), copy_file(), dsm_impl_mmap(), durable_rename(), fsync_fname_ext(), heap_xlog_logical_rewrite(), lo_import_internal(), load_relmap_file(), mdunlinkfork(), qtext_load_file(), qtext_store(), ReadTwoPhaseFile(), RecreateTwoPhaseFile(), ReorderBufferIterTXNFinish(), ReorderBufferRestoreChanges(), ReorderBufferSerializeChange(), ReorderBufferSerializeTXN(), RestoreSlotFromDisk(), SaveSlotToPath(), SendTimeLineHistory(), SimpleLruDoesPhysicalPageExist(), SimpleLruFlush(), SlruInternalWritePage(), SlruPhysicalReadPage(), SlruPhysicalWritePage(), SnapBuildRestore(), SnapBuildSerialize(), StartupReplicationOrigin(), write_relmap_file(), writeTimeLineHistory(), writeTimeLineHistoryFile(), and XLogFileCopy().

2338 {
2339  int i;
2340 
2341  DO_DB(elog(LOG, "CloseTransientFile: Allocated %d", numAllocatedDescs));
2342 
2343  /* Remove fd from list of allocated files, if it's present */
2344  for (i = numAllocatedDescs; --i >= 0;)
2345  {
2346  AllocateDesc *desc = &allocatedDescs[i];
2347 
2348  if (desc->kind == AllocateDescRawFD && desc->desc.fd == fd)
2349  return FreeDesc(desc);
2350  }
2351 
2352  /* Only get here if someone passes us a file not in allocatedDescs */
2353  elog(WARNING, "fd passed to CloseTransientFile was not obtained from OpenTransientFile");
2354 
2355  return close(fd);
2356 }
static AllocateDesc * allocatedDescs
Definition: fd.c:250
#define DO_DB(A)
Definition: fd.c:157
#define LOG
Definition: elog.h:26
AllocateDescKind kind
Definition: fd.c:238
static int fd(const char *x, int i)
Definition: preproc-init.c:105
static int FreeDesc(AllocateDesc *desc)
Definition: fd.c:2270
#define WARNING
Definition: elog.h:40
int fd
Definition: fd.c:244
union AllocateDesc::@27 desc
int i
#define elog
Definition: elog.h:219
#define close(a)
Definition: win32.h:12
static int numAllocatedDescs
Definition: fd.c:248
int durable_link_or_rename ( const char *  oldfile,
const char *  newfile,
int  loglevel 
)

Definition at line 717 of file fd.c.

References ereport, errcode_for_file_access(), errmsg(), fsync_fname_ext(), fsync_parent_path(), and link().

Referenced by InstallXLogFileSegment(), writeTimeLineHistory(), and writeTimeLineHistoryFile().

718 {
719  /*
720  * Ensure that, if we crash directly after the rename/link, a file with
721  * valid contents is moved into place.
722  */
723  if (fsync_fname_ext(oldfile, false, false, elevel) != 0)
724  return -1;
725 
726 #if HAVE_WORKING_LINK
727  if (link(oldfile, newfile) < 0)
728  {
729  ereport(elevel,
731  errmsg("could not link file \"%s\" to \"%s\": %m",
732  oldfile, newfile)));
733  return -1;
734  }
735  unlink(oldfile);
736 #else
737  /* XXX: Add racy file existence check? */
738  if (rename(oldfile, newfile) < 0)
739  {
740  ereport(elevel,
742  errmsg("could not rename file \"%s\" to \"%s\": %m",
743  oldfile, newfile)));
744  return -1;
745  }
746 #endif
747 
748  /*
749  * Make change persistent in case of an OS crash, both the new entry and
750  * its parent directory need to be flushed.
751  */
752  if (fsync_fname_ext(newfile, false, false, elevel) != 0)
753  return -1;
754 
755  /* Same for parent directory */
756  if (fsync_parent_path(newfile, elevel) != 0)
757  return -1;
758 
759  return 0;
760 }
int errcode_for_file_access(void)
Definition: elog.c:598
#define ereport(elevel, rest)
Definition: elog.h:122
int link(const char *fromname, const char *toname)
static int elevel
Definition: vacuumlazy.c:136
int errmsg(const char *fmt,...)
Definition: elog.c:797
static int fsync_fname_ext(const char *fname, bool isdir, bool ignore_perm, int elevel)
Definition: fd.c:3158
static int fsync_parent_path(const char *fname, int elevel)
Definition: fd.c:3228
int durable_rename ( const char *  oldfile,
const char *  newfile,
int  loglevel 
)

Definition at line 598 of file fd.c.

References CloseTransientFile(), ereport, errcode_for_file_access(), errmsg(), fd(), fsync_fname_ext(), fsync_parent_path(), OpenTransientFile(), PG_BINARY, and pg_fsync().

Referenced by AlterSystemSetConfigFile(), apw_dump_now(), CancelBackup(), CheckPointReplicationOrigin(), dir_close(), exitArchiveRecovery(), KeepFileRestoredFromArchive(), pgarch_archiveDone(), pgss_shmem_shutdown(), StartupXLOG(), and XLogArchiveForceDone().

599 {
600  int fd;
601 
602  /*
603  * First fsync the old and target path (if it exists), to ensure that they
604  * are properly persistent on disk. Syncing the target file is not
605  * strictly necessary, but it makes it easier to reason about crashes;
606  * because it's then guaranteed that either source or target file exists
607  * after a crash.
608  */
609  if (fsync_fname_ext(oldfile, false, false, elevel) != 0)
610  return -1;
611 
612  fd = OpenTransientFile(newfile, PG_BINARY | O_RDWR);
613  if (fd < 0)
614  {
615  if (errno != ENOENT)
616  {
617  ereport(elevel,
619  errmsg("could not open file \"%s\": %m", newfile)));
620  return -1;
621  }
622  }
623  else
624  {
625  if (pg_fsync(fd) != 0)
626  {
627  int save_errno;
628 
629  /* close file upon error, might not be in transaction context */
630  save_errno = errno;
631  CloseTransientFile(fd);
632  errno = save_errno;
633 
634  ereport(elevel,
636  errmsg("could not fsync file \"%s\": %m", newfile)));
637  return -1;
638  }
639  CloseTransientFile(fd);
640  }
641 
642  /* Time to do the real deal... */
643  if (rename(oldfile, newfile) < 0)
644  {
645  ereport(elevel,
647  errmsg("could not rename file \"%s\" to \"%s\": %m",
648  oldfile, newfile)));
649  return -1;
650  }
651 
652  /*
653  * To guarantee renaming the file is persistent, fsync the file with its
654  * new name, and its containing directory.
655  */
656  if (fsync_fname_ext(newfile, false, false, elevel) != 0)
657  return -1;
658 
659  if (fsync_parent_path(newfile, elevel) != 0)
660  return -1;
661 
662  return 0;
663 }
static int fd(const char *x, int i)
Definition: preproc-init.c:105
#define PG_BINARY
Definition: c.h:1044
int OpenTransientFile(const char *fileName, int fileFlags)
Definition: fd.c:2167
int errcode_for_file_access(void)
Definition: elog.c:598
#define ereport(elevel, rest)
Definition: elog.h:122
int CloseTransientFile(int fd)
Definition: fd.c:2337
static int elevel
Definition: vacuumlazy.c:136
int errmsg(const char *fmt,...)
Definition: elog.c:797
static int fsync_fname_ext(const char *fname, bool isdir, bool ignore_perm, int elevel)
Definition: fd.c:3158
int pg_fsync(int fd)
Definition: fd.c:338
static int fsync_parent_path(const char *fname, int elevel)
Definition: fd.c:3228
int durable_unlink ( const char *  fname,
int  loglevel 
)

Definition at line 681 of file fd.c.

References ereport, errcode_for_file_access(), errmsg(), and fsync_parent_path().

Referenced by do_pg_stop_backup(), InstallXLogFileSegment(), and RemoveXlogFile().

682 {
683  if (unlink(fname) < 0)
684  {
685  ereport(elevel,
687  errmsg("could not remove file \"%s\": %m",
688  fname)));
689  return -1;
690  }
691 
692  /*
693  * To guarantee that the removal of the file is persistent, fsync its
694  * parent directory.
695  */
696  if (fsync_parent_path(fname, elevel) != 0)
697  return -1;
698 
699  return 0;
700 }
int errcode_for_file_access(void)
Definition: elog.c:598
#define ereport(elevel, rest)
Definition: elog.h:122
static int elevel
Definition: vacuumlazy.c:136
int errmsg(const char *fmt,...)
Definition: elog.c:797
static int fsync_parent_path(const char *fname, int elevel)
Definition: fd.c:3228
void FileClose ( File  file)

Definition at line 1516 of file fd.c.

References Assert, close, Delete(), DO_DB, elog, ereport, errmsg(), vfd::fd, FD_TEMPORARY, vfd::fdstate, FileIsNotOpen, FileIsValid, vfd::fileName, vfd::fileSize, FreeVfd(), LOG, log_temp_files, nfile, pgstat_report_tempfile(), ResourceOwnerForgetFile(), vfd::resowner, temporary_files_size, and VFD_CLOSED.

Referenced by BufFileClose(), CleanupTempFiles(), logical_end_heap_rewrite(), mdclose(), mdtruncate(), and ResourceOwnerReleaseInternal().

1517 {
1518  Vfd *vfdP;
1519 
1520  Assert(FileIsValid(file));
1521 
1522  DO_DB(elog(LOG, "FileClose: %d (%s)",
1523  file, VfdCache[file].fileName));
1524 
1525  vfdP = &VfdCache[file];
1526 
1527  if (!FileIsNotOpen(file))
1528  {
1529  /* close the file */
1530  if (close(vfdP->fd))
1531  elog(LOG, "could not close file \"%s\": %m", vfdP->fileName);
1532 
1533  --nfile;
1534  vfdP->fd = VFD_CLOSED;
1535 
1536  /* remove the file from the lru ring */
1537  Delete(file);
1538  }
1539 
1540  /*
1541  * Delete the file if it was temporary, and make a log entry if wanted
1542  */
1543  if (vfdP->fdstate & FD_TEMPORARY)
1544  {
1545  struct stat filestats;
1546  int stat_errno;
1547 
1548  /*
1549  * If we get an error, as could happen within the ereport/elog calls,
1550  * we'll come right back here during transaction abort. Reset the
1551  * flag to ensure that we can't get into an infinite loop. This code
1552  * is arranged to ensure that the worst-case consequence is failing to
1553  * emit log message(s), not failing to attempt the unlink.
1554  */
1555  vfdP->fdstate &= ~FD_TEMPORARY;
1556 
1557  /* Subtract its size from current usage (do first in case of error) */
1558  temporary_files_size -= vfdP->fileSize;
1559  vfdP->fileSize = 0;
1560 
1561  /* first try the stat() */
1562  if (stat(vfdP->fileName, &filestats))
1563  stat_errno = errno;
1564  else
1565  stat_errno = 0;
1566 
1567  /* in any case do the unlink */
1568  if (unlink(vfdP->fileName))
1569  elog(LOG, "could not unlink file \"%s\": %m", vfdP->fileName);
1570 
1571  /* and last report the stat results */
1572  if (stat_errno == 0)
1573  {
1574  pgstat_report_tempfile(filestats.st_size);
1575 
1576  if (log_temp_files >= 0)
1577  {
1578  if ((filestats.st_size / 1024) >= log_temp_files)
1579  ereport(LOG,
1580  (errmsg("temporary file: path \"%s\", size %lu",
1581  vfdP->fileName,
1582  (unsigned long) filestats.st_size)));
1583  }
1584  }
1585  else
1586  {
1587  errno = stat_errno;
1588  elog(LOG, "could not stat file \"%s\": %m", vfdP->fileName);
1589  }
1590  }
1591 
1592  /* Unregister it from the resource owner */
1593  if (vfdP->resowner)
1594  ResourceOwnerForgetFile(vfdP->resowner, file);
1595 
1596  /*
1597  * Return the Vfd slot to the free list
1598  */
1599  FreeVfd(file);
1600 }
#define DO_DB(A)
Definition: fd.c:157
int log_temp_files
Definition: guc.c:454
static Vfd * VfdCache
Definition: fd.c:202
static void Delete(File file)
Definition: fd.c:999
void pgstat_report_tempfile(size_t filesize)
Definition: pgstat.c:1525
#define LOG
Definition: elog.h:26
char * fileName
Definition: fd.c:191
static int nfile
Definition: fd.c:208
unsigned short fdstate
Definition: fd.c:184
Definition: fd.c:181
off_t fileSize
Definition: fd.c:190
int fd
Definition: fd.c:183
#define ereport(elevel, rest)
Definition: elog.h:122
ResourceOwner resowner
Definition: fd.c:185
#define FileIsNotOpen(file)
Definition: fd.c:166
#define FD_TEMPORARY
Definition: fd.c:178
#define FileIsValid(file)
Definition: fd.c:163
#define VFD_CLOSED
Definition: fd.c:161
static uint64 temporary_files_size
Definition: fd.c:222
#define Assert(condition)
Definition: c.h:681
int errmsg(const char *fmt,...)
Definition: elog.c:797
static void FreeVfd(File file)
Definition: fd.c:1245
#define elog
Definition: elog.h:219
#define close(a)
Definition: win32.h:12
void ResourceOwnerForgetFile(ResourceOwner owner, File file)
Definition: resowner.c:1195
int FileGetRawDesc ( File  file)

Definition at line 2013 of file fd.c.

References Assert, vfd::fd, and FileIsValid.

2014 {
2015  Assert(FileIsValid(file));
2016  return VfdCache[file].fd;
2017 }
static Vfd * VfdCache
Definition: fd.c:202
int fd
Definition: fd.c:183
#define FileIsValid(file)
Definition: fd.c:163
#define Assert(condition)
Definition: c.h:681
int FileGetRawFlags ( File  file)

Definition at line 2023 of file fd.c.

References Assert, vfd::fileFlags, and FileIsValid.

2024 {
2025  Assert(FileIsValid(file));
2026  return VfdCache[file].fileFlags;
2027 }
static Vfd * VfdCache
Definition: fd.c:202
#define FileIsValid(file)
Definition: fd.c:163
#define Assert(condition)
Definition: c.h:681
int fileFlags
Definition: fd.c:193
mode_t FileGetRawMode ( File  file)

Definition at line 2033 of file fd.c.

References Assert, FileIsValid, and vfd::fileMode.

2034 {
2035  Assert(FileIsValid(file));
2036  return VfdCache[file].fileMode;
2037 }
static Vfd * VfdCache
Definition: fd.c:202
mode_t fileMode
Definition: fd.c:194
#define FileIsValid(file)
Definition: fd.c:163
#define Assert(condition)
Definition: c.h:681
char* FilePathName ( File  file)

Definition at line 1997 of file fd.c.

References Assert, FileIsValid, and vfd::fileName.

Referenced by _mdnblocks(), mdextend(), mdimmedsync(), mdread(), mdsync(), mdtruncate(), mdwrite(), and register_dirty_segment().

1998 {
1999  Assert(FileIsValid(file));
2000 
2001  return VfdCache[file].fileName;
2002 }
static Vfd * VfdCache
Definition: fd.c:202
char * fileName
Definition: fd.c:191
#define FileIsValid(file)
Definition: fd.c:163
#define Assert(condition)
Definition: c.h:681
int FilePrefetch ( File  file,
off_t  offset,
int  amount,
uint32  wait_event_info 
)

Definition at line 1613 of file fd.c.

References Assert, DO_DB, elog, fd(), FileAccess(), FileIsValid, INT64_FORMAT, LOG, pgstat_report_wait_end(), and pgstat_report_wait_start().

Referenced by mdprefetch().

1614 {
1615 #if defined(USE_POSIX_FADVISE) && defined(POSIX_FADV_WILLNEED)
1616  int returnCode;
1617 
1618  Assert(FileIsValid(file));
1619 
1620  DO_DB(elog(LOG, "FilePrefetch: %d (%s) " INT64_FORMAT " %d",
1621  file, VfdCache[file].fileName,
1622  (int64) offset, amount));
1623 
1624  returnCode = FileAccess(file);
1625  if (returnCode < 0)
1626  return returnCode;
1627 
1628  pgstat_report_wait_start(wait_event_info);
1629  returnCode = posix_fadvise(VfdCache[file].fd, offset, amount,
1630  POSIX_FADV_WILLNEED);
1632 
1633  return returnCode;
1634 #else
1635  Assert(FileIsValid(file));
1636  return 0;
1637 #endif
1638 }
#define DO_DB(A)
Definition: fd.c:157
static Vfd * VfdCache
Definition: fd.c:202
#define LOG
Definition: elog.h:26
static int fd(const char *x, int i)
Definition: preproc-init.c:105
static void pgstat_report_wait_end(void)
Definition: pgstat.h:1244
#define FileIsValid(file)
Definition: fd.c:163
static int FileAccess(File file)
Definition: fd.c:1265
#define Assert(condition)
Definition: c.h:681
static void pgstat_report_wait_start(uint32 wait_event_info)
Definition: pgstat.h:1220
#define INT64_FORMAT
Definition: c.h:300
#define elog
Definition: elog.h:219
int FileRead ( File  file,
char *  buffer,
int  amount,
uint32  wait_event_info 
)

Definition at line 1668 of file fd.c.

References _dosmaperr(), Assert, DO_DB, EINTR, elog, error(), vfd::fd, FileAccess(), FileIsValid, FilePosIsUnknown, FileUnknownPos, INT64_FORMAT, LOG, pg_usleep(), pgstat_report_wait_end(), pgstat_report_wait_start(), read, and vfd::seekPos.

Referenced by BufFileLoadBuffer(), and mdread().

1669 {
1670  int returnCode;
1671  Vfd *vfdP;
1672 
1673  Assert(FileIsValid(file));
1674 
1675  DO_DB(elog(LOG, "FileRead: %d (%s) " INT64_FORMAT " %d %p",
1676  file, VfdCache[file].fileName,
1677  (int64) VfdCache[file].seekPos,
1678  amount, buffer));
1679 
1680  returnCode = FileAccess(file);
1681  if (returnCode < 0)
1682  return returnCode;
1683 
1684  vfdP = &VfdCache[file];
1685 
1686 retry:
1687  pgstat_report_wait_start(wait_event_info);
1688  returnCode = read(vfdP->fd, buffer, amount);
1690 
1691  if (returnCode >= 0)
1692  {
1693  /* if seekPos is unknown, leave it that way */
1694  if (!FilePosIsUnknown(vfdP->seekPos))
1695  vfdP->seekPos += returnCode;
1696  }
1697  else
1698  {
1699  /*
1700  * Windows may run out of kernel buffers and return "Insufficient
1701  * system resources" error. Wait a bit and retry to solve it.
1702  *
1703  * It is rumored that EINTR is also possible on some Unix filesystems,
1704  * in which case immediate retry is indicated.
1705  */
1706 #ifdef WIN32
1707  DWORD error = GetLastError();
1708 
1709  switch (error)
1710  {
1711  case ERROR_NO_SYSTEM_RESOURCES:
1712  pg_usleep(1000L);
1713  errno = EINTR;
1714  break;
1715  default:
1716  _dosmaperr(error);
1717  break;
1718  }
1719 #endif
1720  /* OK to retry if interrupted */
1721  if (errno == EINTR)
1722  goto retry;
1723 
1724  /* Trouble, so assume we don't know the file position anymore */
1725  vfdP->seekPos = FileUnknownPos;
1726  }
1727 
1728  return returnCode;
1729 }
static void error(void)
Definition: sql-dyntest.c:147
#define DO_DB(A)
Definition: fd.c:157
static Vfd * VfdCache
Definition: fd.c:202
#define LOG
Definition: elog.h:26
#define FilePosIsUnknown(pos)
Definition: fd.c:175
void pg_usleep(long microsec)
Definition: signal.c:53
static void pgstat_report_wait_end(void)
Definition: pgstat.h:1244
off_t seekPos
Definition: fd.c:189
Definition: fd.c:181
int fd
Definition: fd.c:183
#define EINTR
Definition: win32.h:285
#define FileIsValid(file)
Definition: fd.c:163
static int FileAccess(File file)
Definition: fd.c:1265
#define Assert(condition)
Definition: c.h:681
void _dosmaperr(unsigned long)
Definition: win32error.c:171
WalTimeSample buffer[LAG_TRACKER_BUFFER_SIZE]
Definition: walsender.c:214
static void pgstat_report_wait_start(uint32 wait_event_info)
Definition: pgstat.h:1220
#define INT64_FORMAT
Definition: c.h:300
#define elog
Definition: elog.h:219
#define FileUnknownPos
Definition: fd.c:174
#define read(a, b, c)
Definition: win32.h:13
off_t FileSeek ( File  file,
off_t  offset,
int  whence 
)

Definition at line 1874 of file fd.c.

References Assert, DO_DB, elog, ERROR, vfd::fd, FileAccess(), FileIsNotOpen, FileIsValid, FilePosIsUnknown, INT64_FORMAT, LOG, and vfd::seekPos.

Referenced by _mdnblocks(), BufFileDumpBuffer(), BufFileLoadBuffer(), mdextend(), mdread(), and mdwrite().

1875 {
1876  Vfd *vfdP;
1877 
1878  Assert(FileIsValid(file));
1879 
1880  DO_DB(elog(LOG, "FileSeek: %d (%s) " INT64_FORMAT " " INT64_FORMAT " %d",
1881  file, VfdCache[file].fileName,
1882  (int64) VfdCache[file].seekPos,
1883  (int64) offset, whence));
1884 
1885  vfdP = &VfdCache[file];
1886 
1887  if (FileIsNotOpen(file))
1888  {
1889  switch (whence)
1890  {
1891  case SEEK_SET:
1892  if (offset < 0)
1893  {
1894  errno = EINVAL;
1895  return (off_t) -1;
1896  }
1897  vfdP->seekPos = offset;
1898  break;
1899  case SEEK_CUR:
1900  if (FilePosIsUnknown(vfdP->seekPos) ||
1901  vfdP->seekPos + offset < 0)
1902  {
1903  errno = EINVAL;
1904  return (off_t) -1;
1905  }
1906  vfdP->seekPos += offset;
1907  break;
1908  case SEEK_END:
1909  if (FileAccess(file) < 0)
1910  return (off_t) -1;
1911  vfdP->seekPos = lseek(vfdP->fd, offset, whence);
1912  break;
1913  default:
1914  elog(ERROR, "invalid whence: %d", whence);
1915  break;
1916  }
1917  }
1918  else
1919  {
1920  switch (whence)
1921  {
1922  case SEEK_SET:
1923  if (offset < 0)
1924  {
1925  errno = EINVAL;
1926  return (off_t) -1;
1927  }
1928  if (vfdP->seekPos != offset)
1929  vfdP->seekPos = lseek(vfdP->fd, offset, whence);
1930  break;
1931  case SEEK_CUR:
1932  if (offset != 0 || FilePosIsUnknown(vfdP->seekPos))
1933  vfdP->seekPos = lseek(vfdP->fd, offset, whence);
1934  break;
1935  case SEEK_END:
1936  vfdP->seekPos = lseek(vfdP->fd, offset, whence);
1937  break;
1938  default:
1939  elog(ERROR, "invalid whence: %d", whence);
1940  break;
1941  }
1942  }
1943 
1944  return vfdP->seekPos;
1945 }
#define DO_DB(A)
Definition: fd.c:157
static Vfd * VfdCache
Definition: fd.c:202
#define LOG
Definition: elog.h:26
#define FilePosIsUnknown(pos)
Definition: fd.c:175
#define ERROR
Definition: elog.h:43
off_t seekPos
Definition: fd.c:189
Definition: fd.c:181
int fd
Definition: fd.c:183
#define FileIsNotOpen(file)
Definition: fd.c:166
#define FileIsValid(file)
Definition: fd.c:163
static int FileAccess(File file)
Definition: fd.c:1265
#define Assert(condition)
Definition: c.h:681
#define INT64_FORMAT
Definition: c.h:300
#define elog
Definition: elog.h:219
int FileSync ( File  file,
uint32  wait_event_info 
)

Definition at line 1853 of file fd.c.

References Assert, DO_DB, elog, fd(), FileAccess(), FileIsValid, LOG, pg_fsync(), pgstat_report_wait_end(), and pgstat_report_wait_start().

Referenced by logical_end_heap_rewrite(), mdimmedsync(), mdsync(), and register_dirty_segment().

1854 {
1855  int returnCode;
1856 
1857  Assert(FileIsValid(file));
1858 
1859  DO_DB(elog(LOG, "FileSync: %d (%s)",
1860  file, VfdCache[file].fileName));
1861 
1862  returnCode = FileAccess(file);
1863  if (returnCode < 0)
1864  return returnCode;
1865 
1866  pgstat_report_wait_start(wait_event_info);
1867  returnCode = pg_fsync(VfdCache[file].fd);
1869 
1870  return returnCode;
1871 }
#define DO_DB(A)
Definition: fd.c:157
static Vfd * VfdCache
Definition: fd.c:202
#define LOG
Definition: elog.h:26
static int fd(const char *x, int i)
Definition: preproc-init.c:105
static void pgstat_report_wait_end(void)
Definition: pgstat.h:1244
#define FileIsValid(file)
Definition: fd.c:163
static int FileAccess(File file)
Definition: fd.c:1265
#define Assert(condition)
Definition: c.h:681
static void pgstat_report_wait_start(uint32 wait_event_info)
Definition: pgstat.h:1220
int pg_fsync(int fd)
Definition: fd.c:338
#define elog
Definition: elog.h:219
int FileTruncate ( File  file,
off_t  offset,
uint32  wait_event_info 
)

Definition at line 1962 of file fd.c.

References Assert, DO_DB, elog, fd(), FD_TEMPORARY, FileAccess(), FileIsValid, vfd::fileSize, ftruncate, LOG, pgstat_report_wait_end(), pgstat_report_wait_start(), and temporary_files_size.

Referenced by mdtruncate().

1963 {
1964  int returnCode;
1965 
1966  Assert(FileIsValid(file));
1967 
1968  DO_DB(elog(LOG, "FileTruncate %d (%s)",
1969  file, VfdCache[file].fileName));
1970 
1971  returnCode = FileAccess(file);
1972  if (returnCode < 0)
1973  return returnCode;
1974 
1975  pgstat_report_wait_start(wait_event_info);
1976  returnCode = ftruncate(VfdCache[file].fd, offset);
1978 
1979  if (returnCode == 0 && VfdCache[file].fileSize > offset)
1980  {
1981  /* adjust our state for truncation of a temp file */
1982  Assert(VfdCache[file].fdstate & FD_TEMPORARY);
1983  temporary_files_size -= VfdCache[file].fileSize - offset;
1984  VfdCache[file].fileSize = offset;
1985  }
1986 
1987  return returnCode;
1988 }
#define DO_DB(A)
Definition: fd.c:157
static Vfd * VfdCache
Definition: fd.c:202
#define LOG
Definition: elog.h:26
static int fd(const char *x, int i)
Definition: preproc-init.c:105
static void pgstat_report_wait_end(void)
Definition: pgstat.h:1244
off_t fileSize
Definition: fd.c:190
#define FD_TEMPORARY
Definition: fd.c:178
#define FileIsValid(file)
Definition: fd.c:163
static uint64 temporary_files_size
Definition: fd.c:222
#define ftruncate(a, b)
Definition: win32.h:59
static int FileAccess(File file)
Definition: fd.c:1265
#define Assert(condition)
Definition: c.h:681
static void pgstat_report_wait_start(uint32 wait_event_info)
Definition: pgstat.h:1220
#define elog
Definition: elog.h:219
int FileWrite ( File  file,
char *  buffer,
int  amount,
uint32  wait_event_info 
)

Definition at line 1732 of file fd.c.

References _dosmaperr(), Assert, DO_DB, EINTR, elog, ereport, errcode(), errmsg(), ERROR, error(), vfd::fd, FD_TEMPORARY, vfd::fdstate, FileAccess(), FileIsValid, vfd::fileName, FilePosIsUnknown, vfd::fileSize, FileUnknownPos, INT64_FORMAT, LOG, pg_usleep(), pgstat_report_wait_end(), pgstat_report_wait_start(), vfd::seekPos, temp_file_limit, temporary_files_size, and write.

Referenced by BufFileDumpBuffer(), logical_heap_rewrite_flush_mappings(), mdextend(), and mdwrite().

1733 {
1734  int returnCode;
1735  Vfd *vfdP;
1736 
1737  Assert(FileIsValid(file));
1738 
1739  DO_DB(elog(LOG, "FileWrite: %d (%s) " INT64_FORMAT " %d %p",
1740  file, VfdCache[file].fileName,
1741  (int64) VfdCache[file].seekPos,
1742  amount, buffer));
1743 
1744  returnCode = FileAccess(file);
1745  if (returnCode < 0)
1746  return returnCode;
1747 
1748  vfdP = &VfdCache[file];
1749 
1750  /*
1751  * If enforcing temp_file_limit and it's a temp file, check to see if the
1752  * write would overrun temp_file_limit, and throw error if so. Note: it's
1753  * really a modularity violation to throw error here; we should set errno
1754  * and return -1. However, there's no way to report a suitable error
1755  * message if we do that. All current callers would just throw error
1756  * immediately anyway, so this is safe at present.
1757  */
1758  if (temp_file_limit >= 0 && (vfdP->fdstate & FD_TEMPORARY))
1759  {
1760  off_t newPos;
1761 
1762  /*
1763  * Normally we should know the seek position, but if for some reason
1764  * we have lost track of it, try again to get it. Here, it's fine to
1765  * throw an error if we still can't get it.
1766  */
1767  if (FilePosIsUnknown(vfdP->seekPos))
1768  {
1769  vfdP->seekPos = lseek(vfdP->fd, (off_t) 0, SEEK_CUR);
1770  if (FilePosIsUnknown(vfdP->seekPos))
1771  elog(ERROR, "could not seek file \"%s\": %m", vfdP->fileName);
1772  }
1773 
1774  newPos = vfdP->seekPos + amount;
1775  if (newPos > vfdP->fileSize)
1776  {
1777  uint64 newTotal = temporary_files_size;
1778 
1779  newTotal += newPos - vfdP->fileSize;
1780  if (newTotal > (uint64) temp_file_limit * (uint64) 1024)
1781  ereport(ERROR,
1782  (errcode(ERRCODE_CONFIGURATION_LIMIT_EXCEEDED),
1783  errmsg("temporary file size exceeds temp_file_limit (%dkB)",
1784  temp_file_limit)));
1785  }
1786  }
1787 
1788 retry:
1789  errno = 0;
1790  pgstat_report_wait_start(wait_event_info);
1791  returnCode = write(vfdP->fd, buffer, amount);
1793 
1794  /* if write didn't set errno, assume problem is no disk space */
1795  if (returnCode != amount && errno == 0)
1796  errno = ENOSPC;
1797 
1798  if (returnCode >= 0)
1799  {
1800  /* if seekPos is unknown, leave it that way */
1801  if (!FilePosIsUnknown(vfdP->seekPos))
1802  vfdP->seekPos += returnCode;
1803 
1804  /*
1805  * Maintain fileSize and temporary_files_size if it's a temp file.
1806  *
1807  * If seekPos is -1 (unknown), this will do nothing; but we could only
1808  * get here in that state if we're not enforcing temporary_files_size,
1809  * so we don't care.
1810  */
1811  if (vfdP->fdstate & FD_TEMPORARY)
1812  {
1813  off_t newPos = vfdP->seekPos;
1814 
1815  if (newPos > vfdP->fileSize)
1816  {
1817  temporary_files_size += newPos - vfdP->fileSize;
1818  vfdP->fileSize = newPos;
1819  }
1820  }
1821  }
1822  else
1823  {
1824  /*
1825  * See comments in FileRead()
1826  */
1827 #ifdef WIN32
1828  DWORD error = GetLastError();
1829 
1830  switch (error)
1831  {
1832  case ERROR_NO_SYSTEM_RESOURCES:
1833  pg_usleep(1000L);
1834  errno = EINTR;
1835  break;
1836  default:
1837  _dosmaperr(error);
1838  break;
1839  }
1840 #endif
1841  /* OK to retry if interrupted */
1842  if (errno == EINTR)
1843  goto retry;
1844 
1845  /* Trouble, so assume we don't know the file position anymore */
1846  vfdP->seekPos = FileUnknownPos;
1847  }
1848 
1849  return returnCode;
1850 }
static void error(void)
Definition: sql-dyntest.c:147
#define write(a, b, c)
Definition: win32.h:14
#define DO_DB(A)
Definition: fd.c:157
static Vfd * VfdCache
Definition: fd.c:202
int errcode(int sqlerrcode)
Definition: elog.c:575
#define LOG
Definition: elog.h:26
#define FilePosIsUnknown(pos)
Definition: fd.c:175
void pg_usleep(long microsec)
Definition: signal.c:53
#define ERROR
Definition: elog.h:43
char * fileName
Definition: fd.c:191
static void pgstat_report_wait_end(void)
Definition: pgstat.h:1244
off_t seekPos
Definition: fd.c:189
unsigned short fdstate
Definition: fd.c:184
Definition: fd.c:181
off_t fileSize
Definition: fd.c:190
int fd
Definition: fd.c:183
#define ereport(elevel, rest)
Definition: elog.h:122
#define FD_TEMPORARY
Definition: fd.c:178
#define EINTR
Definition: win32.h:285
#define FileIsValid(file)
Definition: fd.c:163
static uint64 temporary_files_size
Definition: fd.c:222
static int FileAccess(File file)
Definition: fd.c:1265
#define Assert(condition)
Definition: c.h:681
void _dosmaperr(unsigned long)
Definition: win32error.c:171
WalTimeSample buffer[LAG_TRACKER_BUFFER_SIZE]
Definition: walsender.c:214
static void pgstat_report_wait_start(uint32 wait_event_info)
Definition: pgstat.h:1220
#define INT64_FORMAT
Definition: c.h:300
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define elog
Definition: elog.h:219
#define FileUnknownPos
Definition: fd.c:174
int temp_file_limit
Definition: guc.c:457
void FileWriteback ( File  file,
off_t  offset,
off_t  nbytes,
uint32  wait_event_info 
)

Definition at line 1641 of file fd.c.

References Assert, DO_DB, elog, fd(), FileAccess(), FileIsValid, INT64_FORMAT, LOG, pg_flush_data(), pgstat_report_wait_end(), and pgstat_report_wait_start().

Referenced by mdwriteback().

1642 {
1643  int returnCode;
1644 
1645  Assert(FileIsValid(file));
1646 
1647  DO_DB(elog(LOG, "FileWriteback: %d (%s) " INT64_FORMAT " " INT64_FORMAT,
1648  file, VfdCache[file].fileName,
1649  (int64) offset, (int64) nbytes));
1650 
1651  /*
1652  * Caution: do not call pg_flush_data with nbytes = 0, it could trash the
1653  * file's seek position. We prefer to define that as a no-op here.
1654  */
1655  if (nbytes <= 0)
1656  return;
1657 
1658  returnCode = FileAccess(file);
1659  if (returnCode < 0)
1660  return;
1661 
1662  pgstat_report_wait_start(wait_event_info);
1663  pg_flush_data(VfdCache[file].fd, offset, nbytes);
1665 }
#define DO_DB(A)
Definition: fd.c:157
static Vfd * VfdCache
Definition: fd.c:202
#define LOG
Definition: elog.h:26
static int fd(const char *x, int i)
Definition: preproc-init.c:105
static void pgstat_report_wait_end(void)
Definition: pgstat.h:1244
void pg_flush_data(int fd, off_t offset, off_t nbytes)
Definition: fd.c:412
#define FileIsValid(file)
Definition: fd.c:163
static int FileAccess(File file)
Definition: fd.c:1265
#define Assert(condition)
Definition: c.h:681
static void pgstat_report_wait_start(uint32 wait_event_info)
Definition: pgstat.h:1220
#define INT64_FORMAT
Definition: c.h:300
#define elog
Definition: elog.h:219
int FreeDir ( DIR dir)

Definition at line 2476 of file fd.c.

References AllocateDescDir, closedir(), AllocateDesc::desc, AllocateDesc::dir, DO_DB, elog, FreeDesc(), i, AllocateDesc::kind, LOG, numAllocatedDescs, and WARNING.

Referenced by calculate_database_size(), calculate_tablespace_size(), CheckPointLogicalRewriteHeap(), CheckPointSnapBuild(), CleanupBackupHistory(), copydir(), db_dir_size(), DeleteAllExportedSnapshotFiles(), destroy_tablespace_directories(), directory_is_empty(), dsm_cleanup_for_mmap(), get_ext_ver_list(), getInstallationPaths(), movedb(), ParseTzFile(), perform_base_backup(), pg_available_extension_versions(), pg_available_extensions(), pg_logdir_ls(), pg_ls_dir(), pg_ls_dir_files(), pg_start_backup(), pg_tablespace_databases(), pg_tzenumerate_end(), pg_tzenumerate_next(), pgarch_readyXlog(), pgstat_reset_remove_files(), RelationCacheInitFileRemove(), RelationCacheInitFileRemoveInDir(), RemoveNonParentXlogFiles(), RemoveOldXlogFiles(), RemovePgTempFiles(), RemovePgTempFilesInDir(), RemovePgTempRelationFiles(), RemovePgTempRelationFilesInDbspace(), ResetUnloggedRelations(), ResetUnloggedRelationsInDbspaceDir(), ResetUnloggedRelationsInTablespaceDir(), restoreTwoPhaseData(), scan_directory_ci(), SendBaseBackup(), sendDir(), SlruScanDirectory(), StartupReorderBuffer(), StartupReplicationSlots(), UpdateLogicalMappings(), and walkdir().

2477 {
2478  int i;
2479 
2480  DO_DB(elog(LOG, "FreeDir: Allocated %d", numAllocatedDescs));
2481 
2482  /* Remove dir from list of allocated dirs, if it's present */
2483  for (i = numAllocatedDescs; --i >= 0;)
2484  {
2485  AllocateDesc *desc = &allocatedDescs[i];
2486 
2487  if (desc->kind == AllocateDescDir && desc->desc.dir == dir)
2488  return FreeDesc(desc);
2489  }
2490 
2491  /* Only get here if someone passes us a dir not in allocatedDescs */
2492  elog(WARNING, "dir passed to FreeDir was not obtained from AllocateDir");
2493 
2494  return closedir(dir);
2495 }
static AllocateDesc * allocatedDescs
Definition: fd.c:250
DIR * dir
Definition: fd.c:243
#define DO_DB(A)
Definition: fd.c:157
int closedir(DIR *)
Definition: dirent.c:111
#define LOG
Definition: elog.h:26
AllocateDescKind kind
Definition: fd.c:238
static int FreeDesc(AllocateDesc *desc)
Definition: fd.c:2270
#define WARNING
Definition: elog.h:40
union AllocateDesc::@27 desc
int i
#define elog
Definition: elog.h:219
static int numAllocatedDescs
Definition: fd.c:248
int FreeFile ( FILE *  file)

Definition at line 2309 of file fd.c.

References AllocateDescFile, AllocateDesc::desc, DO_DB, elog, AllocateDesc::file, FreeDesc(), i, AllocateDesc::kind, LOG, numAllocatedDescs, and WARNING.

Referenced by AlterSystemSetConfigFile(), apw_dump_now(), apw_load_buffers(), checkDataDir(), do_pg_start_backup(), do_pg_stop_backup(), EndCopy(), entry_reset(), existsTimeLineHistory(), ExportSnapshot(), fill_hba_view(), gc_qtexts(), ImportSnapshot(), load_dh_file(), load_hba(), load_ident(), load_relcache_init_file(), parse_extension_control_file(), ParseTzFile(), perform_base_backup(), pg_backup_start_time(), pg_current_logfile(), pg_file_write(), pgss_shmem_shutdown(), pgss_shmem_startup(), pgstat_read_db_statsfile(), pgstat_read_db_statsfile_timestamp(), pgstat_read_statsfiles(), pgstat_write_db_statsfile(), pgstat_write_statsfiles(), read_backup_label(), read_binary_file(), read_tablespace_map(), read_whole_file(), readRecoveryCommandFile(), readTimeLineHistory(), sendFile(), tokenize_inc_file(), tsearch_readline_end(), ValidatePgVersion(), write_relcache_init_file(), XLogArchiveForceDone(), and XLogArchiveNotify().

2310 {
2311  int i;
2312 
2313  DO_DB(elog(LOG, "FreeFile: Allocated %d", numAllocatedDescs));
2314 
2315  /* Remove file from list of allocated files, if it's present */
2316  for (i = numAllocatedDescs; --i >= 0;)
2317  {
2318  AllocateDesc *desc = &allocatedDescs[i];
2319 
2320  if (desc->kind == AllocateDescFile && desc->desc.file == file)
2321  return FreeDesc(desc);
2322  }
2323 
2324  /* Only get here if someone passes us a file not in allocatedDescs */
2325  elog(WARNING, "file passed to FreeFile was not obtained from AllocateFile");
2326 
2327  return fclose(file);
2328 }
static AllocateDesc * allocatedDescs
Definition: fd.c:250
#define DO_DB(A)
Definition: fd.c:157
#define LOG
Definition: elog.h:26
AllocateDescKind kind
Definition: fd.c:238
static int FreeDesc(AllocateDesc *desc)
Definition: fd.c:2270
#define WARNING
Definition: elog.h:40
FILE * file
Definition: fd.c:242
union AllocateDesc::@27 desc
int i
#define elog
Definition: elog.h:219
static int numAllocatedDescs
Definition: fd.c:248
void fsync_fname ( const char *  fname,
bool  isdir 
)
Oid GetNextTempTableSpace ( void  )

Definition at line 2597 of file fd.c.

References InvalidOid, nextTempTableSpace, numTempTableSpaces, and tempTableSpaces.

Referenced by GetDefaultTablespace(), and OpenTemporaryFile().

2598 {
2599  if (numTempTableSpaces > 0)
2600  {
2601  /* Advance nextTempTableSpace counter with wraparound */
2603  nextTempTableSpace = 0;
2605  }
2606  return InvalidOid;
2607 }
static int numTempTableSpaces
Definition: fd.c:263
static int nextTempTableSpace
Definition: fd.c:264
#define InvalidOid
Definition: postgres_ext.h:36
static Oid * tempTableSpaces
Definition: fd.c:262
void InitFileAccess ( void  )

Definition at line 769 of file fd.c.

References Assert, AtProcExit_Files(), ereport, errcode(), errmsg(), FATAL, vfd::fd, malloc, MemSet, on_proc_exit(), SizeVfdCache, and VFD_CLOSED.

Referenced by BaseInit().

770 {
771  Assert(SizeVfdCache == 0); /* call me only once */
772 
773  /* initialize cache header entry */
774  VfdCache = (Vfd *) malloc(sizeof(Vfd));
775  if (VfdCache == NULL)
776  ereport(FATAL,
777  (errcode(ERRCODE_OUT_OF_MEMORY),
778  errmsg("out of memory")));
779 
780  MemSet((char *) &(VfdCache[0]), 0, sizeof(Vfd));
782 
783  SizeVfdCache = 1;
784 
785  /* register proc-exit hook to ensure temp files are dropped at exit */
787 }
static void AtProcExit_Files(int code, Datum arg)
Definition: fd.c:2663
static Size SizeVfdCache
Definition: fd.c:203
void on_proc_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:292
static Vfd * VfdCache
Definition: fd.c:202
int errcode(int sqlerrcode)
Definition: elog.c:575
#define MemSet(start, val, len)
Definition: c.h:863
#define malloc(a)
Definition: header.h:50
#define FATAL
Definition: elog.h:52
Definition: fd.c:181
int fd
Definition: fd.c:183
#define ereport(elevel, rest)
Definition: elog.h:122
#define VFD_CLOSED
Definition: fd.c:161
#define Assert(condition)
Definition: c.h:681
int errmsg(const char *fmt,...)
Definition: elog.c:797
FILE* OpenPipeStream ( const char *  command,
const char *  mode 
)

Definition at line 2216 of file fd.c.

References AllocateDescPipe, AllocateDesc::create_subid, AllocateDesc::desc, DO_DB, elog, ereport, errcode(), errmsg(), ERROR, AllocateDesc::file, GetCurrentSubTransactionId(), AllocateDesc::kind, LOG, maxAllocatedDescs, numAllocatedDescs, ReleaseLruFile(), ReleaseLruFiles(), and reserveAllocatedDesc().

Referenced by BeginCopyFrom(), BeginCopyTo(), and pg_import_system_collations().

2217 {
2218  FILE *file;
2219 
2220  DO_DB(elog(LOG, "OpenPipeStream: Allocated %d (%s)",
2221  numAllocatedDescs, command));
2222 
2223  /* Can we allocate another non-virtual FD? */
2224  if (!reserveAllocatedDesc())
2225  ereport(ERROR,
2226  (errcode(ERRCODE_INSUFFICIENT_RESOURCES),
2227  errmsg("exceeded maxAllocatedDescs (%d) while trying to execute command \"%s\"",
2228  maxAllocatedDescs, command)));
2229 
2230  /* Close excess kernel FDs. */
2231  ReleaseLruFiles();
2232 
2233 TryAgain:
2234  fflush(stdout);
2235  fflush(stderr);
2236  errno = 0;
2237  if ((file = popen(command, mode)) != NULL)
2238  {
2240 
2241  desc->kind = AllocateDescPipe;
2242  desc->desc.file = file;
2245  return desc->desc.file;
2246  }
2247 
2248  if (errno == EMFILE || errno == ENFILE)
2249  {
2250  int save_errno = errno;
2251 
2252  ereport(LOG,
2253  (errcode(ERRCODE_INSUFFICIENT_RESOURCES),
2254  errmsg("out of file descriptors: %m; release and retry")));
2255  errno = 0;
2256  if (ReleaseLruFile())
2257  goto TryAgain;
2258  errno = save_errno;
2259  }
2260 
2261  return NULL;
2262 }
static AllocateDesc * allocatedDescs
Definition: fd.c:250
#define DO_DB(A)
Definition: fd.c:157
int errcode(int sqlerrcode)
Definition: elog.c:575
static bool reserveAllocatedDesc(void)
Definition: fd.c:2044
#define LOG
Definition: elog.h:26
AllocateDescKind kind
Definition: fd.c:238
static bool ReleaseLruFile(void)
Definition: fd.c:1155
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:122
static void ReleaseLruFiles(void)
Definition: fd.c:1177
FILE * file
Definition: fd.c:242
SubTransactionId GetCurrentSubTransactionId(void)
Definition: xact.c:642
SubTransactionId create_subid
Definition: fd.c:239
int errmsg(const char *fmt,...)
Definition: elog.c:797
union AllocateDesc::@27 desc
#define elog
Definition: elog.h:219
static int maxAllocatedDescs
Definition: fd.c:249
static int numAllocatedDescs
Definition: fd.c:248
File OpenTemporaryFile ( bool  interXact)

Definition at line 1396 of file fd.c.

References CurrentResourceOwner, DEFAULTTABLESPACE_OID, FD_TEMPORARY, FD_XACT_TEMPORARY, vfd::fdstate, GetNextTempTableSpace(), have_xact_temporary_files, MyDatabaseTableSpace, numTempTableSpaces, OidIsValid, OpenTemporaryFileInTablespace(), ResourceOwnerEnlargeFiles(), ResourceOwnerRememberFile(), and vfd::resowner.

Referenced by BufFileCreateTemp(), and extendBufFile().

1397 {
1398  File file = 0;
1399 
1400  /*
1401  * If some temp tablespace(s) have been given to us, try to use the next
1402  * one. If a given tablespace can't be found, we silently fall back to
1403  * the database's default tablespace.
1404  *
1405  * BUT: if the temp file is slated to outlive the current transaction,
1406  * force it into the database's default tablespace, so that it will not
1407  * pose a threat to possible tablespace drop attempts.
1408  */
1409  if (numTempTableSpaces > 0 && !interXact)
1410  {
1411  Oid tblspcOid = GetNextTempTableSpace();
1412 
1413  if (OidIsValid(tblspcOid))
1414  file = OpenTemporaryFileInTablespace(tblspcOid, false);
1415  }
1416 
1417  /*
1418  * If not, or if tablespace is bad, create in database's default
1419  * tablespace. MyDatabaseTableSpace should normally be set before we get
1420  * here, but just in case it isn't, fall back to pg_default tablespace.
1421  */
1422  if (file <= 0)
1426  true);
1427 
1428  /* Mark it for deletion at close */
1429  VfdCache[file].fdstate |= FD_TEMPORARY;
1430 
1431  /* Register it with the current resource owner */
1432  if (!interXact)
1433  {
1435 
1439 
1440  /* ensure cleanup happens at eoxact */
1442  }
1443 
1444  return file;
1445 }
static File OpenTemporaryFileInTablespace(Oid tblspcOid, bool rejectError)
Definition: fd.c:1452
ResourceOwner CurrentResourceOwner
Definition: resowner.c:138
static Vfd * VfdCache
Definition: fd.c:202
static int numTempTableSpaces
Definition: fd.c:263
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:532
Oid MyDatabaseTableSpace
Definition: globals.c:79
static bool have_xact_temporary_files
Definition: fd.c:214
Oid GetNextTempTableSpace(void)
Definition: fd.c:2597
void ResourceOwnerRememberFile(ResourceOwner owner, File file)
Definition: resowner.c:1186
#define DEFAULTTABLESPACE_OID
Definition: pg_tablespace.h:63
unsigned short fdstate
Definition: fd.c:184
ResourceOwner resowner
Definition: fd.c:185
#define FD_TEMPORARY
Definition: fd.c:178
#define FD_XACT_TEMPORARY
Definition: fd.c:179
void ResourceOwnerEnlargeFiles(ResourceOwner owner)
Definition: resowner.c:1175
int File
Definition: fd.h:49
int OpenTransientFilePerm ( const char *  fileName,
int  fileFlags,
mode_t  fileMode 
)

Definition at line 2176 of file fd.c.

References AllocateDescRawFD, BasicOpenFilePerm(), AllocateDesc::create_subid, AllocateDesc::desc, DO_DB, elog, ereport, errcode(), errmsg(), ERROR, fd(), AllocateDesc::fd, GetCurrentSubTransactionId(), AllocateDesc::kind, LOG, maxAllocatedDescs, numAllocatedDescs, ReleaseLruFiles(), and reserveAllocatedDesc().

Referenced by be_lo_export(), and OpenTransientFile().

2177 {
2178  int fd;
2179 
2180  DO_DB(elog(LOG, "OpenTransientFile: Allocated %d (%s)",
2181  numAllocatedDescs, fileName));
2182 
2183  /* Can we allocate another non-virtual FD? */
2184  if (!reserveAllocatedDesc())
2185  ereport(ERROR,
2186  (errcode(ERRCODE_INSUFFICIENT_RESOURCES),
2187  errmsg("exceeded maxAllocatedDescs (%d) while trying to open file \"%s\"",
2188  maxAllocatedDescs, fileName)));
2189 
2190  /* Close excess kernel FDs. */
2191  ReleaseLruFiles();
2192 
2193  fd = BasicOpenFilePerm(fileName, fileFlags, fileMode);
2194 
2195  if (fd >= 0)
2196  {
2198 
2199  desc->kind = AllocateDescRawFD;
2200  desc->desc.fd = fd;
2203 
2204  return fd;
2205  }
2206 
2207  return -1; /* failure */
2208 }
static AllocateDesc * allocatedDescs
Definition: fd.c:250
#define DO_DB(A)
Definition: fd.c:157
int errcode(int sqlerrcode)
Definition: elog.c:575
static bool reserveAllocatedDesc(void)
Definition: fd.c:2044
#define LOG
Definition: elog.h:26
AllocateDescKind kind
Definition: fd.c:238
static int fd(const char *x, int i)
Definition: preproc-init.c:105
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:122
static void ReleaseLruFiles(void)
Definition: fd.c:1177
SubTransactionId GetCurrentSubTransactionId(void)
Definition: xact.c:642
SubTransactionId create_subid
Definition: fd.c:239
int fd
Definition: fd.c:244
int errmsg(const char *fmt,...)
Definition: elog.c:797
int BasicOpenFilePerm(const char *fileName, int fileFlags, mode_t fileMode)
Definition: fd.c:951
union AllocateDesc::@27 desc
#define elog
Definition: elog.h:219
static int maxAllocatedDescs
Definition: fd.c:249
static int numAllocatedDescs
Definition: fd.c:248
File PathNameOpenFile ( const char *  fileName,
int  fileFlags 
)

Definition at line 1315 of file fd.c.

References PathNameOpenFilePerm(), and PG_FILE_MODE_DEFAULT.

Referenced by _mdfd_openseg(), logical_rewrite_log_mapping(), mdcreate(), mdopen(), and OpenTemporaryFileInTablespace().

1316 {
1317  return PathNameOpenFilePerm(fileName, fileFlags, PG_FILE_MODE_DEFAULT);
1318 }
File PathNameOpenFilePerm(const char *fileName, int fileFlags, mode_t fileMode)
Definition: fd.c:1328
#define PG_FILE_MODE_DEFAULT
Definition: fd.c:123
File PathNameOpenFilePerm ( const char *  fileName,
int  fileFlags,
mode_t  fileMode 
)

Definition at line 1328 of file fd.c.

References AllocateVfd(), BasicOpenFilePerm(), DO_DB, elog, ereport, errcode(), errmsg(), ERROR, vfd::fd, vfd::fdstate, vfd::fileFlags, vfd::fileMode, vfd::fileName, vfd::fileSize, free, FreeVfd(), Insert(), LOG, nfile, ReleaseLruFiles(), vfd::resowner, and vfd::seekPos.

Referenced by PathNameOpenFile().

1329 {
1330  char *fnamecopy;
1331  File file;
1332  Vfd *vfdP;
1333 
1334  DO_DB(elog(LOG, "PathNameOpenFilePerm: %s %x %o",
1335  fileName, fileFlags, fileMode));
1336 
1337  /*
1338  * We need a malloc'd copy of the file name; fail cleanly if no room.
1339  */
1340  fnamecopy = strdup(fileName);
1341  if (fnamecopy == NULL)
1342  ereport(ERROR,
1343  (errcode(ERRCODE_OUT_OF_MEMORY),
1344  errmsg("out of memory")));
1345 
1346  file = AllocateVfd();
1347  vfdP = &VfdCache[file];
1348 
1349  /* Close excess kernel FDs. */
1350  ReleaseLruFiles();
1351 
1352  vfdP->fd = BasicOpenFilePerm(fileName, fileFlags, fileMode);
1353 
1354  if (vfdP->fd < 0)
1355  {
1356  int save_errno = errno;
1357 
1358  FreeVfd(file);
1359  free(fnamecopy);
1360  errno = save_errno;
1361  return -1;
1362  }
1363  ++nfile;
1364  DO_DB(elog(LOG, "PathNameOpenFile: success %d",
1365  vfdP->fd));
1366 
1367  Insert(file);
1368 
1369  vfdP->fileName = fnamecopy;
1370  /* Saved flags are adjusted to be OK for re-opening file */
1371  vfdP->fileFlags = fileFlags & ~(O_CREAT | O_TRUNC | O_EXCL);
1372  vfdP->fileMode = fileMode;
1373  vfdP->seekPos = 0;
1374  vfdP->fileSize = 0;
1375  vfdP->fdstate = 0x0;
1376  vfdP->resowner = NULL;
1377 
1378  return file;
1379 }
#define DO_DB(A)
Definition: fd.c:157
static Vfd * VfdCache
Definition: fd.c:202
int errcode(int sqlerrcode)
Definition: elog.c:575
#define LOG
Definition: elog.h:26
mode_t fileMode
Definition: fd.c:194
#define ERROR
Definition: elog.h:43
char * fileName
Definition: fd.c:191
static int nfile
Definition: fd.c:208
static File AllocateVfd(void)
Definition: fd.c:1187
off_t seekPos
Definition: fd.c:189
unsigned short fdstate
Definition: fd.c:184
Definition: fd.c:181
off_t fileSize
Definition: fd.c:190
int fd
Definition: fd.c:183
#define ereport(elevel, rest)
Definition: elog.h:122
static void Insert(File file)
Definition: fd.c:1059
ResourceOwner resowner
Definition: fd.c:185
static void ReleaseLruFiles(void)
Definition: fd.c:1177
#define free(a)
Definition: header.h:65
int errmsg(const char *fmt,...)
Definition: elog.c:797
int BasicOpenFilePerm(const char *fileName, int fileFlags, mode_t fileMode)
Definition: fd.c:951
static void FreeVfd(File file)
Definition: fd.c:1245
#define elog
Definition: elog.h:219
int fileFlags
Definition: fd.c:193
int File
Definition: fd.h:49
int pg_fdatasync ( int  fd)

Definition at line 390 of file fd.c.

References enableFsync, and fsync.

Referenced by issue_xlog_fsync().

391 {
392  if (enableFsync)
393  {
394 #ifdef HAVE_FDATASYNC
395  return fdatasync(fd);
396 #else
397  return fsync(fd);
398 #endif
399  }
400  else
401  return 0;
402 }
static int fd(const char *x, int i)
Definition: preproc-init.c:105
#define fsync(fd)
Definition: win32.h:62
bool enableFsync
Definition: globals.c:111
void pg_flush_data ( int  fd,
off_t  offset,
off_t  amount 
)

Definition at line 412 of file fd.c.

References enableFsync, ereport, errcode_for_file_access(), errmsg(), FATAL, MAP_FAILED, and WARNING.

Referenced by copy_file(), and FileWriteback().

413 {
414  /*
415  * Right now file flushing is primarily used to avoid making later
416  * fsync()/fdatasync() calls have less impact. Thus don't trigger flushes
417  * if fsyncs are disabled - that's a decision we might want to make
418  * configurable at some point.
419  */
420  if (!enableFsync)
421  return;
422 
423  /*
424  * We compile all alternatives that are supported on the current platform,
425  * to find portability problems more easily.
426  */
427 #if defined(HAVE_SYNC_FILE_RANGE)
428  {
429  int rc;
430 
431  /*
432  * sync_file_range(SYNC_FILE_RANGE_WRITE), currently linux specific,
433  * tells the OS that writeback for the specified blocks should be
434  * started, but that we don't want to wait for completion. Note that
435  * this call might block if too much dirty data exists in the range.
436  * This is the preferable method on OSs supporting it, as it works
437  * reliably when available (contrast to msync()) and doesn't flush out
438  * clean data (like FADV_DONTNEED).
439  */
440  rc = sync_file_range(fd, offset, nbytes,
441  SYNC_FILE_RANGE_WRITE);
442 
443  /* don't error out, this is just a performance optimization */
444  if (rc != 0)
445  {
448  errmsg("could not flush dirty data: %m")));
449  }
450 
451  return;
452  }
453 #endif
454 #if !defined(WIN32) && defined(MS_ASYNC)
455  {
456  void *p;
457  static int pagesize = 0;
458 
459  /*
460  * On several OSs msync(MS_ASYNC) on a mmap'ed file triggers
461  * writeback. On linux it only does so if MS_SYNC is specified, but
462  * then it does the writeback synchronously. Luckily all common linux
463  * systems have sync_file_range(). This is preferable over
464  * FADV_DONTNEED because it doesn't flush out clean data.
465  *
466  * We map the file (mmap()), tell the kernel to sync back the contents
467  * (msync()), and then remove the mapping again (munmap()).
468  */
469 
470  /* mmap() needs actual length if we want to map whole file */
471  if (offset == 0 && nbytes == 0)
472  {
473  nbytes = lseek(fd, 0, SEEK_END);
474  if (nbytes < 0)
475  {
478  errmsg("could not determine dirty data size: %m")));
479  return;
480  }
481  }
482 
483  /*
484  * Some platforms reject partial-page mmap() attempts. To deal with
485  * that, just truncate the request to a page boundary. If any extra
486  * bytes don't get flushed, well, it's only a hint anyway.
487  */
488 
489  /* fetch pagesize only once */
490  if (pagesize == 0)
491  pagesize = sysconf(_SC_PAGESIZE);
492 
493  /* align length to pagesize, dropping any fractional page */
494  if (pagesize > 0)
495  nbytes = (nbytes / pagesize) * pagesize;
496 
497  /* fractional-page request is a no-op */
498  if (nbytes <= 0)
499  return;
500 
501  /*
502  * mmap could well fail, particularly on 32-bit platforms where there
503  * may simply not be enough address space. If so, silently fall
504  * through to the next implementation.
505  */
506  if (nbytes <= (off_t) SSIZE_MAX)
507  p = mmap(NULL, nbytes, PROT_READ, MAP_SHARED, fd, offset);
508  else
509  p = MAP_FAILED;
510 
511  if (p != MAP_FAILED)
512  {
513  int rc;
514 
515  rc = msync(p, (size_t) nbytes, MS_ASYNC);
516  if (rc != 0)
517  {
520  errmsg("could not flush dirty data: %m")));
521  /* NB: need to fall through to munmap()! */
522  }
523 
524  rc = munmap(p, (size_t) nbytes);
525  if (rc != 0)
526  {
527  /* FATAL error because mapping would remain */
528  ereport(FATAL,
530  errmsg("could not munmap() while flushing data: %m")));
531  }
532 
533  return;
534  }
535  }
536 #endif
537 #if defined(USE_POSIX_FADVISE) && defined(POSIX_FADV_DONTNEED)
538  {
539  int rc;
540 
541  /*
542  * Signal the kernel that the passed in range should not be cached
543  * anymore. This has the, desired, side effect of writing out dirty
544  * data, and the, undesired, side effect of likely discarding useful
545  * clean cached blocks. For the latter reason this is the least
546  * preferable method.
547  */
548 
549  rc = posix_fadvise(fd, offset, nbytes, POSIX_FADV_DONTNEED);
550 
551  if (rc != 0)
552  {
553  /* don't error out, this is just a performance optimization */
556  errmsg("could not flush dirty data: %m")));
557  }
558 
559  return;
560  }
561 #endif
562 }
#define MAP_FAILED
Definition: mem.h:45
static int fd(const char *x, int i)
Definition: preproc-init.c:105
#define FATAL
Definition: elog.h:52
int errcode_for_file_access(void)
Definition: elog.c:598
#define ereport(elevel, rest)
Definition: elog.h:122
#define WARNING
Definition: elog.h:40
bool enableFsync
Definition: globals.c:111
int errmsg(const char *fmt,...)
Definition: elog.c:797
int pg_fsync ( int  fd)

Definition at line 338 of file fd.c.

References pg_fsync_no_writethrough(), pg_fsync_writethrough(), sync_method, and SYNC_METHOD_FSYNC_WRITETHROUGH.

Referenced by AddToDataDirLockFile(), assign_xlog_sync_method(), BootStrapXLOG(), CheckPointLogicalRewriteHeap(), CreateLockFile(), do_pg_start_backup(), durable_rename(), FileSync(), fsync_fname_ext(), heap_xlog_logical_rewrite(), RecreateTwoPhaseFile(), RestoreSlotFromDisk(), SaveSlotToPath(), SimpleLruFlush(), SlruPhysicalWritePage(), SnapBuildSerialize(), UpdateControlFile(), write_auto_conf_file(), write_relmap_file(), WriteControlFile(), writeTimeLineHistory(), writeTimeLineHistoryFile(), XLogFileCopy(), and XLogFileInit().

339 {
340  /* #if is to skip the sync_method test if there's no need for it */
341 #if defined(HAVE_FSYNC_WRITETHROUGH) && !defined(FSYNC_WRITETHROUGH_IS_FSYNC)
343  return pg_fsync_writethrough(fd);
344  else
345 #endif
347 }
#define SYNC_METHOD_FSYNC_WRITETHROUGH
Definition: xlog.h:28
int pg_fsync_writethrough(int fd)
Definition: fd.c:367
int pg_fsync_no_writethrough(int fd)
Definition: fd.c:355
static int fd(const char *x, int i)
Definition: preproc-init.c:105
int sync_method
Definition: xlog.c:103
int pg_fsync_no_writethrough ( int  fd)

Definition at line 355 of file fd.c.

References enableFsync, and fsync.

Referenced by issue_xlog_fsync(), and pg_fsync().

356 {
357  if (enableFsync)
358  return fsync(fd);
359  else
360  return 0;
361 }
static int fd(const char *x, int i)
Definition: preproc-init.c:105
#define fsync(fd)
Definition: win32.h:62
bool enableFsync
Definition: globals.c:111
int pg_fsync_writethrough ( int  fd)

Definition at line 367 of file fd.c.

References enableFsync.

Referenced by issue_xlog_fsync(), pg_fsync(), and test_sync().

368 {
369  if (enableFsync)
370  {
371 #ifdef WIN32
372  return _commit(fd);
373 #elif defined(F_FULLFSYNC)
374  return (fcntl(fd, F_FULLFSYNC, 0) == -1) ? -1 : 0;
375 #else
376  errno = ENOSYS;
377  return -1;
378 #endif
379  }
380  else
381  return 0;
382 }
static int fd(const char *x, int i)
Definition: preproc-init.c:105
bool enableFsync
Definition: globals.c:111
void RemovePgTempFiles ( void  )

Definition at line 2738 of file fd.c.

References AllocateDir(), dirent::d_name, FreeDir(), MAXPGPATH, PG_TEMP_FILES_DIR, ReadDir(), RemovePgTempFilesInDir(), RemovePgTempRelationFiles(), snprintf(), and TABLESPACE_VERSION_DIRECTORY.

Referenced by PostmasterMain().

2739 {
2740  char temp_path[MAXPGPATH + 10 + sizeof(TABLESPACE_VERSION_DIRECTORY) + sizeof(PG_TEMP_FILES_DIR)];
2741  DIR *spc_dir;
2742  struct dirent *spc_de;
2743 
2744  /*
2745  * First process temp files in pg_default ($PGDATA/base)
2746  */
2747  snprintf(temp_path, sizeof(temp_path), "base/%s", PG_TEMP_FILES_DIR);
2748  RemovePgTempFilesInDir(temp_path);
2749  RemovePgTempRelationFiles("base");
2750 
2751  /*
2752  * Cycle through temp directories for all non-default tablespaces.
2753  */
2754  spc_dir = AllocateDir("pg_tblspc");
2755 
2756  while ((spc_de = ReadDir(spc_dir, "pg_tblspc")) != NULL)
2757  {
2758  if (strcmp(spc_de->d_name, ".") == 0 ||
2759  strcmp(spc_de->d_name, "..") == 0)
2760  continue;
2761 
2762  snprintf(temp_path, sizeof(temp_path), "pg_tblspc/%s/%s/%s",
2764  RemovePgTempFilesInDir(temp_path);
2765 
2766  snprintf(temp_path, sizeof(temp_path), "pg_tblspc/%s/%s",
2768  RemovePgTempRelationFiles(temp_path);
2769  }
2770 
2771  FreeDir(spc_dir);
2772 
2773  /*
2774  * In EXEC_BACKEND case there is a pgsql_tmp directory at the top level of
2775  * DataDir as well.
2776  */
2777 #ifdef EXEC_BACKEND
2779 #endif
2780 }
int snprintf(char *str, size_t count, const char *fmt,...) pg_attribute_printf(3
static void RemovePgTempFilesInDir(const char *tmpdirname)
Definition: fd.c:2784
Definition: dirent.h:9
static void RemovePgTempRelationFiles(const char *tsdirname)
Definition: fd.c:2825
Definition: dirent.c:25
#define MAXPGPATH
DIR * AllocateDir(const char *dirname)
Definition: fd.c:2367
#define PG_TEMP_FILES_DIR
Definition: fd.h:128
struct dirent * ReadDir(DIR *dir, const char *dirname)
Definition: fd.c:2433
#define TABLESPACE_VERSION_DIRECTORY
Definition: catalog.h:26
char d_name[MAX_PATH]
Definition: dirent.h:14
int FreeDir(DIR *dir)
Definition: fd.c:2476
void set_max_safe_fds ( void  )

Definition at line 886 of file fd.c.

References count_usable_fds(), DEBUG2, elog, ereport, errcode(), errdetail(), errmsg(), FATAL, FD_MINFREE, max_files_per_process, max_safe_fds, Min, and NUM_RESERVED_FDS.

Referenced by PostmasterMain().

887 {
888  int usable_fds;
889  int already_open;
890 
891  /*----------
892  * We want to set max_safe_fds to
893  * MIN(usable_fds, max_files_per_process - already_open)
894  * less the slop factor for files that are opened without consulting
895  * fd.c. This ensures that we won't exceed either max_files_per_process
896  * or the experimentally-determined EMFILE limit.
897  *----------
898  */
900  &usable_fds, &already_open);
901 
902  max_safe_fds = Min(usable_fds, max_files_per_process - already_open);
903 
904  /*
905  * Take off the FDs reserved for system() etc.
906  */
908 
909  /*
910  * Make sure we still have enough to get by.
911  */
912  if (max_safe_fds < FD_MINFREE)
913  ereport(FATAL,
914  (errcode(ERRCODE_INSUFFICIENT_RESOURCES),
915  errmsg("insufficient file descriptors available to start server process"),
916  errdetail("System allows %d, we need at least %d.",
919 
920  elog(DEBUG2, "max_safe_fds = %d, usable_fds = %d, already_open = %d",
921  max_safe_fds, usable_fds, already_open);
922 }
static void count_usable_fds(int max_to_probe, int *usable_fds, int *already_open)
Definition: fd.c:802
#define NUM_RESERVED_FDS
Definition: fd.c:111
int max_safe_fds
Definition: fd.c:144
#define Min(x, y)
Definition: c.h:812
int errcode(int sqlerrcode)
Definition: elog.c:575
#define FATAL
Definition: elog.h:52
#define DEBUG2
Definition: elog.h:24
int errdetail(const char *fmt,...)
Definition: elog.c:873
int max_files_per_process
Definition: fd.c:131
#define ereport(elevel, rest)
Definition: elog.h:122
#define FD_MINFREE
Definition: fd.c:117
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define elog
Definition: elog.h:219
void SetTempTablespaces ( Oid tableSpaces,
int  numSpaces 
)

Definition at line 2557 of file fd.c.

References Assert, nextTempTableSpace, numTempTableSpaces, random(), and tempTableSpaces.

Referenced by assign_temp_tablespaces(), and PrepareTempTablespaces().

2558 {
2559  Assert(numSpaces >= 0);
2560  tempTableSpaces = tableSpaces;
2561  numTempTableSpaces = numSpaces;
2562 
2563  /*
2564  * Select a random starting point in the list. This is to minimize
2565  * conflicts between backends that are most likely sharing the same list
2566  * of temp tablespaces. Note that if we create multiple temp files in the
2567  * same transaction, we'll advance circularly through the list --- this
2568  * ensures that large temporary sort files are nicely spread across all
2569  * available tablespaces.
2570  */
2571  if (numSpaces > 1)
2572  nextTempTableSpace = random() % numSpaces;
2573  else
2574  nextTempTableSpace = 0;
2575 }
long random(void)
Definition: random.c:22
static int numTempTableSpaces
Definition: fd.c:263
static int nextTempTableSpace
Definition: fd.c:264
#define Assert(condition)
Definition: c.h:681
static Oid * tempTableSpaces
Definition: fd.c:262
void SyncDataDirectory ( void  )

Definition at line 2965 of file fd.c.

References datadir_fsync_fname(), DEBUG1, enableFsync, ereport, errcode_for_file_access(), errmsg(), LOG, lstat, and walkdir().

Referenced by StartupXLOG().

2966 {
2967  bool xlog_is_symlink;
2968 
2969  /* We can skip this whole thing if fsync is disabled. */
2970  if (!enableFsync)
2971  return;
2972 
2973  /*
2974  * If pg_wal is a symlink, we'll need to recurse into it separately,
2975  * because the first walkdir below will ignore it.
2976  */
2977  xlog_is_symlink = false;
2978 
2979 #ifndef WIN32
2980  {
2981  struct stat st;
2982 
2983  if (lstat("pg_wal", &st) < 0)
2984  ereport(LOG,
2986  errmsg("could not stat file \"%s\": %m",
2987  "pg_wal")));
2988  else if (S_ISLNK(st.st_mode))
2989  xlog_is_symlink = true;
2990  }
2991 #else
2992  if (pgwin32_is_junction("pg_wal"))
2993  xlog_is_symlink = true;
2994 #endif
2995 
2996  /*
2997  * If possible, hint to the kernel that we're soon going to fsync the data
2998  * directory and its contents. Errors in this step are even less
2999  * interesting than normal, so log them only at DEBUG1.
3000  */
3001 #ifdef PG_FLUSH_DATA_WORKS
3002  walkdir(".", pre_sync_fname, false, DEBUG1);
3003  if (xlog_is_symlink)
3004  walkdir("pg_wal", pre_sync_fname, false, DEBUG1);
3005  walkdir("pg_tblspc", pre_sync_fname, true, DEBUG1);
3006 #endif
3007 
3008  /*
3009  * Now we do the fsync()s in the same order.
3010  *
3011  * The main call ignores symlinks, so in addition to specially processing
3012  * pg_wal if it's a symlink, pg_tblspc has to be visited separately with
3013  * process_symlinks = true. Note that if there are any plain directories
3014  * in pg_tblspc, they'll get fsync'd twice. That's not an expected case
3015  * so we don't worry about optimizing it.
3016  */
3017  walkdir(".", datadir_fsync_fname, false, LOG);
3018  if (xlog_is_symlink)
3019  walkdir("pg_wal", datadir_fsync_fname, false, LOG);
3020  walkdir("pg_tblspc", datadir_fsync_fname, true, LOG);
3021 }
#define DEBUG1
Definition: elog.h:25
static void walkdir(const char *path, void(*action)(const char *fname, bool isdir, int elevel), bool process_symlinks, int elevel)
Definition: fd.c:3038
#define LOG
Definition: elog.h:26
int errcode_for_file_access(void)
Definition: elog.c:598
#define ereport(elevel, rest)
Definition: elog.h:122
static void datadir_fsync_fname(const char *fname, bool isdir, int elevel)
Definition: fd.c:3140
bool enableFsync
Definition: globals.c:111
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define lstat(path, sb)
Definition: win32.h:262
bool TempTablespacesAreSet ( void  )

Definition at line 2585 of file fd.c.

References numTempTableSpaces.

Referenced by PrepareTempTablespaces().

2586 {
2587  return (numTempTableSpaces >= 0);
2588 }
static int numTempTableSpaces
Definition: fd.c:263

Variable Documentation

int max_files_per_process

Definition at line 131 of file fd.c.

Referenced by set_max_safe_fds().

int max_safe_fds

Definition at line 144 of file fd.c.

Referenced by ReleaseLruFiles(), reserveAllocatedDesc(), and set_max_safe_fds().