LCOV - differential code coverage report
Current view: top level - src/backend/storage/file - fd.c (source / functions) Coverage Total Hit UNC LBC UBC GBC GNC CBC DUB DCB
Current: Differential Code Coverage 16@8cea358b128 vs 17@8cea358b128 Lines: 72.4 % 1020 738 9 273 11 28 699 5 10
Current Date: 2024-04-14 14:21:10 Functions: 90.8 % 98 89 1 8 1 11 77 2
Baseline: 16@8cea358b128 Branches: 44.6 % 854 381 15 4 454 13 7 361
Baseline Date: 2024-04-14 14:21:09 Line coverage date bins:
Legend: Lines: hit not hit | Branches: + taken - not taken # not executed (60,120] days: 66.7 % 9 6 3 6
(120,180] days: 81.5 % 27 22 5 22
(180,240] days: 66.7 % 3 2 1 2
(240..) days: 72.2 % 981 708 273 11 697
Function coverage date bins:
(60,120] days: 100.0 % 1 1 1
(120,180] days: 83.3 % 6 5 1 5
(180,240] days: 100.0 % 2 2 1 1
(240..) days: 91.0 % 89 81 8 1 4 76
Branch coverage date bins:
(60,120] days: 33.3 % 12 4 8 4
(120,180] days: 37.5 % 8 3 5 3
(180,240] days: 0.0 % 2 0 2
(240..) days: 45.0 % 832 374 4 454 13 361

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

Generated by: LCOV version 2.1-beta2-3-g6141622