Coverage Report

Created: 2026-11-12 07:20

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