PostgreSQL Source Code git master
Loading...
Searching...
No Matches
fd.h File Reference
#include "port/pg_iovec.h"
#include <dirent.h>
#include <fcntl.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 IO_DIRECT_DATA   0x01
 
#define IO_DIRECT_WAL   0x02
 
#define IO_DIRECT_WAL_INIT   0x04
 
#define DEFAULT_FILE_EXTEND_METHOD   0
 
#define FILE_POSSIBLY_DELETED(err)   ((err) == ENOENT)
 
#define PG_O_DIRECT   0
 

Typedefs

typedef int File
 

Enumerations

enum  FileExtendMethod { FILE_EXTEND_METHOD_WRITE_ZEROS }
 

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, pgoff_t offset, pgoff_t amount, uint32 wait_event_info)
 
ssize_t FileReadV (File file, const struct iovec *iov, int iovcnt, pgoff_t offset, uint32 wait_event_info)
 
ssize_t FileWriteV (File file, const struct iovec *iov, int iovcnt, pgoff_t offset, uint32 wait_event_info)
 
int FileStartReadV (struct PgAioHandle *ioh, File file, int iovcnt, pgoff_t offset, uint32 wait_event_info)
 
int FileSync (File file, uint32 wait_event_info)
 
int FileZero (File file, pgoff_t offset, pgoff_t amount, uint32 wait_event_info)
 
int FileFallocate (File file, pgoff_t offset, pgoff_t amount, uint32 wait_event_info)
 
pgoff_t FileSize (File file)
 
int FileTruncate (File file, pgoff_t offset, uint32 wait_event_info)
 
void FileWriteback (File file, pgoff_t offset, pgoff_t nbytes, uint32 wait_event_info)
 
charFilePathName (File file)
 
int FileGetRawDesc (File file)
 
int FileGetRawFlags (File file)
 
mode_t FileGetRawMode (File file)
 
File PathNameCreateTemporaryFile (const char *path, bool error_on_failure)
 
File PathNameOpenTemporaryFile (const char *path, int mode)
 
bool PathNameDeleteTemporaryFile (const char *path, bool error_on_failure)
 
void PathNameCreateTemporaryDir (const char *basedir, const char *directory)
 
void PathNameDeleteTemporaryDir (const char *dirname)
 
void TempTablespacePath (char *path, Oid tablespace)
 
FILEAllocateFile (const char *name, const char *mode)
 
int FreeFile (FILE *file)
 
FILEOpenPipeStream (const char *command, const char *mode)
 
int ClosePipeStream (FILE *file)
 
DIRAllocateDir (const char *dirname)
 
struct direntReadDir (DIR *dir, const char *dirname)
 
struct direntReadDirExtended (DIR *dir, const char *dirname, int elevel)
 
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)
 
bool AcquireExternalFD (void)
 
void ReserveExternalFD (void)
 
void ReleaseExternalFD (void)
 
int MakePGDirectory (const char *directoryName)
 
void InitFileAccess (void)
 
void InitTemporaryFileAccess (void)
 
void set_max_safe_fds (void)
 
void closeAllVfds (void)
 
void SetTempTablespaces (Oid *tableSpaces, int numSpaces)
 
bool TempTablespacesAreSet (void)
 
int GetTempTablespaces (Oid *tableSpaces, int numSpaces)
 
Oid GetNextTempTableSpace (void)
 
void AtEOXact_Files (bool isCommit)
 
void AtEOSubXact_Files (bool isCommit, SubTransactionId mySubid, SubTransactionId parentSubid)
 
void RemovePgTempFiles (void)
 
void RemovePgTempFilesInDir (const char *tmpdirname, bool missing_ok, bool unlink_all)
 
bool looks_like_temp_rel_name (const char *name)
 
int pg_fsync (int fd)
 
int pg_fsync_no_writethrough (int fd)
 
int pg_fsync_writethrough (int fd)
 
int pg_fdatasync (int fd)
 
bool pg_file_exists (const char *name)
 
void pg_flush_data (int fd, pgoff_t offset, pgoff_t nbytes)
 
int pg_truncate (const char *path, pgoff_t length)
 
void fsync_fname (const char *fname, bool isdir)
 
int fsync_fname_ext (const char *fname, bool isdir, bool ignore_perm, int elevel)
 
int durable_rename (const char *oldfile, const char *newfile, int elevel)
 
int durable_unlink (const char *fname, int elevel)
 
void SyncDataDirectory (void)
 
int data_sync_elevel (int elevel)
 
static ssize_t FileRead (File file, void *buffer, size_t amount, pgoff_t offset, uint32 wait_event_info)
 
static ssize_t FileWrite (File file, const void *buffer, size_t amount, pgoff_t offset, uint32 wait_event_info)
 

Variables

PGDLLIMPORT int max_files_per_process
 
PGDLLIMPORT bool data_sync_retry
 
PGDLLIMPORT int recovery_init_sync_method
 
PGDLLIMPORT int io_direct_flags
 
PGDLLIMPORT int file_extend_method
 
PGDLLIMPORT int max_safe_fds
 

Macro Definition Documentation

◆ DEFAULT_FILE_EXTEND_METHOD

#define DEFAULT_FILE_EXTEND_METHOD   0

Definition at line 67 of file fd.h.

◆ FILE_POSSIBLY_DELETED

#define FILE_POSSIBLY_DELETED (   err)    ((err) == ENOENT)

Definition at line 89 of file fd.h.

◆ IO_DIRECT_DATA

#define IO_DIRECT_DATA   0x01

Definition at line 54 of file fd.h.

◆ IO_DIRECT_WAL

#define IO_DIRECT_WAL   0x02

Definition at line 55 of file fd.h.

◆ IO_DIRECT_WAL_INIT

#define IO_DIRECT_WAL_INIT   0x04

Definition at line 56 of file fd.h.

◆ PG_O_DIRECT

#define PG_O_DIRECT   0

Definition at line 123 of file fd.h.

Typedef Documentation

◆ File

Definition at line 51 of file fd.h.

Enumeration Type Documentation

◆ FileExtendMethod

Enumerator
FILE_EXTEND_METHOD_WRITE_ZEROS 

Definition at line 58 of file fd.h.

59{
60#ifdef HAVE_POSIX_FALLOCATE
62#endif
64};
@ FILE_EXTEND_METHOD_WRITE_ZEROS
Definition fd.h:63
static int fb(int x)

Function Documentation

◆ AcquireExternalFD()

bool AcquireExternalFD ( void  )
extern

Definition at line 1171 of file fd.c.

1172{
1173 /*
1174 * We don't want more than max_safe_fds / 3 FDs to be consumed for
1175 * "external" FDs.
1176 */
1177 if (numExternalFDs < max_safe_fds / 3)
1178 {
1180 return true;
1181 }
1182 errno = EMFILE;
1183 return false;
1184}
int max_safe_fds
Definition fd.c:159
void ReserveExternalFD(void)
Definition fd.c:1206
static int numExternalFDs
Definition fd.c:277

References fb(), max_safe_fds, numExternalFDs, and ReserveExternalFD().

Referenced by CreateWaitEventSet(), and libpqsrv_connect_prepare().

◆ AllocateDir()

DIR * AllocateDir ( const char dirname)
extern

Definition at line 2890 of file fd.c.

2891{
2892 DIR *dir;
2893
2894 DO_DB(elog(LOG, "AllocateDir: Allocated %d (%s)",
2895 numAllocatedDescs, dirname));
2896
2897 /* Can we allocate another non-virtual FD? */
2898 if (!reserveAllocatedDesc())
2899 ereport(ERROR,
2901 errmsg("exceeded maxAllocatedDescs (%d) while trying to open directory \"%s\"",
2902 maxAllocatedDescs, dirname)));
2903
2904 /* Close excess kernel FDs. */
2906
2907TryAgain:
2908 if ((dir = opendir(dirname)) != NULL)
2909 {
2911
2912 desc->kind = AllocateDescDir;
2913 desc->desc.dir = dir;
2916 return desc->desc.dir;
2917 }
2918
2919 if (errno == EMFILE || errno == ENFILE)
2920 {
2921 int save_errno = errno;
2922
2923 ereport(LOG,
2925 errmsg("out of file descriptors: %m; release and retry")));
2926 errno = 0;
2927 if (ReleaseLruFile())
2928 goto TryAgain;
2929 errno = save_errno;
2930 }
2931
2932 return NULL;
2933}
DIR * opendir(const char *)
Definition dirent.c:33
int errcode(int sqlerrcode)
Definition elog.c:863
int errmsg(const char *fmt,...)
Definition elog.c:1080
#define LOG
Definition elog.h:31
#define ERROR
Definition elog.h:39
#define elog(elevel,...)
Definition elog.h:226
#define ereport(elevel,...)
Definition elog.h:150
static bool ReleaseLruFile(void)
Definition fd.c:1369
static int maxAllocatedDescs
Definition fd.c:271
static int numAllocatedDescs
Definition fd.c:270
#define DO_DB(A)
Definition fd.c:183
static AllocateDesc * allocatedDescs
Definition fd.c:272
@ AllocateDescDir
Definition fd.c:254
static bool reserveAllocatedDesc(void)
Definition fd.c:2552
static void ReleaseLruFiles(void)
Definition fd.c:1391
SubTransactionId create_subid
Definition fd.c:261
DIR * dir
Definition fd.c:265
union AllocateDesc::@20 desc
AllocateDescKind kind
Definition fd.c:260
Definition dirent.c:26
SubTransactionId GetCurrentSubTransactionId(void)
Definition xact.c:792

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

Referenced by calculate_database_size(), calculate_tablespace_size(), CheckPointLogicalRewriteHeap(), CheckPointSnapBuild(), CheckTablespaceDirectory(), CleanupBackupHistory(), copydir(), db_dir_size(), DeleteAllExportedSnapshotFiles(), destroy_tablespace_directories(), directory_is_empty(), do_pg_backup_start(), dsm_cleanup_for_mmap(), extension_file_exists(), get_ext_ver_list(), GetConfFilesInDir(), getInstallationPaths(), GetWalSummaries(), movedb(), ParseTzFile(), perform_base_backup(), pg_available_extension_versions(), pg_available_extensions(), pg_ls_dir(), pg_ls_dir_files(), pg_tablespace_databases(), pg_tzenumerate_next(), pg_tzenumerate_start(), pgarch_readyXlog(), RelationCacheInitFileRemove(), RelationCacheInitFileRemoveInDir(), RemoveNonParentXlogFiles(), RemoveOldXlogFiles(), RemovePgTempFiles(), RemovePgTempFilesInDir(), RemovePgTempRelationFiles(), RemovePgTempRelationFilesInDbspace(), RemoveTempXlogFiles(), ReorderBufferCleanupSerializedTXNs(), ResetUnloggedRelations(), ResetUnloggedRelationsInDbspaceDir(), ResetUnloggedRelationsInTablespaceDir(), restoreTwoPhaseData(), scan_directory_ci(), sendDir(), SlruScanDirectory(), StartupReorderBuffer(), StartupReplicationSlots(), SyncDataDirectory(), UpdateLogicalMappings(), walkdir(), and XLogGetOldestSegno().

◆ AllocateFile()

FILE * AllocateFile ( const char name,
const char mode 
)
extern

Definition at line 2627 of file fd.c.

2628{
2629 FILE *file;
2630
2631 DO_DB(elog(LOG, "AllocateFile: Allocated %d (%s)",
2633
2634 /* Can we allocate another non-virtual FD? */
2635 if (!reserveAllocatedDesc())
2636 ereport(ERROR,
2638 errmsg("exceeded maxAllocatedDescs (%d) while trying to open file \"%s\"",
2640
2641 /* Close excess kernel FDs. */
2643
2644TryAgain:
2645 if ((file = fopen(name, mode)) != NULL)
2646 {
2648
2649 desc->kind = AllocateDescFile;
2650 desc->desc.file = file;
2653 return desc->desc.file;
2654 }
2655
2656 if (errno == EMFILE || errno == ENFILE)
2657 {
2658 int save_errno = errno;
2659
2660 ereport(LOG,
2662 errmsg("out of file descriptors: %m; release and retry")));
2663 errno = 0;
2664 if (ReleaseLruFile())
2665 goto TryAgain;
2666 errno = save_errno;
2667 }
2668
2669 return NULL;
2670}
@ AllocateDescFile
Definition fd.c:252
static PgChecksumMode mode
FILE * file
Definition fd.c:264
const char * name

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

Referenced by AlterSystemSetConfigFile(), apw_dump_now(), apw_load_buffers(), BeginCopyFrom(), BeginCopyTo(), checkControlFile(), do_pg_backup_stop(), entry_reset(), existsTimeLineHistory(), ExportSnapshot(), gc_qtexts(), GetHugePageSize(), ImportSnapshot(), load_dh_file(), load_relcache_init_file(), open_auth_file(), parse_extension_control_file(), ParseConfigFile(), ParseTzFile(), pg_current_logfile(), pg_promote(), pgss_shmem_shutdown(), pgss_shmem_startup(), pgstat_read_statsfile(), pgstat_write_statsfile(), read_backup_label(), read_binary_file(), read_tablespace_map(), read_whole_file(), readTimeLineHistory(), test_custom_stats_var_from_serialized_data(), test_custom_stats_var_to_serialized_data(), tsearch_readline_begin(), ValidatePgVersion(), write_relcache_init_file(), XLogArchiveForceDone(), and XLogArchiveNotify().

◆ AtEOSubXact_Files()

void AtEOSubXact_Files ( bool  isCommit,
SubTransactionId  mySubid,
SubTransactionId  parentSubid 
)
extern

Definition at line 3180 of file fd.c.

3182{
3183 Index i;
3184
3185 for (i = 0; i < numAllocatedDescs; i++)
3186 {
3187 if (allocatedDescs[i].create_subid == mySubid)
3188 {
3189 if (isCommit)
3191 else
3192 {
3193 /* have to recheck the item after FreeDesc (ugly) */
3195 }
3196 }
3197 }
3198}
unsigned int Index
Definition c.h:628
static int FreeDesc(AllocateDesc *desc)
Definition fd.c:2786
int i
Definition isn.c:77

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

Referenced by AbortSubTransaction(), and CommitSubTransaction().

◆ AtEOXact_Files()

void AtEOXact_Files ( bool  isCommit)
extern

Definition at line 3213 of file fd.c.

3214{
3215 CleanupTempFiles(isCommit, false);
3217 numTempTableSpaces = -1;
3218}
static int numTempTableSpaces
Definition fd.c:292
static Oid * tempTableSpaces
Definition fd.c:291
static void CleanupTempFiles(bool isCommit, bool isProcExit)
Definition fd.c:3250

References CleanupTempFiles(), fb(), numTempTableSpaces, and tempTableSpaces.

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

◆ BasicOpenFile()

int BasicOpenFile ( const char fileName,
int  fileFlags 
)
extern

Definition at line 1089 of file fd.c.

1090{
1091 return BasicOpenFilePerm(fileName, fileFlags, pg_file_create_mode);
1092}
int BasicOpenFilePerm(const char *fileName, int fileFlags, mode_t fileMode)
Definition fd.c:1111
int pg_file_create_mode
Definition file_perm.c:19

References BasicOpenFilePerm(), and pg_file_create_mode.

Referenced by AlterSystemSetConfigFile(), ReadControlFile(), update_controlfile(), wal_segment_open(), WalSndSegmentOpen(), WriteControlFile(), XLogFileInit(), XLogFileInitInternal(), XLogFileOpen(), and XLogFileRead().

◆ BasicOpenFilePerm()

int BasicOpenFilePerm ( const char fileName,
int  fileFlags,
mode_t  fileMode 
)
extern

Definition at line 1111 of file fd.c.

1112{
1113 int fd;
1114
1115tryAgain:
1116#ifdef PG_O_DIRECT_USE_F_NOCACHE
1117 fd = open(fileName, fileFlags & ~PG_O_DIRECT, fileMode);
1118#else
1119 fd = open(fileName, fileFlags, fileMode);
1120#endif
1121
1122 if (fd >= 0)
1123 {
1124#ifdef PG_O_DIRECT_USE_F_NOCACHE
1125 if (fileFlags & PG_O_DIRECT)
1126 {
1127 if (fcntl(fd, F_NOCACHE, 1) < 0)
1128 {
1129 int save_errno = errno;
1130
1131 close(fd);
1132 errno = save_errno;
1133 return -1;
1134 }
1135 }
1136#endif
1137
1138 return fd; /* success! */
1139 }
1140
1141 if (errno == EMFILE || errno == ENFILE)
1142 {
1143 int save_errno = errno;
1144
1145 ereport(LOG,
1147 errmsg("out of file descriptors: %m; release and retry")));
1148 errno = 0;
1149 if (ReleaseLruFile())
1150 goto tryAgain;
1151 errno = save_errno;
1152 }
1153
1154 return -1; /* failure */
1155}
#define PG_O_DIRECT
Definition fd.h:123
#define close(a)
Definition win32.h:12
static int fd(const char *x, int i)

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

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

◆ closeAllVfds()

void closeAllVfds ( void  )
extern

Definition at line 3067 of file fd.c.

3068{
3069 Index i;
3070
3071 if (SizeVfdCache > 0)
3072 {
3073 Assert(FileIsNotOpen(0)); /* Make sure ring not corrupted */
3074 for (i = 1; i < SizeVfdCache; i++)
3075 {
3076 if (!FileIsNotOpen(i))
3077 LruDelete(i);
3078 }
3079 }
3080}
#define Assert(condition)
Definition c.h:873
static void LruDelete(File file)
Definition fd.c:1272
static Size SizeVfdCache
Definition fd.c:220
#define FileIsNotOpen(file)
Definition fd.c:192

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

Referenced by standard_ProcessUtility().

◆ ClosePipeStream()

int ClosePipeStream ( FILE file)
extern

Definition at line 3038 of file fd.c.

3039{
3040 int i;
3041
3042 DO_DB(elog(LOG, "ClosePipeStream: Allocated %d", numAllocatedDescs));
3043
3044 /* Remove file from list of allocated files, if it's present */
3045 for (i = numAllocatedDescs; --i >= 0;)
3046 {
3047 AllocateDesc *desc = &allocatedDescs[i];
3048
3049 if (desc->kind == AllocateDescPipe && desc->desc.file == file)
3050 return FreeDesc(desc);
3051 }
3052
3053 /* Only get here if someone passes us a file not in allocatedDescs */
3054 elog(WARNING, "file passed to ClosePipeStream was not obtained from OpenPipeStream");
3055
3056 return pclose(file);
3057}
#define WARNING
Definition elog.h:36
@ AllocateDescPipe
Definition fd.c:253

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

Referenced by ClosePipeFromProgram(), ClosePipeToProgram(), pg_import_system_collations(), run_ssl_passphrase_command(), and shell_finish_command().

◆ CloseTransientFile()

int CloseTransientFile ( int  fd)
extern

Definition at line 2854 of file fd.c.

2855{
2856 int i;
2857
2858 DO_DB(elog(LOG, "CloseTransientFile: Allocated %d", numAllocatedDescs));
2859
2860 /* Remove fd from list of allocated files, if it's present */
2861 for (i = numAllocatedDescs; --i >= 0;)
2862 {
2863 AllocateDesc *desc = &allocatedDescs[i];
2864
2865 if (desc->kind == AllocateDescRawFD && desc->desc.fd == fd)
2866 return FreeDesc(desc);
2867 }
2868
2869 /* Only get here if someone passes us a file not in allocatedDescs */
2870 elog(WARNING, "fd passed to CloseTransientFile was not obtained from OpenTransientFile");
2871
2873
2874 return close(fd);
2875}
void pgaio_closing_fd(int fd)
Definition aio.c:1220
@ AllocateDescRawFD
Definition fd.c:255
int fd
Definition fd.c:266

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

Referenced by ApplyLogicalMappingFile(), be_lo_export(), CheckPointLogicalRewriteHeap(), CheckPointReplicationOrigin(), clone_file(), compare_files(), copy_file(), CreateDirAndVersionFile(), dsm_impl_mmap(), durable_rename(), fsync_fname_ext(), get_controlfile_by_exact_path(), heap_xlog_logical_rewrite(), lo_import_internal(), perform_base_backup(), pg_truncate(), qtext_load_file(), qtext_store(), read_relmap_file(), ReadTwoPhaseFile(), RecreateTwoPhaseFile(), ReorderBufferSerializeChange(), ReorderBufferSerializeTXN(), RestoreSlotFromDisk(), SaveSlotToPath(), sendFile(), SendTimeLineHistory(), SimpleLruDoesPhysicalPageExist(), SimpleLruWriteAll(), SlruInternalWritePage(), SlruPhysicalReadPage(), SlruPhysicalWritePage(), SlruSyncFileTag(), SnapBuildRestoreContents(), SnapBuildRestoreSnapshot(), SnapBuildSerialize(), StartupReplicationOrigin(), write_relmap_file(), writeTimeLineHistory(), writeTimeLineHistoryFile(), and XLogFileCopy().

◆ data_sync_elevel()

◆ durable_rename()

int durable_rename ( const char oldfile,
const char newfile,
int  elevel 
)
extern

Definition at line 782 of file fd.c.

783{
784 int fd;
785
786 /*
787 * First fsync the old and target path (if it exists), to ensure that they
788 * are properly persistent on disk. Syncing the target file is not
789 * strictly necessary, but it makes it easier to reason about crashes;
790 * because it's then guaranteed that either source or target file exists
791 * after a crash.
792 */
793 if (fsync_fname_ext(oldfile, false, false, elevel) != 0)
794 return -1;
795
797 if (fd < 0)
798 {
799 if (errno != ENOENT)
800 {
801 ereport(elevel,
803 errmsg("could not open file \"%s\": %m", newfile)));
804 return -1;
805 }
806 }
807 else
808 {
809 if (pg_fsync(fd) != 0)
810 {
811 int save_errno;
812
813 /* close file upon error, might not be in transaction context */
817
818 ereport(elevel,
820 errmsg("could not fsync file \"%s\": %m", newfile)));
821 return -1;
822 }
823
824 if (CloseTransientFile(fd) != 0)
825 {
826 ereport(elevel,
828 errmsg("could not close file \"%s\": %m", newfile)));
829 return -1;
830 }
831 }
832
833 /* Time to do the real deal... */
834 if (rename(oldfile, newfile) < 0)
835 {
836 ereport(elevel,
838 errmsg("could not rename file \"%s\" to \"%s\": %m",
839 oldfile, newfile)));
840 return -1;
841 }
842
843 /*
844 * To guarantee renaming the file is persistent, fsync the file with its
845 * new name, and its containing directory.
846 */
847 if (fsync_fname_ext(newfile, false, false, elevel) != 0)
848 return -1;
849
850 if (fsync_parent_path(newfile, elevel) != 0)
851 return -1;
852
853 return 0;
854}
#define PG_BINARY
Definition c.h:1287
int errcode_for_file_access(void)
Definition elog.c:886
int CloseTransientFile(int fd)
Definition fd.c:2854
int fsync_fname_ext(const char *fname, bool isdir, bool ignore_perm, int elevel)
Definition fd.c:3846
int pg_fsync(int fd)
Definition fd.c:389
static int fsync_parent_path(const char *fname, int elevel)
Definition fd.c:3922
int OpenTransientFile(const char *fileName, int fileFlags)
Definition fd.c:2677

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

Referenced by AlterSystemSetConfigFile(), apw_dump_now(), BaseBackup(), basic_archive_file(), bbsink_server_end_manifest(), CheckPointReplicationOrigin(), cleanup_objects_atexit(), CleanupAfterArchiveRecovery(), dir_close(), InitWalRecovery(), InstallXLogFileSegment(), KeepFileRestoredFromArchive(), pgss_shmem_shutdown(), pgstat_write_statsfile(), StartupXLOG(), SummarizeWAL(), write_relmap_file(), writeTimeLineHistory(), writeTimeLineHistoryFile(), and XLogArchiveForceDone().

◆ durable_unlink()

int durable_unlink ( const char fname,
int  elevel 
)
extern

Definition at line 872 of file fd.c.

873{
874 if (unlink(fname) < 0)
875 {
876 ereport(elevel,
878 errmsg("could not remove file \"%s\": %m",
879 fname)));
880 return -1;
881 }
882
883 /*
884 * To guarantee that the removal of the file is persistent, fsync its
885 * parent directory.
886 */
887 if (fsync_parent_path(fname, elevel) != 0)
888 return -1;
889
890 return 0;
891}

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

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

◆ FileClose()

void FileClose ( File  file)
extern

Definition at line 1965 of file fd.c.

1966{
1967 Vfd *vfdP;
1968
1969 Assert(FileIsValid(file));
1970
1971 DO_DB(elog(LOG, "FileClose: %d (%s)",
1972 file, VfdCache[file].fileName));
1973
1974 vfdP = &VfdCache[file];
1975
1976 if (!FileIsNotOpen(file))
1977 {
1979
1980 /* close the file */
1981 if (close(vfdP->fd) != 0)
1982 {
1983 /*
1984 * We may need to panic on failure to close non-temporary files;
1985 * see LruDelete.
1986 */
1988 "could not close file \"%s\": %m", vfdP->fileName);
1989 }
1990
1991 --nfile;
1992 vfdP->fd = VFD_CLOSED;
1993
1994 /* remove the file from the lru ring */
1995 Delete(file);
1996 }
1997
1998 if (vfdP->fdstate & FD_TEMP_FILE_LIMIT)
1999 {
2000 /* Subtract its size from current usage (do first in case of error) */
2001 temporary_files_size -= vfdP->fileSize;
2002 vfdP->fileSize = 0;
2003 }
2004
2005 /*
2006 * Delete the file if it was temporary, and make a log entry if wanted
2007 */
2008 if (vfdP->fdstate & FD_DELETE_AT_CLOSE)
2009 {
2010 struct stat filestats;
2011 int stat_errno;
2012
2013 /*
2014 * If we get an error, as could happen within the ereport/elog calls,
2015 * we'll come right back here during transaction abort. Reset the
2016 * flag to ensure that we can't get into an infinite loop. This code
2017 * is arranged to ensure that the worst-case consequence is failing to
2018 * emit log message(s), not failing to attempt the unlink.
2019 */
2020 vfdP->fdstate &= ~FD_DELETE_AT_CLOSE;
2021
2022
2023 /* first try the stat() */
2024 if (stat(vfdP->fileName, &filestats))
2025 stat_errno = errno;
2026 else
2027 stat_errno = 0;
2028
2029 /* in any case do the unlink */
2030 if (unlink(vfdP->fileName))
2031 ereport(LOG,
2033 errmsg("could not delete file \"%s\": %m", vfdP->fileName)));
2034
2035 /* and last report the stat results */
2036 if (stat_errno == 0)
2037 ReportTemporaryFileUsage(vfdP->fileName, filestats.st_size);
2038 else
2039 {
2040 errno = stat_errno;
2041 ereport(LOG,
2043 errmsg("could not stat file \"%s\": %m", vfdP->fileName)));
2044 }
2045 }
2046
2047 /* Unregister it from the resource owner */
2048 if (vfdP->resowner)
2049 ResourceOwnerForgetFile(vfdP->resowner, file);
2050
2051 /*
2052 * Return the Vfd slot to the free list
2053 */
2054 FreeVfd(file);
2055}
#define FD_DELETE_AT_CLOSE
Definition fd.c:195
static void Delete(File file)
Definition fd.c:1253
static void ResourceOwnerForgetFile(ResourceOwner owner, File file)
Definition fd.c:380
#define FileIsValid(file)
Definition fd.c:189
static int nfile
Definition fd.c:225
static void FreeVfd(File file)
Definition fd.c:1459
#define FD_TEMP_FILE_LIMIT
Definition fd.c:197
int data_sync_elevel(int elevel)
Definition fd.c:3985
static void ReportTemporaryFileUsage(const char *path, pgoff_t size)
Definition fd.c:1515
static uint64 temporary_files_size
Definition fd.c:239
#define VFD_CLOSED
Definition fd.c:187
static Vfd * VfdCache
Definition fd.c:219
Definition fd.c:200
#define stat
Definition win32_port.h:74

References Assert, close, data_sync_elevel(), Delete(), DO_DB, elog, ereport, errcode_for_file_access(), errmsg(), fb(), FD_DELETE_AT_CLOSE, FD_TEMP_FILE_LIMIT, FileIsNotOpen, FileIsValid, FreeVfd(), LOG, nfile, pgaio_closing_fd(), ReportTemporaryFileUsage(), ResourceOwnerForgetFile(), stat, temporary_files_size, VFD_CLOSED, and VfdCache.

Referenced by bbsink_server_end_archive(), bbsink_server_end_manifest(), BufFileClose(), BufFileTruncateFileSet(), CleanupTempFiles(), logical_end_heap_rewrite(), mdclose(), mdimmedsync(), mdregistersync(), mdsyncfiletag(), mdtruncate(), pg_wal_summary_contents(), PrepareForIncrementalBackup(), ReorderBufferIterTXNFinish(), ReorderBufferRestoreChanges(), ResOwnerReleaseFile(), and SummarizeWAL().

◆ FileFallocate()

int FileFallocate ( File  file,
pgoff_t  offset,
pgoff_t  amount,
uint32  wait_event_info 
)
extern

Definition at line 2407 of file fd.c.

2408{
2409#ifdef HAVE_POSIX_FALLOCATE
2410 int returnCode;
2411
2412 Assert(FileIsValid(file));
2413
2414 DO_DB(elog(LOG, "FileFallocate: %d (%s) " INT64_FORMAT " " INT64_FORMAT,
2415 file, VfdCache[file].fileName,
2416 (int64) offset, (int64) amount));
2417
2418 returnCode = FileAccess(file);
2419 if (returnCode < 0)
2420 return -1;
2421
2422retry:
2423 pgstat_report_wait_start(wait_event_info);
2424 returnCode = posix_fallocate(VfdCache[file].fd, offset, amount);
2426
2427 if (returnCode == 0)
2428 return 0;
2429 else if (returnCode == EINTR)
2430 goto retry;
2431
2432 /* for compatibility with %m printing etc */
2433 errno = returnCode;
2434
2435 /*
2436 * Return in cases of a "real" failure, if fallocate is not supported,
2437 * fall through to the FileZero() backed implementation.
2438 */
2440 return -1;
2441#endif
2442
2443 return FileZero(file, offset, amount, wait_event_info);
2444}
#define INT64_FORMAT
Definition c.h:564
int64_t int64
Definition c.h:543
static int FileAccess(File file)
Definition fd.c:1479
int FileZero(File file, pgoff_t offset, pgoff_t amount, uint32 wait_event_info)
Definition fd.c:2362
static void pgstat_report_wait_start(uint32 wait_event_info)
Definition wait_event.h:69
static void pgstat_report_wait_end(void)
Definition wait_event.h:85
#define EINTR
Definition win32_port.h:361
#define EOPNOTSUPP
Definition win32_port.h:385

References Assert, DO_DB, EINTR, elog, EOPNOTSUPP, fb(), fd(), FileAccess(), FileIsValid, FileZero(), INT64_FORMAT, LOG, pgstat_report_wait_end(), pgstat_report_wait_start(), and VfdCache.

Referenced by mdzeroextend().

◆ FileGetRawDesc()

int FileGetRawDesc ( File  file)
extern

Definition at line 2515 of file fd.c.

2516{
2517 int returnCode;
2518
2519 returnCode = FileAccess(file);
2520 if (returnCode < 0)
2521 return returnCode;
2522
2523 Assert(FileIsValid(file));
2524 return VfdCache[file].fd;
2525}
int fd
Definition fd.c:201

References Assert, fb(), vfd::fd, FileAccess(), FileIsValid, and VfdCache.

Referenced by mdfd().

◆ FileGetRawFlags()

int FileGetRawFlags ( File  file)
extern

Definition at line 2531 of file fd.c.

2532{
2533 Assert(FileIsValid(file));
2534 return VfdCache[file].fileFlags;
2535}
int fileFlags
Definition fd.c:210

References Assert, vfd::fileFlags, FileIsValid, and VfdCache.

◆ FileGetRawMode()

mode_t FileGetRawMode ( File  file)
extern

Definition at line 2541 of file fd.c.

2542{
2543 Assert(FileIsValid(file));
2544 return VfdCache[file].fileMode;
2545}
mode_t fileMode
Definition fd.c:211

References Assert, FileIsValid, vfd::fileMode, and VfdCache.

◆ FilePathName()

◆ FilePrefetch()

int FilePrefetch ( File  file,
pgoff_t  offset,
pgoff_t  amount,
uint32  wait_event_info 
)
extern

Definition at line 2066 of file fd.c.

2067{
2068 Assert(FileIsValid(file));
2069
2070 DO_DB(elog(LOG, "FilePrefetch: %d (%s) " INT64_FORMAT " " INT64_FORMAT,
2071 file, VfdCache[file].fileName,
2072 (int64) offset, (int64) amount));
2073
2074#if defined(USE_POSIX_FADVISE) && defined(POSIX_FADV_WILLNEED)
2075 {
2076 int returnCode;
2077
2078 returnCode = FileAccess(file);
2079 if (returnCode < 0)
2080 return returnCode;
2081
2082retry:
2083 pgstat_report_wait_start(wait_event_info);
2084 returnCode = posix_fadvise(VfdCache[file].fd, offset, amount,
2087
2088 if (returnCode == EINTR)
2089 goto retry;
2090
2091 return returnCode;
2092 }
2093#elif defined(__darwin__)
2094 {
2095 struct radvisory
2096 {
2097 off_t ra_offset; /* offset into the file */
2098 int ra_count; /* size of the read */
2099 } ra;
2100 int returnCode;
2101
2102 returnCode = FileAccess(file);
2103 if (returnCode < 0)
2104 return returnCode;
2105
2106 ra.ra_offset = offset;
2107 ra.ra_count = amount;
2108 pgstat_report_wait_start(wait_event_info);
2111 if (returnCode != -1)
2112 return 0;
2113 else
2114 return errno;
2115 }
2116#else
2117 return 0;
2118#endif
2119}

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

Referenced by mdprefetch().

◆ FileRead()

static ssize_t FileRead ( File  file,
void buffer,
size_t  amount,
pgoff_t  offset,
uint32  wait_event_info 
)
inlinestatic

Definition at line 225 of file fd.h.

227{
228 struct iovec iov = {
229 .iov_base = buffer,
230 .iov_len = amount
231 };
232
233 return FileReadV(file, &iov, 1, offset, wait_event_info);
234}
ssize_t FileReadV(File file, const struct iovec *iov, int iovcnt, pgoff_t offset, uint32 wait_event_info)
Definition fd.c:2148

References fb(), and FileReadV().

Referenced by BufFileLoadBuffer(), ReadWalSummary(), and ReorderBufferRestoreChanges().

◆ FileReadV()

ssize_t FileReadV ( File  file,
const struct iovec iov,
int  iovcnt,
pgoff_t  offset,
uint32  wait_event_info 
)
extern

Definition at line 2148 of file fd.c.

2150{
2152 Vfd *vfdP;
2153
2154 Assert(FileIsValid(file));
2155
2156 DO_DB(elog(LOG, "FileReadV: %d (%s) " INT64_FORMAT " %d",
2157 file, VfdCache[file].fileName,
2158 (int64) offset,
2159 iovcnt));
2160
2161 returnCode = FileAccess(file);
2162 if (returnCode < 0)
2163 return returnCode;
2164
2165 vfdP = &VfdCache[file];
2166
2167retry:
2168 pgstat_report_wait_start(wait_event_info);
2169 returnCode = pg_preadv(vfdP->fd, iov, iovcnt, offset);
2171
2172 if (returnCode < 0)
2173 {
2174 /*
2175 * Windows may run out of kernel buffers and return "Insufficient
2176 * system resources" error. Wait a bit and retry to solve it.
2177 *
2178 * It is rumored that EINTR is also possible on some Unix filesystems,
2179 * in which case immediate retry is indicated.
2180 */
2181#ifdef WIN32
2183
2184 switch (error)
2185 {
2187 pg_usleep(1000L);
2188 errno = EINTR;
2189 break;
2190 default:
2192 break;
2193 }
2194#endif
2195 /* OK to retry if interrupted */
2196 if (errno == EINTR)
2197 goto retry;
2198 }
2199
2200 return returnCode;
2201}
static ssize_t pg_preadv(int fd, const struct iovec *iov, int iovcnt, pgoff_t offset)
Definition pg_iovec.h:54
void pg_usleep(long microsec)
Definition signal.c:53
static void error(void)
void _dosmaperr(unsigned long)
Definition win32error.c:177

References _dosmaperr(), Assert, DO_DB, EINTR, elog, error(), fb(), FileAccess(), FileIsValid, INT64_FORMAT, LOG, pg_preadv(), pg_usleep(), pgstat_report_wait_end(), pgstat_report_wait_start(), and VfdCache.

Referenced by FileRead(), and mdreadv().

◆ FileSize()

pgoff_t FileSize ( File  file)
extern

Definition at line 2447 of file fd.c.

2448{
2449 Assert(FileIsValid(file));
2450
2451 DO_DB(elog(LOG, "FileSize %d (%s)",
2452 file, VfdCache[file].fileName));
2453
2454 if (FileIsNotOpen(file))
2455 {
2456 if (FileAccess(file) < 0)
2457 return (pgoff_t) -1;
2458 }
2459
2460 return lseek(VfdCache[file].fd, 0, SEEK_END);
2461}
off_t pgoff_t
Definition port.h:421

References Assert, DO_DB, elog, fb(), fd(), FileAccess(), FileIsNotOpen, FileIsValid, LOG, and VfdCache.

Referenced by _mdnblocks(), BufFileSeek(), and BufFileSize().

◆ FileStartReadV()

int FileStartReadV ( struct PgAioHandle ioh,
File  file,
int  iovcnt,
pgoff_t  offset,
uint32  wait_event_info 
)
extern

Definition at line 2204 of file fd.c.

2207{
2208 int returnCode;
2209 Vfd *vfdP;
2210
2211 Assert(FileIsValid(file));
2212
2213 DO_DB(elog(LOG, "FileStartReadV: %d (%s) " INT64_FORMAT " %d",
2214 file, VfdCache[file].fileName,
2215 (int64) offset,
2216 iovcnt));
2217
2218 returnCode = FileAccess(file);
2219 if (returnCode < 0)
2220 return returnCode;
2221
2222 vfdP = &VfdCache[file];
2223
2224 pgaio_io_start_readv(ioh, vfdP->fd, iovcnt, offset);
2225
2226 return 0;
2227}
void pgaio_io_start_readv(PgAioHandle *ioh, int fd, int iovcnt, uint64 offset)
Definition aio_io.c:78

References Assert, DO_DB, elog, fb(), FileAccess(), FileIsValid, INT64_FORMAT, LOG, pgaio_io_start_readv(), and VfdCache.

Referenced by mdstartreadv().

◆ FileSync()

int FileSync ( File  file,
uint32  wait_event_info 
)
extern

Definition at line 2335 of file fd.c.

2336{
2337 int returnCode;
2338
2339 Assert(FileIsValid(file));
2340
2341 DO_DB(elog(LOG, "FileSync: %d (%s)",
2342 file, VfdCache[file].fileName));
2343
2344 returnCode = FileAccess(file);
2345 if (returnCode < 0)
2346 return returnCode;
2347
2348 pgstat_report_wait_start(wait_event_info);
2349 returnCode = pg_fsync(VfdCache[file].fd);
2351
2352 return returnCode;
2353}

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

Referenced by bbsink_server_end_archive(), logical_end_heap_rewrite(), mdimmedsync(), mdsyncfiletag(), and register_dirty_segment().

◆ FileTruncate()

int FileTruncate ( File  file,
pgoff_t  offset,
uint32  wait_event_info 
)
extern

Definition at line 2464 of file fd.c.

2465{
2466 int returnCode;
2467
2468 Assert(FileIsValid(file));
2469
2470 DO_DB(elog(LOG, "FileTruncate %d (%s)",
2471 file, VfdCache[file].fileName));
2472
2473 returnCode = FileAccess(file);
2474 if (returnCode < 0)
2475 return returnCode;
2476
2477 pgstat_report_wait_start(wait_event_info);
2478 returnCode = pg_ftruncate(VfdCache[file].fd, offset);
2480
2481 if (returnCode == 0 && VfdCache[file].fileSize > offset)
2482 {
2483 /* adjust our state for truncation of a temp file */
2484 Assert(VfdCache[file].fdstate & FD_TEMP_FILE_LIMIT);
2485 temporary_files_size -= VfdCache[file].fileSize - offset;
2486 VfdCache[file].fileSize = offset;
2487 }
2488
2489 return returnCode;
2490}
static int pg_ftruncate(int fd, pgoff_t length)
Definition fd.c:703
pgoff_t fileSize
Definition fd.c:207

References Assert, DO_DB, elog, fb(), fd(), FD_TEMP_FILE_LIMIT, FileAccess(), FileIsValid, vfd::fileSize, LOG, pg_ftruncate(), pgstat_report_wait_end(), pgstat_report_wait_start(), temporary_files_size, and VfdCache.

Referenced by BufFileTruncateFileSet(), and mdtruncate().

◆ FileWrite()

static ssize_t FileWrite ( File  file,
const void buffer,
size_t  amount,
pgoff_t  offset,
uint32  wait_event_info 
)
inlinestatic

Definition at line 237 of file fd.h.

239{
240 struct iovec iov = {
241 .iov_base = unconstify(void *, buffer),
242 .iov_len = amount
243 };
244
245 return FileWriteV(file, &iov, 1, offset, wait_event_info);
246}
#define unconstify(underlying_type, expr)
Definition c.h:1240
ssize_t FileWriteV(File file, const struct iovec *iov, int iovcnt, pgoff_t offset, uint32 wait_event_info)
Definition fd.c:2230

References fb(), FileWriteV(), and unconstify.

Referenced by bbsink_server_archive_contents(), bbsink_server_manifest_contents(), BufFileDumpBuffer(), logical_heap_rewrite_flush_mappings(), mdextend(), and WriteWalSummary().

◆ FileWriteback()

void FileWriteback ( File  file,
pgoff_t  offset,
pgoff_t  nbytes,
uint32  wait_event_info 
)
extern

Definition at line 2122 of file fd.c.

2123{
2124 int returnCode;
2125
2126 Assert(FileIsValid(file));
2127
2128 DO_DB(elog(LOG, "FileWriteback: %d (%s) " INT64_FORMAT " " INT64_FORMAT,
2129 file, VfdCache[file].fileName,
2130 (int64) offset, (int64) nbytes));
2131
2132 if (nbytes <= 0)
2133 return;
2134
2135 if (VfdCache[file].fileFlags & PG_O_DIRECT)
2136 return;
2137
2138 returnCode = FileAccess(file);
2139 if (returnCode < 0)
2140 return;
2141
2142 pgstat_report_wait_start(wait_event_info);
2143 pg_flush_data(VfdCache[file].fd, offset, nbytes);
2145}
void pg_flush_data(int fd, pgoff_t offset, pgoff_t nbytes)
Definition fd.c:525

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

Referenced by mdwriteback().

◆ FileWriteV()

ssize_t FileWriteV ( File  file,
const struct iovec iov,
int  iovcnt,
pgoff_t  offset,
uint32  wait_event_info 
)
extern

Definition at line 2230 of file fd.c.

2232{
2234 Vfd *vfdP;
2235
2236 Assert(FileIsValid(file));
2237
2238 DO_DB(elog(LOG, "FileWriteV: %d (%s) " INT64_FORMAT " %d",
2239 file, VfdCache[file].fileName,
2240 (int64) offset,
2241 iovcnt));
2242
2243 returnCode = FileAccess(file);
2244 if (returnCode < 0)
2245 return returnCode;
2246
2247 vfdP = &VfdCache[file];
2248
2249 /*
2250 * If enforcing temp_file_limit and it's a temp file, check to see if the
2251 * write would overrun temp_file_limit, and throw error if so. Note: it's
2252 * really a modularity violation to throw error here; we should set errno
2253 * and return -1. However, there's no way to report a suitable error
2254 * message if we do that. All current callers would just throw error
2255 * immediately anyway, so this is safe at present.
2256 */
2257 if (temp_file_limit >= 0 && (vfdP->fdstate & FD_TEMP_FILE_LIMIT))
2258 {
2259 pgoff_t past_write = offset;
2260
2261 for (int i = 0; i < iovcnt; ++i)
2262 past_write += iov[i].iov_len;
2263
2264 if (past_write > vfdP->fileSize)
2265 {
2267
2269 if (newTotal > (uint64) temp_file_limit * (uint64) 1024)
2270 ereport(ERROR,
2272 errmsg("temporary file size exceeds \"temp_file_limit\" (%dkB)",
2273 temp_file_limit)));
2274 }
2275 }
2276
2277retry:
2278 pgstat_report_wait_start(wait_event_info);
2279 returnCode = pg_pwritev(vfdP->fd, iov, iovcnt, offset);
2281
2282 if (returnCode >= 0)
2283 {
2284 /*
2285 * Some callers expect short writes to set errno, and traditionally we
2286 * have assumed that they imply disk space shortage. We don't want to
2287 * waste CPU cycles adding up the total size here, so we'll just set
2288 * it for all successful writes in case such a caller determines that
2289 * the write was short and ereports "%m".
2290 */
2291 errno = ENOSPC;
2292
2293 /*
2294 * Maintain fileSize and temporary_files_size if it's a temp file.
2295 */
2296 if (vfdP->fdstate & FD_TEMP_FILE_LIMIT)
2297 {
2298 pgoff_t past_write = offset + returnCode;
2299
2300 if (past_write > vfdP->fileSize)
2301 {
2302 temporary_files_size += past_write - vfdP->fileSize;
2303 vfdP->fileSize = past_write;
2304 }
2305 }
2306 }
2307 else
2308 {
2309 /*
2310 * See comments in FileReadV()
2311 */
2312#ifdef WIN32
2314
2315 switch (error)
2316 {
2318 pg_usleep(1000L);
2319 errno = EINTR;
2320 break;
2321 default:
2323 break;
2324 }
2325#endif
2326 /* OK to retry if interrupted */
2327 if (errno == EINTR)
2328 goto retry;
2329 }
2330
2331 return returnCode;
2332}
uint64_t uint64
Definition c.h:547
int temp_file_limit
Definition guc_tables.c:560
static ssize_t pg_pwritev(int fd, const struct iovec *iov, int iovcnt, pgoff_t offset)
Definition pg_iovec.h:93

References _dosmaperr(), Assert, DO_DB, EINTR, elog, ereport, errcode(), errmsg(), ERROR, error(), fb(), FD_TEMP_FILE_LIMIT, FileAccess(), FileIsValid, vfd::fileSize, i, INT64_FORMAT, LOG, pg_pwritev(), pg_usleep(), pgstat_report_wait_end(), pgstat_report_wait_start(), temp_file_limit, temporary_files_size, and VfdCache.

Referenced by FileWrite(), and mdwritev().

◆ FileZero()

int FileZero ( File  file,
pgoff_t  offset,
pgoff_t  amount,
uint32  wait_event_info 
)
extern

Definition at line 2362 of file fd.c.

2363{
2364 int returnCode;
2366
2367 Assert(FileIsValid(file));
2368
2369 DO_DB(elog(LOG, "FileZero: %d (%s) " INT64_FORMAT " " INT64_FORMAT,
2370 file, VfdCache[file].fileName,
2371 (int64) offset, (int64) amount));
2372
2373 returnCode = FileAccess(file);
2374 if (returnCode < 0)
2375 return returnCode;
2376
2377 pgstat_report_wait_start(wait_event_info);
2378 written = pg_pwrite_zeros(VfdCache[file].fd, amount, offset);
2380
2381 if (written < 0)
2382 return -1;
2383 else if (written != amount)
2384 {
2385 /* if errno is unset, assume problem is no disk space */
2386 if (errno == 0)
2387 errno = ENOSPC;
2388 return -1;
2389 }
2390
2391 return 0;
2392}
ssize_t pg_pwrite_zeros(int fd, size_t size, pgoff_t offset)
Definition file_utils.c:709

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

Referenced by FileFallocate(), and mdzeroextend().

◆ FreeDir()

int FreeDir ( DIR dir)
extern

Definition at line 3008 of file fd.c.

3009{
3010 int i;
3011
3012 /* Nothing to do if AllocateDir failed */
3013 if (dir == NULL)
3014 return 0;
3015
3016 DO_DB(elog(LOG, "FreeDir: Allocated %d", numAllocatedDescs));
3017
3018 /* Remove dir from list of allocated dirs, if it's present */
3019 for (i = numAllocatedDescs; --i >= 0;)
3020 {
3021 AllocateDesc *desc = &allocatedDescs[i];
3022
3023 if (desc->kind == AllocateDescDir && desc->desc.dir == dir)
3024 return FreeDesc(desc);
3025 }
3026
3027 /* Only get here if someone passes us a dir not in allocatedDescs */
3028 elog(WARNING, "dir passed to FreeDir was not obtained from AllocateDir");
3029
3030 return closedir(dir);
3031}
int closedir(DIR *)
Definition dirent.c:127

References allocatedDescs, AllocateDescDir, closedir(), AllocateDesc::desc, AllocateDesc::dir, DO_DB, elog, fb(), 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(), do_pg_backup_start(), dsm_cleanup_for_mmap(), extension_file_exists(), get_ext_ver_list(), GetConfFilesInDir(), getInstallationPaths(), GetWalSummaries(), movedb(), ParseTzFile(), perform_base_backup(), pg_available_extension_versions(), pg_available_extensions(), pg_ls_dir(), pg_ls_dir_files(), pg_tablespace_databases(), pg_tzenumerate_end(), pg_tzenumerate_next(), pgarch_readyXlog(), RelationCacheInitFileRemove(), RelationCacheInitFileRemoveInDir(), RemoveNonParentXlogFiles(), RemoveOldXlogFiles(), RemovePgTempFiles(), RemovePgTempFilesInDir(), RemovePgTempRelationFiles(), RemovePgTempRelationFilesInDbspace(), RemoveTempXlogFiles(), ReorderBufferCleanupSerializedTXNs(), ResetUnloggedRelations(), ResetUnloggedRelationsInDbspaceDir(), ResetUnloggedRelationsInTablespaceDir(), restoreTwoPhaseData(), scan_directory_ci(), sendDir(), SlruScanDirectory(), StartupReorderBuffer(), StartupReplicationSlots(), SyncDataDirectory(), UpdateLogicalMappings(), walkdir(), and XLogGetOldestSegno().

◆ FreeFile()

int FreeFile ( FILE file)
extern

Definition at line 2826 of file fd.c.

2827{
2828 int i;
2829
2830 DO_DB(elog(LOG, "FreeFile: Allocated %d", numAllocatedDescs));
2831
2832 /* Remove file from list of allocated files, if it's present */
2833 for (i = numAllocatedDescs; --i >= 0;)
2834 {
2835 AllocateDesc *desc = &allocatedDescs[i];
2836
2837 if (desc->kind == AllocateDescFile && desc->desc.file == file)
2838 return FreeDesc(desc);
2839 }
2840
2841 /* Only get here if someone passes us a file not in allocatedDescs */
2842 elog(WARNING, "file passed to FreeFile was not obtained from AllocateFile");
2843
2844 return fclose(file);
2845}

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

Referenced by AlterSystemSetConfigFile(), apw_dump_now(), apw_load_buffers(), checkControlFile(), do_pg_backup_stop(), EndCopy(), EndCopyFrom(), entry_reset(), existsTimeLineHistory(), ExportSnapshot(), free_auth_file(), gc_qtexts(), GetHugePageSize(), ImportSnapshot(), load_dh_file(), load_relcache_init_file(), parse_extension_control_file(), ParseConfigFile(), ParseTzFile(), pg_current_logfile(), pg_promote(), pgss_shmem_shutdown(), pgss_shmem_startup(), pgstat_read_statsfile(), pgstat_write_statsfile(), read_backup_label(), read_binary_file(), read_tablespace_map(), read_whole_file(), readTimeLineHistory(), test_custom_stats_var_finish(), tsearch_readline_end(), ValidatePgVersion(), write_relcache_init_file(), XLogArchiveForceDone(), and XLogArchiveNotify().

◆ fsync_fname()

◆ fsync_fname_ext()

int fsync_fname_ext ( const char fname,
bool  isdir,
bool  ignore_perm,
int  elevel 
)
extern

Definition at line 3846 of file fd.c.

3847{
3848 int fd;
3849 int flags;
3850 int returncode;
3851
3852 /*
3853 * Some OSs require directories to be opened read-only whereas other
3854 * systems don't allow us to fsync files opened read-only; so we need both
3855 * cases here. Using O_RDWR will cause us to fail to fsync files that are
3856 * not writable by our userid, but we assume that's OK.
3857 */
3858 flags = PG_BINARY;
3859 if (!isdir)
3860 flags |= O_RDWR;
3861 else
3862 flags |= O_RDONLY;
3863
3864 fd = OpenTransientFile(fname, flags);
3865
3866 /*
3867 * Some OSs don't allow us to open directories at all (Windows returns
3868 * EACCES), just ignore the error in that case. If desired also silently
3869 * ignoring errors about unreadable files. Log others.
3870 */
3871 if (fd < 0 && isdir && (errno == EISDIR || errno == EACCES))
3872 return 0;
3873 else if (fd < 0 && ignore_perm && errno == EACCES)
3874 return 0;
3875 else if (fd < 0)
3876 {
3877 ereport(elevel,
3879 errmsg("could not open file \"%s\": %m", fname)));
3880 return -1;
3881 }
3882
3884
3885 /*
3886 * Some OSes don't allow us to fsync directories at all, so we can ignore
3887 * those errors. Anything else needs to be logged.
3888 */
3889 if (returncode != 0 && !(isdir && (errno == EBADF || errno == EINVAL)))
3890 {
3891 int save_errno;
3892
3893 /* close file upon error, might not be in transaction context */
3894 save_errno = errno;
3896 errno = save_errno;
3897
3898 ereport(elevel,
3900 errmsg("could not fsync file \"%s\": %m", fname)));
3901 return -1;
3902 }
3903
3904 if (CloseTransientFile(fd) != 0)
3905 {
3906 ereport(elevel,
3908 errmsg("could not close file \"%s\": %m", fname)));
3909 return -1;
3910 }
3911
3912 return 0;
3913}

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

Referenced by datadir_fsync_fname(), durable_rename(), fsync_fname(), and fsync_parent_path().

◆ GetNextTempTableSpace()

Oid GetNextTempTableSpace ( void  )
extern

Definition at line 3158 of file fd.c.

3159{
3160 if (numTempTableSpaces > 0)
3161 {
3162 /* Advance nextTempTableSpace counter with wraparound */
3166 }
3167 return InvalidOid;
3168}
static int nextTempTableSpace
Definition fd.c:293
#define InvalidOid

References InvalidOid, nextTempTableSpace, numTempTableSpaces, and tempTableSpaces.

Referenced by GetDefaultTablespace(), and OpenTemporaryFile().

◆ GetTempTablespaces()

int GetTempTablespaces ( Oid tableSpaces,
int  numSpaces 
)
extern

Definition at line 3140 of file fd.c.

3141{
3142 int i;
3143
3145 for (i = 0; i < numTempTableSpaces && i < numSpaces; ++i)
3147
3148 return i;
3149}
bool TempTablespacesAreSet(void)
Definition fd.c:3125

References Assert, fb(), i, numTempTableSpaces, tempTableSpaces, and TempTablespacesAreSet().

Referenced by FileSetInit().

◆ InitFileAccess()

void InitFileAccess ( void  )
extern

Definition at line 903 of file fd.c.

904{
905 Assert(SizeVfdCache == 0); /* call me only once */
906
907 /* initialize cache header entry */
908 VfdCache = (Vfd *) malloc(sizeof(Vfd));
909 if (VfdCache == NULL)
912 errmsg("out of memory")));
913
914 MemSet(&(VfdCache[0]), 0, sizeof(Vfd));
916
917 SizeVfdCache = 1;
918}
#define MemSet(start, val, len)
Definition c.h:1013
#define FATAL
Definition elog.h:41
#define malloc(a)

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

Referenced by BaseInit().

◆ InitTemporaryFileAccess()

void InitTemporaryFileAccess ( void  )
extern

Definition at line 933 of file fd.c.

934{
935 Assert(SizeVfdCache != 0); /* InitFileAccess() needs to have run */
936 Assert(!temporary_files_allowed); /* call me only once */
937
938 /*
939 * Register before-shmem-exit hook to ensure temp files are dropped while
940 * we can still report stats.
941 */
943
944#ifdef USE_ASSERT_CHECKING
946#endif
947}
static void BeforeShmemExit_Files(int code, Datum arg)
Definition fd.c:3227
void before_shmem_exit(pg_on_exit_callback function, Datum arg)
Definition ipc.c:344

References Assert, before_shmem_exit(), BeforeShmemExit_Files(), fb(), and SizeVfdCache.

Referenced by BaseInit().

◆ looks_like_temp_rel_name()

bool looks_like_temp_rel_name ( const char name)
extern

Definition at line 3498 of file fd.c.

3499{
3500 int pos;
3501 int savepos;
3502
3503 /* Must start with "t". */
3504 if (name[0] != 't')
3505 return false;
3506
3507 /* Followed by a non-empty string of digits and then an underscore. */
3508 for (pos = 1; isdigit((unsigned char) name[pos]); ++pos)
3509 ;
3510 if (pos == 1 || name[pos] != '_')
3511 return false;
3512
3513 /* Followed by another nonempty string of digits. */
3514 for (savepos = ++pos; isdigit((unsigned char) name[pos]); ++pos)
3515 ;
3516 if (savepos == pos)
3517 return false;
3518
3519 /* We might have _forkname or .segment or both. */
3520 if (name[pos] == '_')
3521 {
3522 int forkchar = forkname_chars(&name[pos + 1], NULL);
3523
3524 if (forkchar <= 0)
3525 return false;
3526 pos += forkchar + 1;
3527 }
3528 if (name[pos] == '.')
3529 {
3530 int segchar;
3531
3532 for (segchar = 1; isdigit((unsigned char) name[pos + segchar]); ++segchar)
3533 ;
3534 if (segchar <= 1)
3535 return false;
3536 pos += segchar;
3537 }
3538
3539 /* Now we should be at the end. */
3540 if (name[pos] != '\0')
3541 return false;
3542 return true;
3543}
int forkname_chars(const char *str, ForkNumber *fork)
Definition relpath.c:81

References fb(), forkname_chars(), and name.

Referenced by RemovePgTempRelationFilesInDbspace(), and sendDir().

◆ MakePGDirectory()

◆ OpenPipeStream()

FILE * OpenPipeStream ( const char command,
const char mode 
)
extern

Definition at line 2730 of file fd.c.

2731{
2732 FILE *file;
2733 int save_errno;
2734
2735 DO_DB(elog(LOG, "OpenPipeStream: Allocated %d (%s)",
2736 numAllocatedDescs, command));
2737
2738 /* Can we allocate another non-virtual FD? */
2739 if (!reserveAllocatedDesc())
2740 ereport(ERROR,
2742 errmsg("exceeded maxAllocatedDescs (%d) while trying to execute command \"%s\"",
2743 maxAllocatedDescs, command)));
2744
2745 /* Close excess kernel FDs. */
2747
2748TryAgain:
2749 fflush(NULL);
2751 errno = 0;
2752 file = popen(command, mode);
2753 save_errno = errno;
2755 errno = save_errno;
2756 if (file != NULL)
2757 {
2759
2760 desc->kind = AllocateDescPipe;
2761 desc->desc.file = file;
2764 return desc->desc.file;
2765 }
2766
2767 if (errno == EMFILE || errno == ENFILE)
2768 {
2769 ereport(LOG,
2771 errmsg("out of file descriptors: %m; release and retry")));
2772 if (ReleaseLruFile())
2773 goto TryAgain;
2774 errno = save_errno;
2775 }
2776
2777 return NULL;
2778}
#define pqsignal
Definition port.h:547
#define SIGPIPE
Definition win32_port.h:163

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

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

◆ OpenTemporaryFile()

File OpenTemporaryFile ( bool  interXact)
extern

Definition at line 1711 of file fd.c.

1712{
1713 File file = 0;
1714
1715 Assert(temporary_files_allowed); /* check temp file access is up */
1716
1717 /*
1718 * Make sure the current resource owner has space for this File before we
1719 * open it, if we'll be registering it below.
1720 */
1721 if (!interXact)
1723
1724 /*
1725 * If some temp tablespace(s) have been given to us, try to use the next
1726 * one. If a given tablespace can't be found, we silently fall back to
1727 * the database's default tablespace.
1728 *
1729 * BUT: if the temp file is slated to outlive the current transaction,
1730 * force it into the database's default tablespace, so that it will not
1731 * pose a threat to possible tablespace drop attempts.
1732 */
1733 if (numTempTableSpaces > 0 && !interXact)
1734 {
1736
1737 if (OidIsValid(tblspcOid))
1739 }
1740
1741 /*
1742 * If not, or if tablespace is bad, create in database's default
1743 * tablespace. MyDatabaseTableSpace should normally be set before we get
1744 * here, but just in case it isn't, fall back to pg_default tablespace.
1745 */
1746 if (file <= 0)
1750 true);
1751
1752 /* Mark it for deletion at close and temporary file size limit */
1754
1755 /* Register it with the current resource owner */
1756 if (!interXact)
1758
1759 return file;
1760}
#define OidIsValid(objectId)
Definition c.h:788
Oid GetNextTempTableSpace(void)
Definition fd.c:3158
static File OpenTemporaryFileInTablespace(Oid tblspcOid, bool rejectError)
Definition fd.c:1791
static void RegisterTemporaryFile(File file)
Definition fd.c:1534
int File
Definition fd.h:51
Oid MyDatabaseTableSpace
Definition globals.c:96
return true
Definition isn.c:130
unsigned int Oid
ResourceOwner CurrentResourceOwner
Definition resowner.c:173
void ResourceOwnerEnlarge(ResourceOwner owner)
Definition resowner.c:449
unsigned short fdstate
Definition fd.c:202

References Assert, CurrentResourceOwner, fb(), FD_DELETE_AT_CLOSE, FD_TEMP_FILE_LIMIT, vfd::fdstate, GetNextTempTableSpace(), MyDatabaseTableSpace, numTempTableSpaces, OidIsValid, OpenTemporaryFileInTablespace(), RegisterTemporaryFile(), ResourceOwnerEnlarge(), and VfdCache.

Referenced by BufFileCreateTemp(), and extendBufFile().

◆ OpenTransientFile()

◆ OpenTransientFilePerm()

int OpenTransientFilePerm ( const char fileName,
int  fileFlags,
mode_t  fileMode 
)
extern

Definition at line 2686 of file fd.c.

2687{
2688 int fd;
2689
2690 DO_DB(elog(LOG, "OpenTransientFile: Allocated %d (%s)",
2691 numAllocatedDescs, fileName));
2692
2693 /* Can we allocate another non-virtual FD? */
2694 if (!reserveAllocatedDesc())
2695 ereport(ERROR,
2697 errmsg("exceeded maxAllocatedDescs (%d) while trying to open file \"%s\"",
2698 maxAllocatedDescs, fileName)));
2699
2700 /* Close excess kernel FDs. */
2702
2703 fd = BasicOpenFilePerm(fileName, fileFlags, fileMode);
2704
2705 if (fd >= 0)
2706 {
2708
2709 desc->kind = AllocateDescRawFD;
2710 desc->desc.fd = fd;
2713
2714 return fd;
2715 }
2716
2717 return -1; /* failure */
2718}

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

Referenced by be_lo_export(), and OpenTransientFile().

◆ PathNameCreateTemporaryDir()

void PathNameCreateTemporaryDir ( const char basedir,
const char directory 
)
extern

Definition at line 1647 of file fd.c.

1648{
1649 if (MakePGDirectory(directory) < 0)
1650 {
1651 if (errno == EEXIST)
1652 return;
1653
1654 /*
1655 * Failed. Try to create basedir first in case it's missing. Tolerate
1656 * EEXIST to close a race against another process following the same
1657 * algorithm.
1658 */
1659 if (MakePGDirectory(basedir) < 0 && errno != EEXIST)
1660 ereport(ERROR,
1662 errmsg("cannot create temporary directory \"%s\": %m",
1663 basedir)));
1664
1665 /* Try again. */
1666 if (MakePGDirectory(directory) < 0 && errno != EEXIST)
1667 ereport(ERROR,
1669 errmsg("cannot create temporary subdirectory \"%s\": %m",
1670 directory)));
1671 }
1672}
int MakePGDirectory(const char *directoryName)
Definition fd.c:3962
static char * basedir
static const char * directory
Definition zic.c:648

References basedir, directory, ereport, errcode_for_file_access(), errmsg(), ERROR, fb(), and MakePGDirectory().

Referenced by FileSetCreate().

◆ PathNameCreateTemporaryFile()

File PathNameCreateTemporaryFile ( const char path,
bool  error_on_failure 
)
extern

Definition at line 1848 of file fd.c.

1849{
1850 File file;
1851
1852 Assert(temporary_files_allowed); /* check temp file access is up */
1853
1855
1856 /*
1857 * Open the file. Note: we don't use O_EXCL, in case there is an orphaned
1858 * temp file that can be reused.
1859 */
1860 file = PathNameOpenFile(path, O_RDWR | O_CREAT | O_TRUNC | PG_BINARY);
1861 if (file <= 0)
1862 {
1863 if (error_on_failure)
1864 ereport(ERROR,
1866 errmsg("could not create temporary file \"%s\": %m",
1867 path)));
1868 else
1869 return file;
1870 }
1871
1872 /* Mark it for temp_file_limit accounting. */
1874
1875 /* Register it for automatic close. */
1877
1878 return file;
1879}
File PathNameOpenFile(const char *fileName, int fileFlags)
Definition fd.c:1562

References Assert, CurrentResourceOwner, ereport, errcode_for_file_access(), errmsg(), ERROR, fb(), FD_TEMP_FILE_LIMIT, vfd::fdstate, PathNameOpenFile(), PG_BINARY, RegisterTemporaryFile(), ResourceOwnerEnlarge(), and VfdCache.

Referenced by FileSetCreate().

◆ PathNameDeleteTemporaryDir()

void PathNameDeleteTemporaryDir ( const char dirname)
extern

Definition at line 1678 of file fd.c.

1679{
1680 struct stat statbuf;
1681
1682 /* Silently ignore missing directory. */
1683 if (stat(dirname, &statbuf) != 0 && errno == ENOENT)
1684 return;
1685
1686 /*
1687 * Currently, walkdir doesn't offer a way for our passed in function to
1688 * maintain state. Perhaps it should, so that we could tell the caller
1689 * whether this operation succeeded or failed. Since this operation is
1690 * used in a cleanup path, we wouldn't actually behave differently: we'll
1691 * just log failures.
1692 */
1693 walkdir(dirname, unlink_if_exists_fname, false, LOG);
1694}
static void unlink_if_exists_fname(const char *fname, bool isdir, int elevel)
Definition fd.c:3821
static void walkdir(const char *path, void(*action)(const char *fname, bool isdir, int elevel), bool process_symlinks, int elevel)
Definition fd.c:3707

References fb(), LOG, stat, unlink_if_exists_fname(), and walkdir().

Referenced by FileSetDeleteAll().

◆ PathNameDeleteTemporaryFile()

bool PathNameDeleteTemporaryFile ( const char path,
bool  error_on_failure 
)
extern

Definition at line 1919 of file fd.c.

1920{
1921 struct stat filestats;
1922 int stat_errno;
1923
1924 /* Get the final size for pgstat reporting. */
1925 if (stat(path, &filestats) != 0)
1926 stat_errno = errno;
1927 else
1928 stat_errno = 0;
1929
1930 /*
1931 * Unlike FileClose's automatic file deletion code, we tolerate
1932 * non-existence to support BufFileDeleteFileSet which doesn't know how
1933 * many segments it has to delete until it runs out.
1934 */
1935 if (stat_errno == ENOENT)
1936 return false;
1937
1938 if (unlink(path) < 0)
1939 {
1940 if (errno != ENOENT)
1943 errmsg("could not unlink temporary file \"%s\": %m",
1944 path)));
1945 return false;
1946 }
1947
1948 if (stat_errno == 0)
1949 ReportTemporaryFileUsage(path, filestats.st_size);
1950 else
1951 {
1952 errno = stat_errno;
1953 ereport(LOG,
1955 errmsg("could not stat file \"%s\": %m", path)));
1956 }
1957
1958 return true;
1959}

References ereport, errcode_for_file_access(), errmsg(), ERROR, fb(), LOG, ReportTemporaryFileUsage(), and stat.

Referenced by FileSetDelete(), and unlink_if_exists_fname().

◆ PathNameOpenFile()

File PathNameOpenFile ( const char fileName,
int  fileFlags 
)
extern

◆ PathNameOpenFilePerm()

File PathNameOpenFilePerm ( const char fileName,
int  fileFlags,
mode_t  fileMode 
)
extern

Definition at line 1575 of file fd.c.

1576{
1577 char *fnamecopy;
1578 File file;
1579 Vfd *vfdP;
1580
1581 DO_DB(elog(LOG, "PathNameOpenFilePerm: %s %x %o",
1582 fileName, fileFlags, fileMode));
1583
1584 /*
1585 * We need a malloc'd copy of the file name; fail cleanly if no room.
1586 */
1587 fnamecopy = strdup(fileName);
1588 if (fnamecopy == NULL)
1589 ereport(ERROR,
1591 errmsg("out of memory")));
1592
1593 file = AllocateVfd();
1594 vfdP = &VfdCache[file];
1595
1596 /* Close excess kernel FDs. */
1598
1599 /*
1600 * Descriptors managed by VFDs are implicitly marked O_CLOEXEC. The
1601 * client shouldn't be expected to know which kernel descriptors are
1602 * currently open, so it wouldn't make sense for them to be inherited by
1603 * executed subprograms.
1604 */
1605 fileFlags |= O_CLOEXEC;
1606
1607 vfdP->fd = BasicOpenFilePerm(fileName, fileFlags, fileMode);
1608
1609 if (vfdP->fd < 0)
1610 {
1611 int save_errno = errno;
1612
1613 FreeVfd(file);
1614 free(fnamecopy);
1615 errno = save_errno;
1616 return -1;
1617 }
1618 ++nfile;
1619 DO_DB(elog(LOG, "PathNameOpenFile: success %d",
1620 vfdP->fd));
1621
1622 vfdP->fileName = fnamecopy;
1623 /* Saved flags are adjusted to be OK for re-opening file */
1624 vfdP->fileFlags = fileFlags & ~(O_CREAT | O_TRUNC | O_EXCL);
1625 vfdP->fileMode = fileMode;
1626 vfdP->fileSize = 0;
1627 vfdP->fdstate = 0x0;
1628 vfdP->resowner = NULL;
1629
1630 Insert(file);
1631
1632 return file;
1633}
static File AllocateVfd(void)
Definition fd.c:1401
static void Insert(File file)
Definition fd.c:1300
#define free(a)
#define O_CLOEXEC
Definition win32_port.h:344

References AllocateVfd(), BasicOpenFilePerm(), DO_DB, elog, ereport, errcode(), errmsg(), ERROR, fb(), free, FreeVfd(), Insert(), LOG, nfile, O_CLOEXEC, ReleaseLruFiles(), and VfdCache.

Referenced by PathNameOpenFile().

◆ PathNameOpenTemporaryFile()

File PathNameOpenTemporaryFile ( const char path,
int  mode 
)
extern

Definition at line 1888 of file fd.c.

1889{
1890 File file;
1891
1892 Assert(temporary_files_allowed); /* check temp file access is up */
1893
1895
1896 file = PathNameOpenFile(path, mode | PG_BINARY);
1897
1898 /* If no such file, then we don't raise an error. */
1899 if (file <= 0 && errno != ENOENT)
1900 ereport(ERROR,
1902 errmsg("could not open temporary file \"%s\": %m",
1903 path)));
1904
1905 if (file > 0)
1906 {
1907 /* Register it for automatic close. */
1909 }
1910
1911 return file;
1912}

References Assert, CurrentResourceOwner, ereport, errcode_for_file_access(), errmsg(), ERROR, fb(), mode, PathNameOpenFile(), PG_BINARY, RegisterTemporaryFile(), and ResourceOwnerEnlarge().

Referenced by FileSetOpen().

◆ pg_fdatasync()

int pg_fdatasync ( int  fd)
extern

Definition at line 480 of file fd.c.

481{
482 int rc;
483
484 if (!enableFsync)
485 return 0;
486
487retry:
488 rc = fdatasync(fd);
489
490 if (rc == -1 && errno == EINTR)
491 goto retry;
492
493 return rc;
494}
int fdatasync(int fd)
bool enableFsync
Definition globals.c:129

References EINTR, enableFsync, fb(), fd(), and fdatasync().

Referenced by issue_xlog_fsync().

◆ pg_file_exists()

bool pg_file_exists ( const char name)
extern

Definition at line 503 of file fd.c.

504{
505 struct stat st;
506
507 Assert(name != NULL);
508
509 if (stat(name, &st) == 0)
510 return !S_ISDIR(st.st_mode);
511 else if (!(errno == ENOENT || errno == ENOTDIR || errno == EACCES))
514 errmsg("could not access file \"%s\": %m", name)));
515
516 return false;
517}
#define S_ISDIR(m)
Definition win32_port.h:315

References Assert, ereport, errcode_for_file_access(), errmsg(), ERROR, fb(), name, S_ISDIR, stat::st_mode, and stat.

Referenced by expand_dynamic_library_name(), find_in_path(), find_in_paths(), and provider_init().

◆ pg_flush_data()

void pg_flush_data ( int  fd,
pgoff_t  offset,
pgoff_t  nbytes 
)
extern

Definition at line 525 of file fd.c.

526{
527 /*
528 * Right now file flushing is primarily used to avoid making later
529 * fsync()/fdatasync() calls have less impact. Thus don't trigger flushes
530 * if fsyncs are disabled - that's a decision we might want to make
531 * configurable at some point.
532 */
533 if (!enableFsync)
534 return;
535
536 /*
537 * We compile all alternatives that are supported on the current platform,
538 * to find portability problems more easily.
539 */
540#if defined(HAVE_SYNC_FILE_RANGE)
541 {
542 int rc;
543 static bool not_implemented_by_kernel = false;
544
546 return;
547
548retry:
549
550 /*
551 * sync_file_range(SYNC_FILE_RANGE_WRITE), currently linux specific,
552 * tells the OS that writeback for the specified blocks should be
553 * started, but that we don't want to wait for completion. Note that
554 * this call might block if too much dirty data exists in the range.
555 * This is the preferable method on OSs supporting it, as it works
556 * reliably when available (contrast to msync()) and doesn't flush out
557 * clean data (like FADV_DONTNEED).
558 */
559 rc = sync_file_range(fd, offset, nbytes,
561 if (rc != 0)
562 {
563 int elevel;
564
565 if (rc == EINTR)
566 goto retry;
567
568 /*
569 * For systems that don't have an implementation of
570 * sync_file_range() such as Windows WSL, generate only one
571 * warning and then suppress all further attempts by this process.
572 */
573 if (errno == ENOSYS)
574 {
575 elevel = WARNING;
577 }
578 else
579 elevel = data_sync_elevel(WARNING);
580
581 ereport(elevel,
583 errmsg("could not flush dirty data: %m")));
584 }
585
586 return;
587 }
588#endif
589#if !defined(WIN32) && defined(MS_ASYNC)
590 {
591 void *p;
592 static int pagesize = 0;
593
594 /*
595 * On several OSs msync(MS_ASYNC) on a mmap'ed file triggers
596 * writeback. On linux it only does so if MS_SYNC is specified, but
597 * then it does the writeback synchronously. Luckily all common linux
598 * systems have sync_file_range(). This is preferable over
599 * FADV_DONTNEED because it doesn't flush out clean data.
600 *
601 * We map the file (mmap()), tell the kernel to sync back the contents
602 * (msync()), and then remove the mapping again (munmap()).
603 */
604
605 /* mmap() needs actual length if we want to map whole file */
606 if (offset == 0 && nbytes == 0)
607 {
608 nbytes = lseek(fd, 0, SEEK_END);
609 if (nbytes < 0)
610 {
613 errmsg("could not determine dirty data size: %m")));
614 return;
615 }
616 }
617
618 /*
619 * Some platforms reject partial-page mmap() attempts. To deal with
620 * that, just truncate the request to a page boundary. If any extra
621 * bytes don't get flushed, well, it's only a hint anyway.
622 */
623
624 /* fetch pagesize only once */
625 if (pagesize == 0)
627
628 /* align length to pagesize, dropping any fractional page */
629 if (pagesize > 0)
630 nbytes = (nbytes / pagesize) * pagesize;
631
632 /* fractional-page request is a no-op */
633 if (nbytes <= 0)
634 return;
635
636 /*
637 * mmap could well fail, particularly on 32-bit platforms where there
638 * may simply not be enough address space. If so, silently fall
639 * through to the next implementation.
640 */
641 if (nbytes <= (pgoff_t) SSIZE_MAX)
642 p = mmap(NULL, nbytes, PROT_READ, MAP_SHARED, fd, offset);
643 else
644 p = MAP_FAILED;
645
646 if (p != MAP_FAILED)
647 {
648 int rc;
649
650 rc = msync(p, (size_t) nbytes, MS_ASYNC);
651 if (rc != 0)
652 {
655 errmsg("could not flush dirty data: %m")));
656 /* NB: need to fall through to munmap()! */
657 }
658
659 rc = munmap(p, (size_t) nbytes);
660 if (rc != 0)
661 {
662 /* FATAL error because mapping would remain */
665 errmsg("could not munmap() while flushing data: %m")));
666 }
667
668 return;
669 }
670 }
671#endif
672#if defined(USE_POSIX_FADVISE) && defined(POSIX_FADV_DONTNEED)
673 {
674 int rc;
675
676 /*
677 * Signal the kernel that the passed in range should not be cached
678 * anymore. This has the, desired, side effect of writing out dirty
679 * data, and the, undesired, side effect of likely discarding useful
680 * clean cached blocks. For the latter reason this is the least
681 * preferable method.
682 */
683
684 rc = posix_fadvise(fd, offset, nbytes, POSIX_FADV_DONTNEED);
685
686 if (rc != 0)
687 {
688 /* don't error out, this is just a performance optimization */
691 errmsg("could not flush dirty data: %m")));
692 }
693
694 return;
695 }
696#endif
697}
#define MAP_FAILED
Definition mem.h:43

References data_sync_elevel(), EINTR, enableFsync, ereport, errcode_for_file_access(), errmsg(), FATAL, fb(), fd(), MAP_FAILED, and WARNING.

Referenced by copy_file(), and FileWriteback().

◆ pg_fsync()

int pg_fsync ( int  fd)
extern

Definition at line 389 of file fd.c.

390{
391#if !defined(WIN32) && defined(USE_ASSERT_CHECKING)
392 struct stat st;
393
394 /*
395 * Some operating system implementations of fsync() have requirements
396 * about the file access modes that were used when their file descriptor
397 * argument was opened, and these requirements differ depending on whether
398 * the file descriptor is for a directory.
399 *
400 * For any file descriptor that may eventually be handed to fsync(), we
401 * should have opened it with access modes that are compatible with
402 * fsync() on all supported systems, otherwise the code may not be
403 * portable, even if it runs ok on the current system.
404 *
405 * We assert here that a descriptor for a file was opened with write
406 * permissions (i.e., not O_RDONLY) and for a directory without write
407 * permissions (O_RDONLY). Notice that the assertion check is made even
408 * if fsync() is disabled.
409 *
410 * If fstat() fails, ignore it and let the follow-up fsync() complain.
411 */
412 if (fstat(fd, &st) == 0)
413 {
414 int desc_flags = fcntl(fd, F_GETFL);
415
417
418 if (S_ISDIR(st.st_mode))
420 else
422 }
423 errno = 0;
424#endif
425
426 /* #if is to skip the wal_sync_method test if there's no need for it */
427#if defined(HAVE_FSYNC_WRITETHROUGH)
430 else
431#endif
433}
int pg_fsync_no_writethrough(int fd)
Definition fd.c:441
int pg_fsync_writethrough(int fd)
Definition fd.c:461
#define fstat
Definition win32_port.h:73
int wal_sync_method
Definition xlog.c:133
@ WAL_SYNC_METHOD_FSYNC_WRITETHROUGH
Definition xlog.h:28

References Assert, fb(), fd(), fstat, pg_fsync_no_writethrough(), pg_fsync_writethrough(), S_ISDIR, stat::st_mode, wal_sync_method, and WAL_SYNC_METHOD_FSYNC_WRITETHROUGH.

Referenced by AddToDataDirLockFile(), assign_wal_sync_method(), BootStrapXLOG(), CheckPointLogicalRewriteHeap(), CreateDirAndVersionFile(), CreateLockFile(), durable_rename(), FileSync(), fsync_fname_ext(), heap_xlog_logical_rewrite(), readRecoverySignalFile(), RecreateTwoPhaseFile(), RestoreSlotFromDisk(), SaveSlotToPath(), SlruPhysicalWritePage(), SlruSyncFileTag(), SnapBuildSerialize(), update_controlfile(), write_auto_conf_file(), WriteControlFile(), writeTimeLineHistory(), writeTimeLineHistoryFile(), XLogFileCopy(), and XLogFileInitInternal().

◆ pg_fsync_no_writethrough()

int pg_fsync_no_writethrough ( int  fd)
extern

Definition at line 441 of file fd.c.

442{
443 int rc;
444
445 if (!enableFsync)
446 return 0;
447
448retry:
449 rc = fsync(fd);
450
451 if (rc == -1 && errno == EINTR)
452 goto retry;
453
454 return rc;
455}
#define fsync(fd)
Definition win32_port.h:83

References EINTR, enableFsync, fb(), fd(), and fsync.

Referenced by issue_xlog_fsync(), and pg_fsync().

◆ pg_fsync_writethrough()

int pg_fsync_writethrough ( int  fd)
extern

Definition at line 461 of file fd.c.

462{
463 if (enableFsync)
464 {
465#if defined(F_FULLFSYNC)
466 return (fcntl(fd, F_FULLFSYNC, 0) == -1) ? -1 : 0;
467#else
468 errno = ENOSYS;
469 return -1;
470#endif
471 }
472 else
473 return 0;
474}

References enableFsync, fb(), and fd().

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

◆ pg_truncate()

int pg_truncate ( const char path,
pgoff_t  length 
)
extern

Definition at line 720 of file fd.c.

721{
722 int ret;
723#ifdef WIN32
724 int save_errno;
725 int fd;
726
728 if (fd >= 0)
729 {
730 ret = pg_ftruncate(fd, length);
734 }
735 else
736 ret = -1;
737#else
738
739retry:
740 ret = truncate(path, length);
741
742 if (ret == -1 && errno == EINTR)
743 goto retry;
744#endif
745
746 return ret;
747}

References CloseTransientFile(), EINTR, fb(), fd(), OpenTransientFile(), PG_BINARY, and pg_ftruncate().

Referenced by do_truncate().

◆ ReadDir()

◆ ReadDirExtended()

struct dirent * ReadDirExtended ( DIR dir,
const char dirname,
int  elevel 
)
extern

Definition at line 2971 of file fd.c.

2972{
2973 struct dirent *dent;
2974
2975 /* Give a generic message for AllocateDir failure, if caller didn't */
2976 if (dir == NULL)
2977 {
2978 ereport(elevel,
2980 errmsg("could not open directory \"%s\": %m",
2981 dirname)));
2982 return NULL;
2983 }
2984
2985 errno = 0;
2986 if ((dent = readdir(dir)) != NULL)
2987 return dent;
2988
2989 if (errno)
2990 ereport(elevel,
2992 errmsg("could not read directory \"%s\": %m",
2993 dirname)));
2994 return NULL;
2995}
struct dirent * readdir(DIR *)
Definition dirent.c:78

References ereport, errcode_for_file_access(), errmsg(), fb(), and readdir().

Referenced by DeleteAllExportedSnapshotFiles(), ReadDir(), RelationCacheInitFileRemove(), RelationCacheInitFileRemoveInDir(), RemovePgTempFiles(), RemovePgTempFilesInDir(), RemovePgTempRelationFiles(), RemovePgTempRelationFilesInDbspace(), ReorderBufferCleanupSerializedTXNs(), scan_directory_ci(), SyncDataDirectory(), and walkdir().

◆ ReleaseExternalFD()

◆ RemovePgTempFiles()

void RemovePgTempFiles ( void  )
extern

Definition at line 3322 of file fd.c.

3323{
3325 DIR *spc_dir;
3326 struct dirent *spc_de;
3327
3328 /*
3329 * First process temp files in pg_default ($PGDATA/base)
3330 */
3331 snprintf(temp_path, sizeof(temp_path), "base/%s", PG_TEMP_FILES_DIR);
3332 RemovePgTempFilesInDir(temp_path, true, false);
3334
3335 /*
3336 * Cycle through temp directories for all non-default tablespaces.
3337 */
3339
3341 {
3342 if (strcmp(spc_de->d_name, ".") == 0 ||
3343 strcmp(spc_de->d_name, "..") == 0)
3344 continue;
3345
3346 snprintf(temp_path, sizeof(temp_path), "%s/%s/%s/%s",
3349 RemovePgTempFilesInDir(temp_path, true, false);
3350
3351 snprintf(temp_path, sizeof(temp_path), "%s/%s/%s",
3354 }
3355
3357
3358 /*
3359 * In EXEC_BACKEND case there is a pgsql_tmp directory at the top level of
3360 * DataDir as well. However, that is *not* cleaned here because doing so
3361 * would create a race condition. It's done separately, earlier in
3362 * postmaster startup.
3363 */
3364}
int FreeDir(DIR *dir)
Definition fd.c:3008
static void RemovePgTempRelationFiles(const char *tsdirname)
Definition fd.c:3442
void RemovePgTempFilesInDir(const char *tmpdirname, bool missing_ok, bool unlink_all)
Definition fd.c:3382
DIR * AllocateDir(const char *dirname)
Definition fd.c:2890
#define PG_TEMP_FILES_DIR
Definition file_utils.h:63
#define MAXPGPATH
#define snprintf
Definition port.h:260
#define PG_TBLSPC_DIR
Definition relpath.h:41
#define TABLESPACE_VERSION_DIRECTORY
Definition relpath.h:33

References AllocateDir(), fb(), FreeDir(), LOG, MAXPGPATH, PG_TBLSPC_DIR, PG_TEMP_FILES_DIR, ReadDirExtended(), RemovePgTempFilesInDir(), RemovePgTempRelationFiles(), snprintf, and TABLESPACE_VERSION_DIRECTORY.

Referenced by PostmasterMain(), and PostmasterStateMachine().

◆ RemovePgTempFilesInDir()

void RemovePgTempFilesInDir ( const char tmpdirname,
bool  missing_ok,
bool  unlink_all 
)
extern

Definition at line 3382 of file fd.c.

3383{
3384 DIR *temp_dir;
3385 struct dirent *temp_de;
3386 char rm_path[MAXPGPATH * 2];
3387
3389
3390 if (temp_dir == NULL && errno == ENOENT && missing_ok)
3391 return;
3392
3394 {
3395 if (strcmp(temp_de->d_name, ".") == 0 ||
3396 strcmp(temp_de->d_name, "..") == 0)
3397 continue;
3398
3399 snprintf(rm_path, sizeof(rm_path), "%s/%s",
3400 tmpdirname, temp_de->d_name);
3401
3402 if (unlink_all ||
3403 strncmp(temp_de->d_name,
3406 {
3408
3409 if (type == PGFILETYPE_ERROR)
3410 continue;
3411 else if (type == PGFILETYPE_DIR)
3412 {
3413 /* recursively remove contents, then directory itself */
3414 RemovePgTempFilesInDir(rm_path, false, true);
3415
3416 if (rmdir(rm_path) < 0)
3417 ereport(LOG,
3419 errmsg("could not remove directory \"%s\": %m",
3420 rm_path)));
3421 }
3422 else
3423 {
3424 if (unlink(rm_path) < 0)
3425 ereport(LOG,
3427 errmsg("could not remove file \"%s\": %m",
3428 rm_path)));
3429 }
3430 }
3431 else
3432 ereport(LOG,
3433 (errmsg("unexpected file found in temporary-files directory: \"%s\"",
3434 rm_path)));
3435 }
3436
3438}
PGFileType get_dirent_type(const char *path, const struct dirent *de, bool look_through_symlinks, int elevel)
Definition file_utils.c:547
#define PG_TEMP_FILE_PREFIX
Definition file_utils.h:64
PGFileType
Definition file_utils.h:19
@ PGFILETYPE_DIR
Definition file_utils.h:23
@ PGFILETYPE_ERROR
Definition file_utils.h:20
const char * type

References AllocateDir(), ereport, errcode_for_file_access(), errmsg(), fb(), FreeDir(), get_dirent_type(), LOG, MAXPGPATH, PG_TEMP_FILE_PREFIX, PGFILETYPE_DIR, PGFILETYPE_ERROR, ReadDirExtended(), RemovePgTempFilesInDir(), snprintf, and type.

Referenced by PostmasterMain(), RemovePgTempFiles(), and RemovePgTempFilesInDir().

◆ ReserveExternalFD()

void ReserveExternalFD ( void  )
extern

Definition at line 1206 of file fd.c.

1207{
1208 /*
1209 * Release VFDs if needed to stay safe. Because we do this before
1210 * incrementing numExternalFDs, the final state will be as desired, i.e.,
1211 * nfile + numAllocatedDescs + numExternalFDs <= max_safe_fds.
1212 */
1214
1216}

References numExternalFDs, and ReleaseLruFiles().

Referenced by AcquireExternalFD(), BackendInitialize(), dsm_impl_posix(), InitializeWaitEventSupport(), InitPostmasterDeathWatchHandle(), and XLogWrite().

◆ set_max_safe_fds()

void set_max_safe_fds ( void  )
extern

Definition at line 1044 of file fd.c.

1045{
1046 int usable_fds;
1047 int already_open;
1048
1049 /*----------
1050 * We want to set max_safe_fds to
1051 * MIN(usable_fds, max_files_per_process)
1052 * less the slop factor for files that are opened without consulting
1053 * fd.c. This ensures that we won't allow to open more than
1054 * max_files_per_process, or the experimentally-determined EMFILE limit,
1055 * additional files.
1056 *----------
1057 */
1060
1062
1063 /*
1064 * Take off the FDs reserved for system() etc.
1065 */
1067
1068 /*
1069 * Make sure we still have enough to get by.
1070 */
1072 ereport(FATAL,
1074 errmsg("insufficient file descriptors available to start server process"),
1075 errdetail("System allows %d, server needs at least %d, %d files are already open.",
1078 already_open)));
1079
1080 elog(DEBUG2, "max_safe_fds = %d, usable_fds = %d, already_open = %d",
1082}
#define Min(x, y)
Definition c.h:997
int errdetail(const char *fmt,...)
Definition elog.c:1216
#define DEBUG2
Definition elog.h:29
int max_files_per_process
Definition fd.c:146
#define FD_MINFREE
Definition fd.c:138
static void count_usable_fds(int max_to_probe, int *usable_fds, int *already_open)
Definition fd.c:964
#define NUM_RESERVED_FDS
Definition fd.c:129

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

Referenced by BootstrapModeMain(), PostgresSingleUserMain(), and PostmasterMain().

◆ SetTempTablespaces()

void SetTempTablespaces ( Oid tableSpaces,
int  numSpaces 
)
extern

Definition at line 3096 of file fd.c.

3097{
3098 Assert(numSpaces >= 0);
3101
3102 /*
3103 * Select a random starting point in the list. This is to minimize
3104 * conflicts between backends that are most likely sharing the same list
3105 * of temp tablespaces. Note that if we create multiple temp files in the
3106 * same transaction, we'll advance circularly through the list --- this
3107 * ensures that large temporary sort files are nicely spread across all
3108 * available tablespaces.
3109 */
3110 if (numSpaces > 1)
3112 0, numSpaces - 1);
3113 else
3115}
uint64 pg_prng_uint64_range(pg_prng_state *state, uint64 rmin, uint64 rmax)
Definition pg_prng.c:144
pg_prng_state pg_global_prng_state
Definition pg_prng.c:34

References Assert, fb(), nextTempTableSpace, numTempTableSpaces, pg_global_prng_state, pg_prng_uint64_range(), and tempTableSpaces.

Referenced by assign_temp_tablespaces(), and PrepareTempTablespaces().

◆ SyncDataDirectory()

void SyncDataDirectory ( void  )
extern

Definition at line 3593 of file fd.c.

3594{
3595 bool xlog_is_symlink;
3596
3597 /* We can skip this whole thing if fsync is disabled. */
3598 if (!enableFsync)
3599 return;
3600
3601 /*
3602 * If pg_wal is a symlink, we'll need to recurse into it separately,
3603 * because the first walkdir below will ignore it.
3604 */
3605 xlog_is_symlink = false;
3606
3607 {
3608 struct stat st;
3609
3610 if (lstat("pg_wal", &st) < 0)
3611 ereport(LOG,
3613 errmsg("could not stat file \"%s\": %m",
3614 "pg_wal")));
3615 else if (S_ISLNK(st.st_mode))
3616 xlog_is_symlink = true;
3617 }
3618
3619#ifdef HAVE_SYNCFS
3621 {
3622 DIR *dir;
3623 struct dirent *de;
3624
3625 /*
3626 * On Linux, we don't have to open every single file one by one. We
3627 * can use syncfs() to sync whole filesystems. We only expect
3628 * filesystem boundaries to exist where we tolerate symlinks, namely
3629 * pg_wal and the tablespaces, so we call syncfs() for each of those
3630 * directories.
3631 */
3632
3633 /* Prepare to report progress syncing the data directory via syncfs. */
3635
3636 /* Sync the top level pgdata directory. */
3637 do_syncfs(".");
3638 /* If any tablespaces are configured, sync each of those. */
3640 while ((de = ReadDirExtended(dir, PG_TBLSPC_DIR, LOG)))
3641 {
3642 char path[MAXPGPATH];
3643
3644 if (strcmp(de->d_name, ".") == 0 || strcmp(de->d_name, "..") == 0)
3645 continue;
3646
3647 snprintf(path, MAXPGPATH, "%s/%s", PG_TBLSPC_DIR, de->d_name);
3648 do_syncfs(path);
3649 }
3650 FreeDir(dir);
3651 /* If pg_wal is a symlink, process that too. */
3652 if (xlog_is_symlink)
3653 do_syncfs("pg_wal");
3654 return;
3655 }
3656#endif /* !HAVE_SYNCFS */
3657
3658#ifdef PG_FLUSH_DATA_WORKS
3659 /* Prepare to report progress of the pre-fsync phase. */
3661
3662 /*
3663 * If possible, hint to the kernel that we're soon going to fsync the data
3664 * directory and its contents. Errors in this step are even less
3665 * interesting than normal, so log them only at DEBUG1.
3666 */
3667 walkdir(".", pre_sync_fname, false, DEBUG1);
3668 if (xlog_is_symlink)
3669 walkdir("pg_wal", pre_sync_fname, false, DEBUG1);
3671#endif
3672
3673 /* Prepare to report progress syncing the data directory via fsync. */
3675
3676 /*
3677 * Now we do the fsync()s in the same order.
3678 *
3679 * The main call ignores symlinks, so in addition to specially processing
3680 * pg_wal if it's a symlink, pg_tblspc has to be visited separately with
3681 * process_symlinks = true. Note that if there are any plain directories
3682 * in pg_tblspc, they'll get fsync'd twice. That's not an expected case
3683 * so we don't worry about optimizing it.
3684 */
3685 walkdir(".", datadir_fsync_fname, false, LOG);
3686 if (xlog_is_symlink)
3687 walkdir("pg_wal", datadir_fsync_fname, false, LOG);
3689}
void begin_startup_progress_phase(void)
Definition startup.c:342
#define DEBUG1
Definition elog.h:30
int recovery_init_sync_method
Definition fd.c:165
static void datadir_fsync_fname(const char *fname, bool isdir, int elevel)
Definition fd.c:3808
@ DATA_DIR_SYNC_METHOD_SYNCFS
Definition file_utils.h:30
#define lstat(path, sb)
Definition win32_port.h:275
#define S_ISLNK(m)
Definition win32_port.h:334

References AllocateDir(), begin_startup_progress_phase(), DATA_DIR_SYNC_METHOD_SYNCFS, datadir_fsync_fname(), DEBUG1, enableFsync, ereport, errcode_for_file_access(), errmsg(), fb(), FreeDir(), LOG, lstat, MAXPGPATH, PG_TBLSPC_DIR, ReadDirExtended(), recovery_init_sync_method, S_ISLNK, snprintf, stat::st_mode, and walkdir().

Referenced by StartupXLOG().

◆ TempTablespacePath()

void TempTablespacePath ( char path,
Oid  tablespace 
)
extern

Definition at line 1766 of file fd.c.

1767{
1768 /*
1769 * Identify the tempfile directory for this tablespace.
1770 *
1771 * If someone tries to specify pg_global, use pg_default instead.
1772 */
1773 if (tablespace == InvalidOid ||
1776 snprintf(path, MAXPGPATH, "base/%s", PG_TEMP_FILES_DIR);
1777 else
1778 {
1779 /* All other tablespaces are accessed via symlinks */
1780 snprintf(path, MAXPGPATH, "%s/%u/%s/%s",
1783 }
1784}
static char * tablespace
Definition pgbench.c:217

References fb(), InvalidOid, MAXPGPATH, PG_TBLSPC_DIR, PG_TEMP_FILES_DIR, snprintf, tablespace, and TABLESPACE_VERSION_DIRECTORY.

Referenced by FileSetCreate(), FileSetPath(), OpenTemporaryFileInTablespace(), and pg_ls_tmpdir().

◆ TempTablespacesAreSet()

bool TempTablespacesAreSet ( void  )
extern

Definition at line 3125 of file fd.c.

3126{
3127 return (numTempTableSpaces >= 0);
3128}

References numTempTableSpaces.

Referenced by GetTempTablespaces(), and PrepareTempTablespaces().

Variable Documentation

◆ data_sync_retry

PGDLLIMPORT bool data_sync_retry
extern

Definition at line 162 of file fd.c.

Referenced by data_sync_elevel().

◆ file_extend_method

PGDLLIMPORT int file_extend_method
extern

Definition at line 168 of file fd.c.

Referenced by mdzeroextend().

◆ io_direct_flags

◆ max_files_per_process

PGDLLIMPORT int max_files_per_process
extern

Definition at line 146 of file fd.c.

Referenced by set_max_safe_fds().

◆ max_safe_fds

PGDLLIMPORT int max_safe_fds
extern

Definition at line 159 of file fd.c.

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

◆ recovery_init_sync_method

PGDLLIMPORT int recovery_init_sync_method
extern

Definition at line 165 of file fd.c.

Referenced by SyncDataDirectory().