Branch data Line data Source code
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 : : #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 : : ((void) 0)
186 : : #endif
187 : :
188 : : #define VFD_CLOSED (-1)
189 : :
190 : : #define FileIsValid(file) \
191 : : ((file) > 0 && (file) < (int) SizeVfdCache && VfdCache[file].fileName != NULL)
192 : :
193 : : #define FileIsNotOpen(file) (VfdCache[file].fd == VFD_CLOSED)
194 : :
195 : : /* these are the assigned bits in fdstate below: */
196 : : #define FD_DELETE_AT_CLOSE (1 << 0) /* T = delete when closed */
197 : : #define FD_CLOSE_AT_EOXACT (1 << 1) /* T = close at eoXact */
198 : : #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 : 6422 : ResourceOwnerRememberFile(ResourceOwner owner, File file)
377 : : {
378 : 6422 : ResourceOwnerRemember(owner, Int32GetDatum(file), &file_resowner_desc);
379 : 6422 : }
380 : : static inline void
381 : 6417 : ResourceOwnerForgetFile(ResourceOwner owner, File file)
382 : : {
383 : 6417 : ResourceOwnerForget(owner, Int32GetDatum(file), &file_resowner_desc);
384 : 6417 : }
385 : :
386 : : /*
387 : : * pg_fsync --- do fsync with or without writethrough
388 : : */
389 : : int
390 : 77241 : pg_fsync(int fd)
391 : : {
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 : 77241 : return pg_fsync_no_writethrough(fd);
434 : : }
435 : :
436 : :
437 : : /*
438 : : * pg_fsync_no_writethrough --- same as fsync except does nothing if
439 : : * enableFsync is off
440 : : */
441 : : int
442 : 77241 : pg_fsync_no_writethrough(int fd)
443 : : {
444 : : int rc;
445 : :
446 [ - + ]: 77241 : if (!enableFsync)
447 : 77241 : 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 : : }
457 : :
458 : : /*
459 : : * pg_fsync_writethrough
460 : : */
461 : : int
462 : 0 : pg_fsync_writethrough(int fd)
463 : : {
464 [ # # ]: 0 : if (enableFsync)
465 : : {
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 : : #endif
472 : : }
473 : : else
474 : 0 : return 0;
475 : : }
476 : :
477 : : /*
478 : : * pg_fdatasync --- same as fdatasync except does nothing if enableFsync is off
479 : : */
480 : : int
481 : 0 : pg_fdatasync(int fd)
482 : : {
483 : : 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 : : }
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 : 24986 : pg_file_exists(const char *name)
505 : : {
506 : : struct stat st;
507 : :
508 : : Assert(name != NULL);
509 : :
510 [ + + ]: 24986 : if (stat(name, &st) == 0)
511 : 13080 : return !S_ISDIR(st.st_mode);
512 [ - + - - : 11906 : else if (!(errno == ENOENT || errno == ENOTDIR || errno == EACCES))
- - ]
513 [ # # ]: 0 : ereport(ERROR,
514 : : (errcode_for_file_access(),
515 : : errmsg("could not access file \"%s\": %m", name)));
516 : :
517 : 11906 : return false;
518 : : }
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 : 43509 : 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 [ + - ]: 43509 : if (!enableFsync)
535 : 43509 : 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 [ # # ]: 0 : if (not_implemented_by_kernel)
547 : 0 : return;
548 : :
549 : 0 : 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 : 0 : rc = sync_file_range(fd, offset, nbytes,
561 : : SYNC_FILE_RANGE_WRITE);
562 [ # # ]: 0 : if (rc != 0)
563 : : {
564 : : int elevel;
565 : :
566 [ # # ]: 0 : if (errno == EINTR)
567 : 0 : 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 [ # # ]: 0 : if (errno == ENOSYS)
575 : : {
576 : 0 : elevel = WARNING;
577 : 0 : not_implemented_by_kernel = true;
578 : : }
579 : : else
580 : 0 : elevel = data_sync_elevel(WARNING);
581 : :
582 [ # # ]: 0 : ereport(elevel,
583 : : (errcode_for_file_access(),
584 : : errmsg("could not flush dirty data: %m")));
585 : : }
586 : :
587 : 0 : 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 : 734 : pg_ftruncate(int fd, pgoff_t length)
708 : : {
709 : : int ret;
710 : :
711 : 734 : retry:
712 : 734 : ret = ftruncate(fd, length);
713 : :
714 [ - + - - ]: 734 : if (ret == -1 && errno == EINTR)
715 : 0 : goto retry;
716 : :
717 : 734 : return ret;
718 : : }
719 : :
720 : : /*
721 : : * Truncate a file to a given length by name.
722 : : */
723 : : int
724 : 281018 : pg_truncate(const char *path, pgoff_t length)
725 : : {
726 : : 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 : 281018 : retry:
744 : 281018 : ret = truncate(path, length);
745 : :
746 [ + + - + ]: 281018 : if (ret == -1 && errno == EINTR)
747 : 0 : goto retry;
748 : : #endif
749 : :
750 : 281018 : return ret;
751 : : }
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 : 25492 : fsync_fname(const char *fname, bool isdir)
761 : : {
762 : 25492 : fsync_fname_ext(fname, isdir, false, data_sync_elevel(ERROR));
763 : 25492 : }
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 : 7399 : durable_rename(const char *oldfile, const char *newfile, int elevel)
787 : : {
788 : : 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 [ - + ]: 7399 : if (fsync_fname_ext(oldfile, false, false, elevel) != 0)
798 : 0 : return -1;
799 : :
800 : 7399 : fd = OpenTransientFile(newfile, PG_BINARY | O_RDWR);
801 [ + + ]: 7399 : if (fd < 0)
802 : : {
803 [ - + ]: 5080 : if (errno != ENOENT)
804 : : {
805 [ # # ]: 0 : ereport(elevel,
806 : : (errcode_for_file_access(),
807 : : errmsg("could not open file \"%s\": %m", newfile)));
808 : 0 : return -1;
809 : : }
810 : : }
811 : : else
812 : : {
813 [ - + ]: 2319 : if (pg_fsync(fd) != 0)
814 : : {
815 : : 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 : : (errcode_for_file_access(),
824 : : errmsg("could not fsync file \"%s\": %m", newfile)));
825 : 0 : return -1;
826 : : }
827 : :
828 [ - + ]: 2319 : if (CloseTransientFile(fd) != 0)
829 : : {
830 [ # # ]: 0 : ereport(elevel,
831 : : (errcode_for_file_access(),
832 : : errmsg("could not close file \"%s\": %m", newfile)));
833 : 0 : return -1;
834 : : }
835 : : }
836 : :
837 : : /* Time to do the real deal... */
838 [ - + ]: 7399 : if (rename(oldfile, newfile) < 0)
839 : : {
840 [ # # ]: 0 : ereport(elevel,
841 : : (errcode_for_file_access(),
842 : : errmsg("could not rename file \"%s\" to \"%s\": %m",
843 : : oldfile, newfile)));
844 : 0 : return -1;
845 : : }
846 : :
847 : : /*
848 : : * To guarantee renaming the file is persistent, fsync the file with its
849 : : * new name, and its containing directory.
850 : : */
851 [ - + ]: 7399 : if (fsync_fname_ext(newfile, false, false, elevel) != 0)
852 : 0 : return -1;
853 : :
854 [ - + ]: 7399 : if (fsync_parent_path(newfile, elevel) != 0)
855 : 0 : return -1;
856 : :
857 : 7399 : return 0;
858 : : }
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 : 1351 : durable_unlink(const char *fname, int elevel)
877 : : {
878 [ + + ]: 1351 : if (unlink(fname) < 0)
879 : : {
880 [ + + ]: 57 : ereport(elevel,
881 : : (errcode_for_file_access(),
882 : : errmsg("could not remove file \"%s\": %m",
883 : : fname)));
884 : 57 : return -1;
885 : : }
886 : :
887 : : /*
888 : : * To guarantee that the removal of the file is persistent, fsync its
889 : : * parent directory.
890 : : */
891 [ - + ]: 1294 : if (fsync_parent_path(fname, elevel) != 0)
892 : 0 : return -1;
893 : :
894 : 1294 : return 0;
895 : : }
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 : 26330 : InitFileAccess(void)
908 : : {
909 : : Assert(SizeVfdCache == 0); /* call me only once */
910 : :
911 : : /* initialize cache header entry */
912 : 26330 : VfdCache = (Vfd *) malloc(sizeof(Vfd));
913 [ - + ]: 26330 : if (VfdCache == NULL)
914 [ # # ]: 0 : ereport(FATAL,
915 : : (errcode(ERRCODE_OUT_OF_MEMORY),
916 : : errmsg("out of memory")));
917 : :
918 [ + - + - : 210640 : MemSet(&(VfdCache[0]), 0, sizeof(Vfd));
+ - + - +
+ ]
919 : 26330 : VfdCache->fd = VFD_CLOSED;
920 : :
921 : 26330 : SizeVfdCache = 1;
922 : 26330 : }
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 : 26330 : InitTemporaryFileAccess(void)
938 : : {
939 : : Assert(SizeVfdCache != 0); /* InitFileAccess() needs to have run */
940 : : 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 : 26330 : before_shmem_exit(BeforeShmemExit_Files, 0);
947 : :
948 : : #ifdef USE_ASSERT_CHECKING
949 : : temporary_files_allowed = true;
950 : : #endif
951 : 26330 : }
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 : 1325 : count_usable_fds(int max_to_probe, int *usable_fds, int *already_open)
969 : : {
970 : : int *fd;
971 : : int size;
972 : 1325 : int used = 0;
973 : 1325 : int highestfd = 0;
974 : : int j;
975 : :
976 : : #ifdef HAVE_GETRLIMIT
977 : : struct rlimit rlim;
978 : : int getrlimit_status;
979 : : #endif
980 : :
981 : 1325 : size = 1024;
982 : 1325 : fd = palloc_array(int, size);
983 : :
984 : : #ifdef HAVE_GETRLIMIT
985 : 1325 : getrlimit_status = getrlimit(RLIMIT_NOFILE, &rlim);
986 [ - + ]: 1325 : if (getrlimit_status != 0)
987 [ # # ]: 0 : ereport(WARNING, (errmsg("getrlimit failed: %m")));
988 : : #endif /* HAVE_GETRLIMIT */
989 : :
990 : : /* dup until failure or probe limit reached */
991 : : for (;;)
992 : 1323675 : {
993 : : int thisfd;
994 : :
995 : : #ifdef HAVE_GETRLIMIT
996 : :
997 : : /*
998 : : * don't go beyond RLIMIT_NOFILE; causes irritating kernel logs on
999 : : * some platforms
1000 : : */
1001 [ + - - + ]: 1325000 : if (getrlimit_status == 0 && highestfd >= rlim.rlim_cur - 1)
1002 : 0 : break;
1003 : : #endif
1004 : :
1005 : 1325000 : thisfd = dup(2);
1006 [ - + ]: 1325000 : if (thisfd < 0)
1007 : : {
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 : : }
1013 : :
1014 [ - + ]: 1325000 : if (used >= size)
1015 : : {
1016 : 0 : size *= 2;
1017 : 0 : fd = repalloc_array(fd, int, size);
1018 : : }
1019 : 1325000 : fd[used++] = thisfd;
1020 : :
1021 [ + - ]: 1325000 : if (highestfd < thisfd)
1022 : 1325000 : highestfd = thisfd;
1023 : :
1024 [ + + ]: 1325000 : if (used >= max_to_probe)
1025 : 1325 : break;
1026 : : }
1027 : :
1028 : : /* release the files we opened */
1029 [ + + ]: 1326325 : for (j = 0; j < used; j++)
1030 : 1325000 : close(fd[j]);
1031 : :
1032 : 1325 : 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 : 1325 : *usable_fds = used;
1040 : 1325 : *already_open = highestfd + 1 - used;
1041 : 1325 : }
1042 : :
1043 : : /*
1044 : : * set_max_safe_fds
1045 : : * Determine number of file descriptors that fd.c is allowed to use
1046 : : */
1047 : : void
1048 : 1325 : 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 : 1325 : count_usable_fds(max_files_per_process,
1063 : : &usable_fds, &already_open);
1064 : :
1065 : 1325 : max_safe_fds = Min(usable_fds, max_files_per_process);
1066 : :
1067 : : /*
1068 : : * Take off the FDs reserved for system() etc.
1069 : : */
1070 : 1325 : max_safe_fds -= NUM_RESERVED_FDS;
1071 : :
1072 : : /*
1073 : : * Make sure we still have enough to get by.
1074 : : */
1075 [ - + ]: 1325 : if (max_safe_fds < FD_MINFREE)
1076 [ # # ]: 0 : 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 [ + + ]: 1325 : elog(DEBUG2, "max_safe_fds = %d, usable_fds = %d, already_open = %d",
1085 : : max_safe_fds, usable_fds, already_open);
1086 : 1325 : }
1087 : :
1088 : : /*
1089 : : * Open a file with BasicOpenFilePerm() and pass default file mode for the
1090 : : * fileMode parameter.
1091 : : */
1092 : : int
1093 : 47837 : BasicOpenFile(const char *fileName, int fileFlags)
1094 : : {
1095 : 47837 : return BasicOpenFilePerm(fileName, fileFlags, pg_file_create_mode);
1096 : : }
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 : 9679434 : BasicOpenFilePerm(const char *fileName, int fileFlags, mode_t fileMode)
1116 : : {
1117 : : int fd;
1118 : :
1119 : 9679434 : tryAgain:
1120 : : #ifdef PG_O_DIRECT_USE_F_NOCACHE
1121 : : fd = open(fileName, fileFlags & ~PG_O_DIRECT, fileMode);
1122 : : #else
1123 : 9679434 : fd = open(fileName, fileFlags, fileMode);
1124 : : #endif
1125 : :
1126 [ + + ]: 9679434 : if (fd >= 0)
1127 : : {
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 : 9146614 : return fd; /* success! */
1143 : : }
1144 : :
1145 [ + - - + ]: 532820 : if (errno == EMFILE || errno == ENFILE)
1146 : : {
1147 : 0 : int save_errno = errno;
1148 : :
1149 [ # # ]: 0 : ereport(LOG,
1150 : : (errcode(ERRCODE_INSUFFICIENT_RESOURCES),
1151 : : 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 : : }
1157 : :
1158 : 532820 : return -1; /* failure */
1159 : : }
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 : 152432 : AcquireExternalFD(void)
1176 : : {
1177 : : /*
1178 : : * We don't want more than max_safe_fds / 3 FDs to be consumed for
1179 : : * "external" FDs.
1180 : : */
1181 [ + - ]: 152432 : if (numExternalFDs < max_safe_fds / 3)
1182 : : {
1183 : 152432 : ReserveExternalFD();
1184 : 152432 : return true;
1185 : : }
1186 : 0 : errno = EMFILE;
1187 : 0 : return false;
1188 : : }
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 : 247806 : ReserveExternalFD(void)
1211 : : {
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 : 247806 : ReleaseLruFiles();
1218 : :
1219 : 247806 : numExternalFDs++;
1220 : 247806 : }
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 : 224643 : ReleaseExternalFD(void)
1229 : : {
1230 : : Assert(numExternalFDs > 0);
1231 : 224643 : numExternalFDs--;
1232 : 224643 : }
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 : 1563108 : Delete(File file)
1258 : : {
1259 : : Vfd *vfdP;
1260 : :
1261 : : Assert(file != 0);
1262 : :
1263 : : DO_DB(elog(LOG, "Delete %d (%s)",
1264 : : file, VfdCache[file].fileName));
1265 : : DO_DB(_dump_lru());
1266 : :
1267 : 1563108 : vfdP = &VfdCache[file];
1268 : :
1269 : 1563108 : VfdCache[vfdP->lruLessRecently].lruMoreRecently = vfdP->lruMoreRecently;
1270 : 1563108 : VfdCache[vfdP->lruMoreRecently].lruLessRecently = vfdP->lruLessRecently;
1271 : :
1272 : : DO_DB(_dump_lru());
1273 : 1563108 : }
1274 : :
1275 : : static void
1276 : 3265 : LruDelete(File file)
1277 : : {
1278 : : Vfd *vfdP;
1279 : :
1280 : : Assert(file != 0);
1281 : :
1282 : : DO_DB(elog(LOG, "LruDelete %d (%s)",
1283 : : file, VfdCache[file].fileName));
1284 : :
1285 : 3265 : vfdP = &VfdCache[file];
1286 : :
1287 : 3265 : 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 [ - + ]: 3265 : if (close(vfdP->fd) != 0)
1294 [ # # # # ]: 0 : elog(vfdP->fdstate & FD_TEMP_FILE_LIMIT ? LOG : data_sync_elevel(LOG),
1295 : : "could not close file \"%s\": %m", vfdP->fileName);
1296 : 3265 : vfdP->fd = VFD_CLOSED;
1297 : 3265 : --nfile;
1298 : :
1299 : : /* delete the vfd record from the LRU ring */
1300 : 3265 : Delete(file);
1301 : 3265 : }
1302 : :
1303 : : static void
1304 : 2182401 : Insert(File file)
1305 : : {
1306 : : Vfd *vfdP;
1307 : :
1308 : : Assert(file != 0);
1309 : :
1310 : : DO_DB(elog(LOG, "Insert %d (%s)",
1311 : : file, VfdCache[file].fileName));
1312 : : DO_DB(_dump_lru());
1313 : :
1314 : 2182401 : vfdP = &VfdCache[file];
1315 : :
1316 : 2182401 : vfdP->lruMoreRecently = 0;
1317 : 2182401 : vfdP->lruLessRecently = VfdCache[0].lruLessRecently;
1318 : 2182401 : VfdCache[0].lruLessRecently = file;
1319 : 2182401 : VfdCache[vfdP->lruLessRecently].lruMoreRecently = file;
1320 : :
1321 : : DO_DB(_dump_lru());
1322 : 2182401 : }
1323 : :
1324 : : /* returns 0 on success, -1 on re-open failure (with errno set) */
1325 : : static int
1326 : 41 : LruInsert(File file)
1327 : : {
1328 : : Vfd *vfdP;
1329 : :
1330 : : Assert(file != 0);
1331 : :
1332 : : DO_DB(elog(LOG, "LruInsert %d (%s)",
1333 : : file, VfdCache[file].fileName));
1334 : :
1335 : 41 : vfdP = &VfdCache[file];
1336 : :
1337 [ + - ]: 41 : if (FileIsNotOpen(file))
1338 : : {
1339 : : /* Close excess kernel FDs. */
1340 : 41 : 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 : 41 : vfdP->fd = BasicOpenFilePerm(vfdP->fileName, vfdP->fileFlags,
1348 : : vfdP->fileMode);
1349 [ - + ]: 41 : if (vfdP->fd < 0)
1350 : : {
1351 : : DO_DB(elog(LOG, "re-open failed: %m"));
1352 : 0 : return -1;
1353 : : }
1354 : : else
1355 : : {
1356 : 41 : ++nfile;
1357 : : }
1358 : : }
1359 : :
1360 : : /*
1361 : : * put it at the head of the Lru ring
1362 : : */
1363 : :
1364 : 41 : Insert(file);
1365 : :
1366 : 41 : return 0;
1367 : : }
1368 : :
1369 : : /*
1370 : : * Release one kernel FD by closing the least-recently-used VFD.
1371 : : */
1372 : : static bool
1373 : 3083 : ReleaseLruFile(void)
1374 : : {
1375 : : DO_DB(elog(LOG, "ReleaseLruFile. Opened %d", nfile));
1376 : :
1377 [ + - ]: 3083 : if (nfile > 0)
1378 : : {
1379 : : /*
1380 : : * There are opened files and so there should be at least one used vfd
1381 : : * in the ring.
1382 : : */
1383 : : Assert(VfdCache[0].lruMoreRecently != 0);
1384 : 3083 : LruDelete(VfdCache[0].lruMoreRecently);
1385 : 3083 : return true; /* freed a file */
1386 : : }
1387 : 0 : return false; /* no files available to free */
1388 : : }
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 : 10046353 : ReleaseLruFiles(void)
1396 : : {
1397 [ + + ]: 10049436 : while (nfile + numAllocatedDescs + numExternalFDs >= max_safe_fds)
1398 : : {
1399 [ - + ]: 3083 : if (!ReleaseLruFile())
1400 : 0 : break;
1401 : : }
1402 : 10046353 : }
1403 : :
1404 : : static File
1405 : 1816119 : AllocateVfd(void)
1406 : : {
1407 : : Index i;
1408 : : File file;
1409 : :
1410 : : DO_DB(elog(LOG, "AllocateVfd. Size %zu", SizeVfdCache));
1411 : :
1412 : : Assert(SizeVfdCache > 0); /* InitFileAccess not called? */
1413 : :
1414 [ + + ]: 1816119 : if (VfdCache[0].nextFree == 0)
1415 : : {
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 : 32915 : Size newCacheSize = SizeVfdCache * 2;
1422 : : Vfd *newVfdCache;
1423 : :
1424 [ + + ]: 32915 : if (newCacheSize < 32)
1425 : 23075 : newCacheSize = 32;
1426 : :
1427 : : /*
1428 : : * Be careful not to clobber VfdCache ptr if realloc fails.
1429 : : */
1430 : 32915 : newVfdCache = (Vfd *) realloc(VfdCache, sizeof(Vfd) * newCacheSize);
1431 [ - + ]: 32915 : if (newVfdCache == NULL)
1432 [ # # ]: 0 : ereport(ERROR,
1433 : : (errcode(ERRCODE_OUT_OF_MEMORY),
1434 : : errmsg("out of memory")));
1435 : 32915 : VfdCache = newVfdCache;
1436 : :
1437 : : /*
1438 : : * Initialize the new entries and link them into the free list.
1439 : : */
1440 [ + + ]: 1603856 : for (i = SizeVfdCache; i < newCacheSize; i++)
1441 : : {
1442 [ + - + - : 12567528 : MemSet(&(VfdCache[i]), 0, sizeof(Vfd));
+ - + - +
+ ]
1443 : 1570941 : VfdCache[i].nextFree = i + 1;
1444 : 1570941 : VfdCache[i].fd = VFD_CLOSED;
1445 : : }
1446 : 32915 : VfdCache[newCacheSize - 1].nextFree = 0;
1447 : 32915 : VfdCache[0].nextFree = SizeVfdCache;
1448 : :
1449 : : /*
1450 : : * Record the new size
1451 : : */
1452 : 32915 : SizeVfdCache = newCacheSize;
1453 : : }
1454 : :
1455 : 1816119 : file = VfdCache[0].nextFree;
1456 : :
1457 : 1816119 : VfdCache[0].nextFree = VfdCache[file].nextFree;
1458 : :
1459 : 1816119 : return file;
1460 : : }
1461 : :
1462 : : static void
1463 : 1193922 : FreeVfd(File file)
1464 : : {
1465 : 1193922 : Vfd *vfdP = &VfdCache[file];
1466 : :
1467 : : DO_DB(elog(LOG, "FreeVfd: %d (%s)",
1468 : : file, vfdP->fileName ? vfdP->fileName : ""));
1469 : :
1470 [ + + ]: 1193922 : if (vfdP->fileName != NULL)
1471 : : {
1472 : 668503 : free(vfdP->fileName);
1473 : 668503 : vfdP->fileName = NULL;
1474 : : }
1475 : 1193922 : vfdP->fdstate = 0x0;
1476 : :
1477 : 1193922 : vfdP->nextFree = VfdCache[0].nextFree;
1478 : 1193922 : VfdCache[0].nextFree = file;
1479 : 1193922 : }
1480 : :
1481 : : /* returns 0 on success, -1 on re-open failure (with errno set) */
1482 : : static int
1483 : 3446912 : FileAccess(File file)
1484 : : {
1485 : : int returnValue;
1486 : :
1487 : : DO_DB(elog(LOG, "FileAccess %d (%s)",
1488 : : 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 [ + + ]: 3446912 : if (FileIsNotOpen(file))
1496 : : {
1497 : 41 : returnValue = LruInsert(file);
1498 [ - + ]: 41 : if (returnValue != 0)
1499 : 0 : return returnValue;
1500 : : }
1501 [ + + ]: 3446871 : else if (VfdCache[0].lruLessRecently != file)
1502 : : {
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 : 891660 : Delete(file);
1509 : 891660 : Insert(file);
1510 : : }
1511 : :
1512 : 3446912 : return 0;
1513 : : }
1514 : :
1515 : : /*
1516 : : * Called whenever a temporary file is deleted to report its size.
1517 : : */
1518 : : static void
1519 : 3993 : ReportTemporaryFileUsage(const char *path, pgoff_t size)
1520 : : {
1521 : 3993 : pgstat_report_tempfile(size);
1522 : :
1523 [ + + ]: 3993 : if (log_temp_files >= 0)
1524 : : {
1525 [ + + ]: 928 : if ((size / 1024) >= log_temp_files)
1526 [ + - ]: 136 : ereport(LOG,
1527 : : (errmsg("temporary file: path \"%s\", size %lld",
1528 : : path, (long long) size)));
1529 : : }
1530 : 3993 : }
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 : 6422 : RegisterTemporaryFile(File file)
1539 : : {
1540 : 6422 : ResourceOwnerRememberFile(CurrentResourceOwner, file);
1541 : 6422 : VfdCache[file].resowner = CurrentResourceOwner;
1542 : :
1543 : : /* Backup mechanism for closing at end of xact. */
1544 : 6422 : VfdCache[file].fdstate |= FD_CLOSE_AT_EOXACT;
1545 : 6422 : have_xact_temporary_files = true;
1546 : 6422 : }
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 : 1816119 : PathNameOpenFile(const char *fileName, int fileFlags)
1567 : : {
1568 : 1816119 : return PathNameOpenFilePerm(fileName, fileFlags, pg_file_create_mode);
1569 : : }
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 : 1816119 : PathNameOpenFilePerm(const char *fileName, int fileFlags, mode_t fileMode)
1580 : : {
1581 : : char *fnamecopy;
1582 : : File file;
1583 : : Vfd *vfdP;
1584 : :
1585 : : DO_DB(elog(LOG, "PathNameOpenFilePerm: %s %x %o",
1586 : : fileName, fileFlags, fileMode));
1587 : :
1588 : : /*
1589 : : * We need a malloc'd copy of the file name; fail cleanly if no room.
1590 : : */
1591 : 1816119 : fnamecopy = strdup(fileName);
1592 [ - + ]: 1816119 : if (fnamecopy == NULL)
1593 [ # # ]: 0 : ereport(ERROR,
1594 : : (errcode(ERRCODE_OUT_OF_MEMORY),
1595 : : errmsg("out of memory")));
1596 : :
1597 : 1816119 : file = AllocateVfd();
1598 : 1816119 : vfdP = &VfdCache[file];
1599 : :
1600 : : /* Close excess kernel FDs. */
1601 : 1816119 : 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 : 1816119 : fileFlags |= O_CLOEXEC;
1610 : :
1611 : 1816119 : vfdP->fd = BasicOpenFilePerm(fileName, fileFlags, fileMode);
1612 : :
1613 [ + + ]: 1816119 : if (vfdP->fd < 0)
1614 : : {
1615 : 525419 : int save_errno = errno;
1616 : :
1617 : 525419 : FreeVfd(file);
1618 : 525419 : free(fnamecopy);
1619 : 525419 : errno = save_errno;
1620 : 525419 : return -1;
1621 : : }
1622 : 1290700 : ++nfile;
1623 : : DO_DB(elog(LOG, "PathNameOpenFile: success %d",
1624 : : vfdP->fd));
1625 : :
1626 : 1290700 : vfdP->fileName = fnamecopy;
1627 : : /* Saved flags are adjusted to be OK for re-opening file */
1628 : 1290700 : vfdP->fileFlags = fileFlags & ~(O_CREAT | O_TRUNC | O_EXCL);
1629 : 1290700 : vfdP->fileMode = fileMode;
1630 : 1290700 : vfdP->fileSize = 0;
1631 : 1290700 : vfdP->fdstate = 0x0;
1632 : 1290700 : vfdP->resowner = NULL;
1633 : :
1634 : 1290700 : Insert(file);
1635 : :
1636 : 1290700 : return file;
1637 : : }
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 : 274 : PathNameCreateTemporaryDir(const char *basedir, const char *directory)
1652 : : {
1653 [ + + ]: 274 : if (MakePGDirectory(directory) < 0)
1654 : : {
1655 [ + + ]: 24 : if (errno == EEXIST)
1656 : 8 : 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 [ + + - + ]: 16 : if (MakePGDirectory(basedir) < 0 && errno != EEXIST)
1664 [ # # ]: 0 : ereport(ERROR,
1665 : : (errcode_for_file_access(),
1666 : : errmsg("cannot create temporary directory \"%s\": %m",
1667 : : basedir)));
1668 : :
1669 : : /* Try again. */
1670 [ + + - + ]: 16 : if (MakePGDirectory(directory) < 0 && errno != EEXIST)
1671 [ # # ]: 0 : ereport(ERROR,
1672 : : (errcode_for_file_access(),
1673 : : errmsg("cannot create temporary subdirectory \"%s\": %m",
1674 : : directory)));
1675 : : }
1676 : : }
1677 : :
1678 : : /*
1679 : : * Delete a directory and everything in it, if it exists.
1680 : : */
1681 : : void
1682 : 322 : PathNameDeleteTemporaryDir(const char *dirname)
1683 : : {
1684 : : struct stat statbuf;
1685 : :
1686 : : /* Silently ignore missing directory. */
1687 [ + + + - ]: 322 : if (stat(dirname, &statbuf) != 0 && errno == ENOENT)
1688 : 57 : 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 : 265 : walkdir(dirname, unlink_if_exists_fname, false, LOG);
1698 : : }
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 : 2019 : OpenTemporaryFile(bool interXact)
1716 : : {
1717 : 2019 : File file = 0;
1718 : :
1719 : : 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 [ + - ]: 2019 : if (!interXact)
1726 : 2019 : 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 [ + + + - ]: 2019 : if (numTempTableSpaces > 0 && !interXact)
1738 : : {
1739 : 1 : Oid tblspcOid = GetNextTempTableSpace();
1740 : :
1741 [ + - ]: 1 : if (OidIsValid(tblspcOid))
1742 : 1 : file = OpenTemporaryFileInTablespace(tblspcOid, false);
1743 : : }
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 [ + + ]: 2019 : if (file <= 0)
1751 [ + + ]: 2018 : file = OpenTemporaryFileInTablespace(MyDatabaseTableSpace ?
1752 : : MyDatabaseTableSpace :
1753 : : DEFAULTTABLESPACE_OID,
1754 : : true);
1755 : :
1756 : : /* Mark it for deletion at close and temporary file size limit */
1757 : 2019 : VfdCache[file].fdstate |= FD_DELETE_AT_CLOSE | FD_TEMP_FILE_LIMIT;
1758 : :
1759 : : /* Register it with the current resource owner */
1760 [ + - ]: 2019 : if (!interXact)
1761 : 2019 : RegisterTemporaryFile(file);
1762 : :
1763 : 2019 : return file;
1764 : : }
1765 : :
1766 : : /*
1767 : : * Return the path of the temp directory in a given tablespace.
1768 : : */
1769 : : void
1770 : 12393 : TempTablespacePath(char *path, Oid tablespace)
1771 : : {
1772 : : /*
1773 : : * Identify the tempfile directory for this tablespace.
1774 : : *
1775 : : * If someone tries to specify pg_global, use pg_default instead.
1776 : : */
1777 [ + - + + ]: 12393 : if (tablespace == InvalidOid ||
1778 [ - + ]: 1 : tablespace == DEFAULTTABLESPACE_OID ||
1779 : : tablespace == GLOBALTABLESPACE_OID)
1780 : 12392 : snprintf(path, MAXPGPATH, "base/%s", PG_TEMP_FILES_DIR);
1781 : : else
1782 : : {
1783 : : /* All other tablespaces are accessed via symlinks */
1784 : 1 : snprintf(path, MAXPGPATH, "%s/%u/%s/%s",
1785 : : PG_TBLSPC_DIR, tablespace, TABLESPACE_VERSION_DIRECTORY,
1786 : : PG_TEMP_FILES_DIR);
1787 : : }
1788 : 12393 : }
1789 : :
1790 : : /*
1791 : : * Open a temporary file in a specific tablespace.
1792 : : * Subroutine for OpenTemporaryFile, which see for details.
1793 : : */
1794 : : static File
1795 : 2019 : OpenTemporaryFileInTablespace(Oid tblspcOid, bool rejectError)
1796 : : {
1797 : : char tempdirpath[MAXPGPATH];
1798 : : char tempfilepath[MAXPGPATH];
1799 : : File file;
1800 : :
1801 : 2019 : TempTablespacePath(tempdirpath, tblspcOid);
1802 : :
1803 : : /*
1804 : : * Generate a tempfile name that should be unique within the current
1805 : : * database instance.
1806 : : */
1807 : 2019 : snprintf(tempfilepath, sizeof(tempfilepath), "%s/%s%d.%ld",
1808 : : 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 : 2019 : file = PathNameOpenFile(tempfilepath,
1815 : : O_RDWR | O_CREAT | O_TRUNC | PG_BINARY);
1816 [ + + ]: 2019 : if (file <= 0)
1817 : : {
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 : 122 : (void) MakePGDirectory(tempdirpath);
1827 : :
1828 : 122 : file = PathNameOpenFile(tempfilepath,
1829 : : O_RDWR | O_CREAT | O_TRUNC | PG_BINARY);
1830 [ - + - - ]: 122 : if (file <= 0 && rejectError)
1831 [ # # ]: 0 : elog(ERROR, "could not create temporary file \"%s\": %m",
1832 : : tempfilepath);
1833 : : }
1834 : :
1835 : 2019 : return file;
1836 : : }
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 : 2248 : PathNameCreateTemporaryFile(const char *path, bool error_on_failure)
1853 : : {
1854 : : File file;
1855 : :
1856 : : Assert(temporary_files_allowed); /* check temp file access is up */
1857 : :
1858 : 2248 : 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 : 2248 : file = PathNameOpenFile(path, O_RDWR | O_CREAT | O_TRUNC | PG_BINARY);
1865 [ + + ]: 2248 : if (file <= 0)
1866 : : {
1867 [ - + ]: 274 : if (error_on_failure)
1868 [ # # ]: 0 : ereport(ERROR,
1869 : : (errcode_for_file_access(),
1870 : : errmsg("could not create temporary file \"%s\": %m",
1871 : : path)));
1872 : : else
1873 : 274 : return file;
1874 : : }
1875 : :
1876 : : /* Mark it for temp_file_limit accounting. */
1877 : 1974 : VfdCache[file].fdstate |= FD_TEMP_FILE_LIMIT;
1878 : :
1879 : : /* Register it for automatic close. */
1880 : 1974 : RegisterTemporaryFile(file);
1881 : :
1882 : 1974 : return file;
1883 : : }
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 : 5148 : PathNameOpenTemporaryFile(const char *path, int mode)
1893 : : {
1894 : : File file;
1895 : :
1896 : : Assert(temporary_files_allowed); /* check temp file access is up */
1897 : :
1898 : 5148 : ResourceOwnerEnlarge(CurrentResourceOwner);
1899 : :
1900 : 5148 : file = PathNameOpenFile(path, mode | PG_BINARY);
1901 : :
1902 : : /* If no such file, then we don't raise an error. */
1903 [ + + - + ]: 5148 : if (file <= 0 && errno != ENOENT)
1904 [ # # ]: 0 : ereport(ERROR,
1905 : : (errcode_for_file_access(),
1906 : : errmsg("could not open temporary file \"%s\": %m",
1907 : : path)));
1908 : :
1909 [ + + ]: 5148 : if (file > 0)
1910 : : {
1911 : : /* Register it for automatic close. */
1912 : 2429 : RegisterTemporaryFile(file);
1913 : : }
1914 : :
1915 : 5148 : return file;
1916 : : }
1917 : :
1918 : : /*
1919 : : * Delete a file by pathname. Return true if the file existed, false if
1920 : : * didn't.
1921 : : */
1922 : : bool
1923 : 4317 : 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 [ + + ]: 4317 : if (stat(path, &filestats) != 0)
1930 : 2343 : stat_errno = errno;
1931 : : else
1932 : 1974 : 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 [ + + ]: 4317 : if (stat_errno == ENOENT)
1940 : 2343 : return false;
1941 : :
1942 [ - + ]: 1974 : if (unlink(path) < 0)
1943 : : {
1944 [ # # ]: 0 : if (errno != ENOENT)
1945 [ # # # # ]: 0 : ereport(error_on_failure ? ERROR : LOG,
1946 : : (errcode_for_file_access(),
1947 : : errmsg("could not unlink temporary file \"%s\": %m",
1948 : : path)));
1949 : 0 : return false;
1950 : : }
1951 : :
1952 [ + - ]: 1974 : if (stat_errno == 0)
1953 : 1974 : ReportTemporaryFileUsage(path, filestats.st_size);
1954 : : else
1955 : : {
1956 : 0 : errno = stat_errno;
1957 [ # # ]: 0 : ereport(LOG,
1958 : : (errcode_for_file_access(),
1959 : : errmsg("could not stat file \"%s\": %m", path)));
1960 : : }
1961 : :
1962 : 1974 : return true;
1963 : : }
1964 : :
1965 : : /*
1966 : : * close a file when done with it
1967 : : */
1968 : : void
1969 : 668503 : FileClose(File file)
1970 : : {
1971 : : Vfd *vfdP;
1972 : :
1973 : : Assert(FileIsValid(file));
1974 : :
1975 : : DO_DB(elog(LOG, "FileClose: %d (%s)",
1976 : : file, VfdCache[file].fileName));
1977 : :
1978 : 668503 : vfdP = &VfdCache[file];
1979 : :
1980 [ + + ]: 668503 : if (!FileIsNotOpen(file))
1981 : : {
1982 : 668183 : pgaio_closing_fd(vfdP->fd);
1983 : :
1984 : : /* close the file */
1985 [ - + ]: 668183 : if (close(vfdP->fd) != 0)
1986 : : {
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 : : "could not close file \"%s\": %m", vfdP->fileName);
1993 : : }
1994 : :
1995 : 668183 : --nfile;
1996 : 668183 : vfdP->fd = VFD_CLOSED;
1997 : :
1998 : : /* remove the file from the lru ring */
1999 : 668183 : Delete(file);
2000 : : }
2001 : :
2002 [ + + ]: 668503 : if (vfdP->fdstate & FD_TEMP_FILE_LIMIT)
2003 : : {
2004 : : /* Subtract its size from current usage (do first in case of error) */
2005 : 3993 : temporary_files_size -= vfdP->fileSize;
2006 : 3993 : vfdP->fileSize = 0;
2007 : : }
2008 : :
2009 : : /*
2010 : : * Delete the file if it was temporary, and make a log entry if wanted
2011 : : */
2012 [ + + ]: 668503 : if (vfdP->fdstate & FD_DELETE_AT_CLOSE)
2013 : : {
2014 : : struct stat filestats;
2015 : : 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 : 2019 : vfdP->fdstate &= ~FD_DELETE_AT_CLOSE;
2025 : :
2026 : :
2027 : : /* first try the stat() */
2028 [ - + ]: 2019 : if (stat(vfdP->fileName, &filestats))
2029 : 0 : stat_errno = errno;
2030 : : else
2031 : 2019 : stat_errno = 0;
2032 : :
2033 : : /* in any case do the unlink */
2034 [ - + ]: 2019 : if (unlink(vfdP->fileName))
2035 [ # # ]: 0 : ereport(LOG,
2036 : : (errcode_for_file_access(),
2037 : : errmsg("could not delete file \"%s\": %m", vfdP->fileName)));
2038 : :
2039 : : /* and last report the stat results */
2040 [ + - ]: 2019 : if (stat_errno == 0)
2041 : 2019 : ReportTemporaryFileUsage(vfdP->fileName, filestats.st_size);
2042 : : else
2043 : : {
2044 : 0 : errno = stat_errno;
2045 [ # # ]: 0 : ereport(LOG,
2046 : : (errcode_for_file_access(),
2047 : : errmsg("could not stat file \"%s\": %m", vfdP->fileName)));
2048 : : }
2049 : : }
2050 : :
2051 : : /* Unregister it from the resource owner */
2052 [ + + ]: 668503 : if (vfdP->resowner)
2053 : 6417 : ResourceOwnerForgetFile(vfdP->resowner, file);
2054 : :
2055 : : /*
2056 : : * Return the Vfd slot to the free list
2057 : : */
2058 : 668503 : FreeVfd(file);
2059 : 668503 : }
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 : 9662 : FilePrefetch(File file, pgoff_t offset, pgoff_t amount, uint32 wait_event_info)
2071 : : {
2072 : : Assert(FileIsValid(file));
2073 : :
2074 : : DO_DB(elog(LOG, "FilePrefetch: %d (%s) " INT64_FORMAT " " INT64_FORMAT,
2075 : : file, VfdCache[file].fileName,
2076 : : (int64) offset, (int64) amount));
2077 : :
2078 : : #if defined(USE_POSIX_FADVISE) && defined(POSIX_FADV_WILLNEED)
2079 : : {
2080 : : int returnCode;
2081 : :
2082 : 9662 : returnCode = FileAccess(file);
2083 [ + - ]: 9662 : if (returnCode < 0)
2084 : 0 : return errno;
2085 : :
2086 : 9662 : retry:
2087 : 9662 : pgstat_report_wait_start(wait_event_info);
2088 : 9662 : returnCode = posix_fadvise(VfdCache[file].fd, offset, amount,
2089 : : POSIX_FADV_WILLNEED);
2090 : 9662 : pgstat_report_wait_end();
2091 : :
2092 [ - + ]: 9662 : if (returnCode == EINTR)
2093 : 0 : goto retry;
2094 : :
2095 : 9662 : return returnCode;
2096 : : }
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 : : }
2124 : :
2125 : : void
2126 : 0 : FileWriteback(File file, pgoff_t offset, pgoff_t nbytes, uint32 wait_event_info)
2127 : : {
2128 : : int returnCode;
2129 : :
2130 : : Assert(FileIsValid(file));
2131 : :
2132 : : DO_DB(elog(LOG, "FileWriteback: %d (%s) " INT64_FORMAT " " INT64_FORMAT,
2133 : : file, VfdCache[file].fileName,
2134 : : (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 : : }
2150 : :
2151 : : ssize_t
2152 : 421969 : FileReadV(File file, const struct iovec *iov, int iovcnt, pgoff_t offset,
2153 : : uint32 wait_event_info)
2154 : : {
2155 : : ssize_t returnCode;
2156 : : Vfd *vfdP;
2157 : :
2158 : : Assert(FileIsValid(file));
2159 : :
2160 : : DO_DB(elog(LOG, "FileReadV: %d (%s) " INT64_FORMAT " %d",
2161 : : file, VfdCache[file].fileName,
2162 : : (int64) offset,
2163 : : iovcnt));
2164 : :
2165 : 421969 : returnCode = FileAccess(file);
2166 [ - + ]: 421969 : if (returnCode < 0)
2167 : 0 : return returnCode;
2168 : :
2169 : 421969 : vfdP = &VfdCache[file];
2170 : :
2171 : 421969 : retry:
2172 : 421969 : pgstat_report_wait_start(wait_event_info);
2173 : 421969 : returnCode = pg_preadv(vfdP->fd, iov, iovcnt, offset);
2174 : 421969 : pgstat_report_wait_end();
2175 : :
2176 [ - + ]: 421969 : if (returnCode < 0)
2177 : : {
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 : : }
2203 : :
2204 : 421969 : return returnCode;
2205 : : }
2206 : :
2207 : : int
2208 : 1366124 : FileStartReadV(PgAioHandle *ioh, File file,
2209 : : int iovcnt, pgoff_t offset,
2210 : : uint32 wait_event_info)
2211 : : {
2212 : : int returnCode;
2213 : : Vfd *vfdP;
2214 : :
2215 : : Assert(FileIsValid(file));
2216 : :
2217 : : DO_DB(elog(LOG, "FileStartReadV: %d (%s) " INT64_FORMAT " %d",
2218 : : file, VfdCache[file].fileName,
2219 : : (int64) offset,
2220 : : iovcnt));
2221 : :
2222 : 1366124 : returnCode = FileAccess(file);
2223 [ - + ]: 1366124 : if (returnCode < 0)
2224 : 0 : return returnCode;
2225 : :
2226 : 1366124 : vfdP = &VfdCache[file];
2227 : :
2228 : 1366124 : pgaio_io_start_readv(ioh, vfdP->fd, iovcnt, offset);
2229 : :
2230 : 1366124 : return 0;
2231 : : }
2232 : :
2233 : : ssize_t
2234 : 931137 : FileWriteV(File file, const struct iovec *iov, int iovcnt, pgoff_t offset,
2235 : : uint32 wait_event_info)
2236 : : {
2237 : : ssize_t returnCode;
2238 : : Vfd *vfdP;
2239 : :
2240 : : Assert(FileIsValid(file));
2241 : :
2242 : : DO_DB(elog(LOG, "FileWriteV: %d (%s) " INT64_FORMAT " %d",
2243 : : file, VfdCache[file].fileName,
2244 : : (int64) offset,
2245 : : iovcnt));
2246 : :
2247 : 931137 : returnCode = FileAccess(file);
2248 [ - + ]: 931137 : if (returnCode < 0)
2249 : 0 : return returnCode;
2250 : :
2251 : 931137 : 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 [ + - - - ]: 931137 : if (temp_file_limit >= 0 && (vfdP->fdstate & FD_TEMP_FILE_LIMIT))
2262 : : {
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 : : {
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 : : (errcode(ERRCODE_CONFIGURATION_LIMIT_EXCEEDED),
2276 : : errmsg("temporary file size exceeds \"temp_file_limit\" (%dkB)",
2277 : : temp_file_limit)));
2278 : : }
2279 : : }
2280 : :
2281 : 931137 : retry:
2282 : 931137 : pgstat_report_wait_start(wait_event_info);
2283 : 931137 : returnCode = pg_pwritev(vfdP->fd, iov, iovcnt, offset);
2284 : 931137 : pgstat_report_wait_end();
2285 : :
2286 [ + - ]: 931137 : if (returnCode >= 0)
2287 : : {
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 : 931137 : errno = ENOSPC;
2296 : :
2297 : : /*
2298 : : * Maintain fileSize and temporary_files_size if it's a temp file.
2299 : : */
2300 [ + + ]: 931137 : if (vfdP->fdstate & FD_TEMP_FILE_LIMIT)
2301 : : {
2302 : 69154 : pgoff_t past_write = offset + returnCode;
2303 : :
2304 [ + + ]: 69154 : if (past_write > vfdP->fileSize)
2305 : : {
2306 : 45886 : temporary_files_size += past_write - vfdP->fileSize;
2307 : 45886 : vfdP->fileSize = past_write;
2308 : : }
2309 : : }
2310 : : }
2311 : : else
2312 : : {
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 : : }
2334 : :
2335 : 931137 : return returnCode;
2336 : : }
2337 : :
2338 : : int
2339 : 544 : FileSync(File file, uint32 wait_event_info)
2340 : : {
2341 : : int returnCode;
2342 : :
2343 : : Assert(FileIsValid(file));
2344 : :
2345 : : DO_DB(elog(LOG, "FileSync: %d (%s)",
2346 : : file, VfdCache[file].fileName));
2347 : :
2348 : 544 : returnCode = FileAccess(file);
2349 [ - + ]: 544 : if (returnCode < 0)
2350 : 0 : return returnCode;
2351 : :
2352 : 544 : pgstat_report_wait_start(wait_event_info);
2353 : 544 : returnCode = pg_fsync(VfdCache[file].fd);
2354 : 544 : pgstat_report_wait_end();
2355 : :
2356 : 544 : return returnCode;
2357 : : }
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 : 270658 : FileZero(File file, pgoff_t offset, pgoff_t amount, uint32 wait_event_info)
2367 : : {
2368 : : int returnCode;
2369 : : ssize_t written;
2370 : :
2371 : : Assert(FileIsValid(file));
2372 : :
2373 : : DO_DB(elog(LOG, "FileZero: %d (%s) " INT64_FORMAT " " INT64_FORMAT,
2374 : : file, VfdCache[file].fileName,
2375 : : (int64) offset, (int64) amount));
2376 : :
2377 : 270658 : returnCode = FileAccess(file);
2378 [ - + ]: 270658 : if (returnCode < 0)
2379 : 0 : return returnCode;
2380 : :
2381 : 270658 : pgstat_report_wait_start(wait_event_info);
2382 : 270658 : written = pg_pwrite_zeros(VfdCache[file].fd, amount, offset);
2383 : 270658 : pgstat_report_wait_end();
2384 : :
2385 [ - + ]: 270658 : if (written < 0)
2386 : 0 : return -1;
2387 [ - + ]: 270658 : else if (written != amount)
2388 : : {
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 : : }
2394 : :
2395 : 270658 : return 0;
2396 : : }
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 : 657 : FileFallocate(File file, pgoff_t offset, pgoff_t amount, uint32 wait_event_info)
2412 : : {
2413 : : #ifdef HAVE_POSIX_FALLOCATE
2414 : : int returnCode;
2415 : :
2416 : : Assert(FileIsValid(file));
2417 : :
2418 : : DO_DB(elog(LOG, "FileFallocate: %d (%s) " INT64_FORMAT " " INT64_FORMAT,
2419 : : file, VfdCache[file].fileName,
2420 : : (int64) offset, (int64) amount));
2421 : :
2422 : 657 : returnCode = FileAccess(file);
2423 [ + - ]: 657 : if (returnCode < 0)
2424 : 0 : return -1;
2425 : :
2426 : 657 : retry:
2427 : 657 : pgstat_report_wait_start(wait_event_info);
2428 : 657 : returnCode = posix_fallocate(VfdCache[file].fd, offset, amount);
2429 : 657 : pgstat_report_wait_end();
2430 : :
2431 [ + - ]: 657 : if (returnCode == 0)
2432 : 657 : 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 : : #endif
2446 : :
2447 : 0 : return FileZero(file, offset, amount, wait_event_info);
2448 : : }
2449 : :
2450 : : pgoff_t
2451 : 3044938 : FileSize(File file)
2452 : : {
2453 : : Assert(FileIsValid(file));
2454 : :
2455 : : DO_DB(elog(LOG, "FileSize %d (%s)",
2456 : : file, VfdCache[file].fileName));
2457 : :
2458 [ + + ]: 3044938 : if (FileIsNotOpen(file))
2459 : : {
2460 [ - + ]: 29 : if (FileAccess(file) < 0)
2461 : 0 : return (pgoff_t) -1;
2462 : : }
2463 : :
2464 : 3044938 : return lseek(VfdCache[file].fd, 0, SEEK_END);
2465 : : }
2466 : :
2467 : : int
2468 : 734 : FileTruncate(File file, pgoff_t offset, uint32 wait_event_info)
2469 : : {
2470 : : int returnCode;
2471 : :
2472 : : Assert(FileIsValid(file));
2473 : :
2474 : : DO_DB(elog(LOG, "FileTruncate %d (%s)",
2475 : : file, VfdCache[file].fileName));
2476 : :
2477 : 734 : returnCode = FileAccess(file);
2478 [ - + ]: 734 : if (returnCode < 0)
2479 : 0 : return returnCode;
2480 : :
2481 : 734 : pgstat_report_wait_start(wait_event_info);
2482 : 734 : returnCode = pg_ftruncate(VfdCache[file].fd, offset);
2483 : 734 : pgstat_report_wait_end();
2484 : :
2485 [ + - - + ]: 734 : if (returnCode == 0 && VfdCache[file].fileSize > offset)
2486 : : {
2487 : : /* adjust our state for truncation of a temp file */
2488 : : Assert(VfdCache[file].fdstate & FD_TEMP_FILE_LIMIT);
2489 : 0 : temporary_files_size -= VfdCache[file].fileSize - offset;
2490 : 0 : VfdCache[file].fileSize = offset;
2491 : : }
2492 : :
2493 : 734 : return returnCode;
2494 : : }
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 : 38 : FilePathName(File file)
2504 : : {
2505 : : Assert(FileIsValid(file));
2506 : :
2507 : 38 : return VfdCache[file].fileName;
2508 : : }
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 : 445398 : FileGetRawDesc(File file)
2520 : : {
2521 : : int returnCode;
2522 : :
2523 : 445398 : returnCode = FileAccess(file);
2524 [ - + ]: 445398 : if (returnCode < 0)
2525 : 0 : return returnCode;
2526 : :
2527 : : Assert(FileIsValid(file));
2528 : 445398 : return VfdCache[file].fd;
2529 : : }
2530 : :
2531 : : /*
2532 : : * FileGetRawFlags - returns the file flags on open(2)
2533 : : */
2534 : : int
2535 : 0 : FileGetRawFlags(File file)
2536 : : {
2537 : : Assert(FileIsValid(file));
2538 : 0 : return VfdCache[file].fileFlags;
2539 : : }
2540 : :
2541 : : /*
2542 : : * FileGetRawMode - returns the mode bitmask passed to open(2)
2543 : : */
2544 : : mode_t
2545 : 0 : FileGetRawMode(File file)
2546 : : {
2547 : : Assert(FileIsValid(file));
2548 : 0 : return VfdCache[file].fileMode;
2549 : : }
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 : 7982387 : reserveAllocatedDesc(void)
2557 : : {
2558 : : AllocateDesc *newDescs;
2559 : : int newMax;
2560 : :
2561 : : /* Quick out if array already has a free slot. */
2562 [ + + ]: 7982387 : if (numAllocatedDescs < maxAllocatedDescs)
2563 : 7981035 : 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 [ + - ]: 1352 : if (allocatedDescs == NULL)
2572 : : {
2573 : 1352 : newMax = FD_MINFREE / 3;
2574 : 1352 : newDescs = (AllocateDesc *) malloc(newMax * sizeof(AllocateDesc));
2575 : : /* Out of memory already? Treat as fatal error. */
2576 [ - + ]: 1352 : if (newDescs == NULL)
2577 [ # # ]: 0 : ereport(ERROR,
2578 : : (errcode(ERRCODE_OUT_OF_MEMORY),
2579 : : errmsg("out of memory")));
2580 : 1352 : allocatedDescs = newDescs;
2581 : 1352 : maxAllocatedDescs = newMax;
2582 : 1352 : return true;
2583 : : }
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 : : {
2599 : 0 : newDescs = (AllocateDesc *) realloc(allocatedDescs,
2600 : : 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 : : }
2608 : :
2609 : : /* Can't enlarge allocatedDescs[] any more. */
2610 : 0 : return false;
2611 : : }
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 : 110554 : AllocateFile(const char *name, const char *mode)
2632 : : {
2633 : : FILE *file;
2634 : :
2635 : : DO_DB(elog(LOG, "AllocateFile: Allocated %d (%s)",
2636 : : numAllocatedDescs, name));
2637 : :
2638 : : /* Can we allocate another non-virtual FD? */
2639 [ - + ]: 110554 : if (!reserveAllocatedDesc())
2640 [ # # ]: 0 : ereport(ERROR,
2641 : : (errcode(ERRCODE_INSUFFICIENT_RESOURCES),
2642 : : errmsg("exceeded maxAllocatedDescs (%d) while trying to open file \"%s\"",
2643 : : maxAllocatedDescs, name)));
2644 : :
2645 : : /* Close excess kernel FDs. */
2646 : 110554 : ReleaseLruFiles();
2647 : :
2648 : 110554 : TryAgain:
2649 [ + + ]: 110554 : if ((file = fopen(name, mode)) != NULL)
2650 : : {
2651 : 101835 : AllocateDesc *desc = &allocatedDescs[numAllocatedDescs];
2652 : :
2653 : 101835 : desc->kind = AllocateDescFile;
2654 : 101835 : desc->desc.file = file;
2655 : 101835 : desc->create_subid = GetCurrentSubTransactionId();
2656 : 101835 : numAllocatedDescs++;
2657 : 101835 : return desc->desc.file;
2658 : : }
2659 : :
2660 [ + - - + ]: 8719 : if (errno == EMFILE || errno == ENFILE)
2661 : : {
2662 : 0 : int save_errno = errno;
2663 : :
2664 [ # # ]: 0 : ereport(LOG,
2665 : : (errcode(ERRCODE_INSUFFICIENT_RESOURCES),
2666 : : 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 : : }
2672 : :
2673 : 8719 : return NULL;
2674 : : }
2675 : :
2676 : : /*
2677 : : * Open a file with OpenTransientFilePerm() and pass default file mode for
2678 : : * the fileMode parameter.
2679 : : */
2680 : : int
2681 : 7815286 : OpenTransientFile(const char *fileName, int fileFlags)
2682 : : {
2683 : 7815286 : return OpenTransientFilePerm(fileName, fileFlags, pg_file_create_mode);
2684 : : }
2685 : :
2686 : : /*
2687 : : * Like AllocateFile, but returns an unbuffered fd like open(2)
2688 : : */
2689 : : int
2690 : 7815294 : OpenTransientFilePerm(const char *fileName, int fileFlags, mode_t fileMode)
2691 : : {
2692 : : int fd;
2693 : :
2694 : : DO_DB(elog(LOG, "OpenTransientFile: Allocated %d (%s)",
2695 : : numAllocatedDescs, fileName));
2696 : :
2697 : : /* Can we allocate another non-virtual FD? */
2698 [ - + ]: 7815294 : if (!reserveAllocatedDesc())
2699 [ # # ]: 0 : ereport(ERROR,
2700 : : (errcode(ERRCODE_INSUFFICIENT_RESOURCES),
2701 : : errmsg("exceeded maxAllocatedDescs (%d) while trying to open file \"%s\"",
2702 : : maxAllocatedDescs, fileName)));
2703 : :
2704 : : /* Close excess kernel FDs. */
2705 : 7815294 : ReleaseLruFiles();
2706 : :
2707 : 7815294 : fd = BasicOpenFilePerm(fileName, fileFlags, fileMode);
2708 : :
2709 [ + + ]: 7815294 : if (fd >= 0)
2710 : : {
2711 : 7809742 : AllocateDesc *desc = &allocatedDescs[numAllocatedDescs];
2712 : :
2713 : 7809742 : desc->kind = AllocateDescRawFD;
2714 : 7809742 : desc->desc.fd = fd;
2715 : 7809742 : desc->create_subid = GetCurrentSubTransactionId();
2716 : 7809742 : numAllocatedDescs++;
2717 : :
2718 : 7809742 : return fd;
2719 : : }
2720 : :
2721 : 5552 : return -1; /* failure */
2722 : : }
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 : 81 : OpenPipeStream(const char *command, const char *mode)
2735 : : {
2736 : : FILE *file;
2737 : : int save_errno;
2738 : :
2739 : : DO_DB(elog(LOG, "OpenPipeStream: Allocated %d (%s)",
2740 : : numAllocatedDescs, command));
2741 : :
2742 : : /* Can we allocate another non-virtual FD? */
2743 [ - + ]: 81 : if (!reserveAllocatedDesc())
2744 [ # # ]: 0 : ereport(ERROR,
2745 : : (errcode(ERRCODE_INSUFFICIENT_RESOURCES),
2746 : : errmsg("exceeded maxAllocatedDescs (%d) while trying to execute command \"%s\"",
2747 : : maxAllocatedDescs, command)));
2748 : :
2749 : : /* Close excess kernel FDs. */
2750 : 81 : ReleaseLruFiles();
2751 : :
2752 : 81 : TryAgain:
2753 : 81 : fflush(NULL);
2754 : 81 : pqsignal(SIGPIPE, PG_SIG_DFL);
2755 : 81 : errno = 0;
2756 : 81 : file = popen(command, mode);
2757 : 81 : save_errno = errno;
2758 : 81 : pqsignal(SIGPIPE, PG_SIG_IGN);
2759 : 81 : errno = save_errno;
2760 [ + - ]: 81 : if (file != NULL)
2761 : : {
2762 : 81 : AllocateDesc *desc = &allocatedDescs[numAllocatedDescs];
2763 : :
2764 : 81 : desc->kind = AllocateDescPipe;
2765 : 81 : desc->desc.file = file;
2766 : 81 : desc->create_subid = GetCurrentSubTransactionId();
2767 : 81 : numAllocatedDescs++;
2768 : 81 : return desc->desc.file;
2769 : : }
2770 : :
2771 [ # # # # ]: 0 : if (errno == EMFILE || errno == ENFILE)
2772 : : {
2773 [ # # ]: 0 : ereport(LOG,
2774 : : (errcode(ERRCODE_INSUFFICIENT_RESOURCES),
2775 : : errmsg("out of file descriptors: %m; release and retry")));
2776 [ # # ]: 0 : if (ReleaseLruFile())
2777 : 0 : goto TryAgain;
2778 : 0 : errno = save_errno;
2779 : : }
2780 : :
2781 : 0 : return NULL;
2782 : : }
2783 : :
2784 : : /*
2785 : : * Free an AllocateDesc of any type.
2786 : : *
2787 : : * The argument *must* point into the allocatedDescs[] array.
2788 : : */
2789 : : static int
2790 : 7967026 : FreeDesc(AllocateDesc *desc)
2791 : : {
2792 : : int result;
2793 : :
2794 : : /* Close the underlying object */
2795 [ + + + + : 7967026 : switch (desc->kind)
- ]
2796 : : {
2797 : 101835 : case AllocateDescFile:
2798 : 101835 : result = fclose(desc->desc.file);
2799 : 101835 : break;
2800 : 81 : case AllocateDescPipe:
2801 : 81 : result = pclose(desc->desc.file);
2802 : 81 : break;
2803 : 55368 : case AllocateDescDir:
2804 : 55368 : result = closedir(desc->desc.dir);
2805 : 55368 : break;
2806 : 7809742 : case AllocateDescRawFD:
2807 : 7809742 : pgaio_closing_fd(desc->desc.fd);
2808 : 7809742 : result = close(desc->desc.fd);
2809 : 7809742 : break;
2810 : 0 : default:
2811 [ # # ]: 0 : elog(ERROR, "AllocateDesc kind not recognized");
2812 : : result = 0; /* keep compiler quiet */
2813 : : break;
2814 : : }
2815 : :
2816 : : /* Compact storage in the allocatedDescs array */
2817 : 7967026 : numAllocatedDescs--;
2818 : 7967026 : *desc = allocatedDescs[numAllocatedDescs];
2819 : :
2820 : 7967026 : return result;
2821 : : }
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 : 101815 : 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 [ + - ]: 101820 : for (i = numAllocatedDescs; --i >= 0;)
2838 : : {
2839 : 101820 : AllocateDesc *desc = &allocatedDescs[i];
2840 : :
2841 [ + - + + ]: 101820 : if (desc->kind == AllocateDescFile && desc->desc.file == file)
2842 : 101815 : return FreeDesc(desc);
2843 : : }
2844 : :
2845 : : /* Only get here if someone passes us a file not in allocatedDescs */
2846 [ # # ]: 0 : elog(WARNING, "file passed to FreeFile was not obtained from AllocateFile");
2847 : :
2848 : 0 : 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 : 7809740 : 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 [ + - ]: 7809750 : for (i = numAllocatedDescs; --i >= 0;)
2866 : : {
2867 : 7809750 : AllocateDesc *desc = &allocatedDescs[i];
2868 : :
2869 [ + - + + ]: 7809750 : if (desc->kind == AllocateDescRawFD && desc->desc.fd == fd)
2870 : 7809740 : return FreeDesc(desc);
2871 : : }
2872 : :
2873 : : /* Only get here if someone passes us a file not in allocatedDescs */
2874 [ # # ]: 0 : elog(WARNING, "fd passed to CloseTransientFile was not obtained from OpenTransientFile");
2875 : :
2876 : 0 : pgaio_closing_fd(fd);
2877 : :
2878 : 0 : 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 : 56458 : AllocateDir(const char *dirname)
2895 : : {
2896 : : DIR *dir;
2897 : :
2898 : : DO_DB(elog(LOG, "AllocateDir: Allocated %d (%s)",
2899 : : numAllocatedDescs, dirname));
2900 : :
2901 : : /* Can we allocate another non-virtual FD? */
2902 [ - + ]: 56458 : if (!reserveAllocatedDesc())
2903 [ # # ]: 0 : ereport(ERROR,
2904 : : (errcode(ERRCODE_INSUFFICIENT_RESOURCES),
2905 : : errmsg("exceeded maxAllocatedDescs (%d) while trying to open directory \"%s\"",
2906 : : maxAllocatedDescs, dirname)));
2907 : :
2908 : : /* Close excess kernel FDs. */
2909 : 56458 : ReleaseLruFiles();
2910 : :
2911 : 56458 : TryAgain:
2912 [ + + ]: 56458 : if ((dir = opendir(dirname)) != NULL)
2913 : : {
2914 : 55368 : AllocateDesc *desc = &allocatedDescs[numAllocatedDescs];
2915 : :
2916 : 55368 : desc->kind = AllocateDescDir;
2917 : 55368 : desc->desc.dir = dir;
2918 : 55368 : desc->create_subid = GetCurrentSubTransactionId();
2919 : 55368 : numAllocatedDescs++;
2920 : 55368 : return desc->desc.dir;
2921 : : }
2922 : :
2923 [ + - - + ]: 1090 : if (errno == EMFILE || errno == ENFILE)
2924 : : {
2925 : 0 : int save_errno = errno;
2926 : :
2927 [ # # ]: 0 : ereport(LOG,
2928 : : (errcode(ERRCODE_INSUFFICIENT_RESOURCES),
2929 : : 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 : : }
2935 : :
2936 : 1090 : return NULL;
2937 : : }
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 : 2787413 : ReadDir(DIR *dir, const char *dirname)
2961 : : {
2962 : 2787413 : return ReadDirExtended(dir, dirname, ERROR);
2963 : : }
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 : 4826079 : ReadDirExtended(DIR *dir, const char *dirname, int elevel)
2976 : : {
2977 : : struct dirent *dent;
2978 : :
2979 : : /* Give a generic message for AllocateDir failure, if caller didn't */
2980 [ + + ]: 4826079 : if (dir == NULL)
2981 : : {
2982 [ + - ]: 4 : ereport(elevel,
2983 : : (errcode_for_file_access(),
2984 : : errmsg("could not open directory \"%s\": %m",
2985 : : dirname)));
2986 : 0 : return NULL;
2987 : : }
2988 : :
2989 : 4826075 : errno = 0;
2990 [ + + ]: 4826075 : if ((dent = readdir(dir)) != NULL)
2991 : 4785343 : return dent;
2992 : :
2993 [ - + ]: 40732 : if (errno)
2994 [ # # ]: 0 : ereport(elevel,
2995 : : (errcode_for_file_access(),
2996 : : errmsg("could not read directory \"%s\": %m",
2997 : : dirname)));
2998 : 40732 : return NULL;
2999 : : }
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 : 55355 : FreeDir(DIR *dir)
3013 : : {
3014 : : int i;
3015 : :
3016 : : /* Nothing to do if AllocateDir failed */
3017 [ - + ]: 55355 : if (dir == NULL)
3018 : 0 : 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 [ + - ]: 55355 : for (i = numAllocatedDescs; --i >= 0;)
3024 : : {
3025 : 55355 : AllocateDesc *desc = &allocatedDescs[i];
3026 : :
3027 [ + - + - ]: 55355 : if (desc->kind == AllocateDescDir && desc->desc.dir == dir)
3028 : 55355 : return FreeDesc(desc);
3029 : : }
3030 : :
3031 : : /* Only get here if someone passes us a dir not in allocatedDescs */
3032 [ # # ]: 0 : elog(WARNING, "dir passed to FreeDir was not obtained from AllocateDir");
3033 : :
3034 : 0 : return closedir(dir);
3035 : : }
3036 : :
3037 : :
3038 : : /*
3039 : : * Close a pipe stream returned by OpenPipeStream.
3040 : : */
3041 : : int
3042 : 81 : 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 [ + - ]: 81 : for (i = numAllocatedDescs; --i >= 0;)
3050 : : {
3051 : 81 : AllocateDesc *desc = &allocatedDescs[i];
3052 : :
3053 [ + - + - ]: 81 : if (desc->kind == AllocateDescPipe && desc->desc.file == file)
3054 : 81 : return FreeDesc(desc);
3055 : : }
3056 : :
3057 : : /* Only get here if someone passes us a file not in allocatedDescs */
3058 [ # # ]: 0 : elog(WARNING, "file passed to ClosePipeStream was not obtained from OpenPipeStream");
3059 : :
3060 : 0 : 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 : 50 : closeAllVfds(void)
3072 : : {
3073 : : Index i;
3074 : :
3075 [ + - ]: 50 : if (SizeVfdCache > 0)
3076 : : {
3077 : : Assert(FileIsNotOpen(0)); /* Make sure ring not corrupted */
3078 [ + + ]: 1600 : for (i = 1; i < SizeVfdCache; i++)
3079 : : {
3080 [ + + ]: 1550 : if (!FileIsNotOpen(i))
3081 : 182 : LruDelete(i);
3082 : : }
3083 : : }
3084 : 50 : }
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 : 4322 : SetTempTablespaces(Oid *tableSpaces, int numSpaces)
3101 : : {
3102 : : Assert(numSpaces >= 0);
3103 : 4322 : tempTableSpaces = tableSpaces;
3104 : 4322 : 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 [ - + ]: 4322 : if (numSpaces > 1)
3115 : 0 : nextTempTableSpace = pg_prng_uint64_range(&pg_global_prng_state,
3116 : 0 : 0, numSpaces - 1);
3117 : : else
3118 : 4322 : nextTempTableSpace = 0;
3119 : 4322 : }
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 : 6264 : TempTablespacesAreSet(void)
3130 : : {
3131 : 6264 : return (numTempTableSpaces >= 0);
3132 : : }
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 : 290 : GetTempTablespaces(Oid *tableSpaces, int numSpaces)
3145 : : {
3146 : : int i;
3147 : :
3148 : : Assert(TempTablespacesAreSet());
3149 [ - + - - ]: 290 : for (i = 0; i < numTempTableSpaces && i < numSpaces; ++i)
3150 : 0 : tableSpaces[i] = tempTableSpaces[i];
3151 : :
3152 : 290 : return i;
3153 : : }
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 : 3142 : GetNextTempTableSpace(void)
3163 : : {
3164 [ + + ]: 3142 : if (numTempTableSpaces > 0)
3165 : : {
3166 : : /* Advance nextTempTableSpace counter with wraparound */
3167 [ + - ]: 1 : if (++nextTempTableSpace >= numTempTableSpaces)
3168 : 1 : nextTempTableSpace = 0;
3169 : 1 : return tempTableSpaces[nextTempTableSpace];
3170 : : }
3171 : 3141 : return InvalidOid;
3172 : : }
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 : 23017 : AtEOSubXact_Files(bool isCommit, SubTransactionId mySubid,
3185 : : SubTransactionId parentSubid)
3186 : : {
3187 [ - + ]: 23017 : for (int i = 0; i < numAllocatedDescs; i++)
3188 : : {
3189 [ # # ]: 0 : if (allocatedDescs[i].create_subid == mySubid)
3190 : : {
3191 [ # # ]: 0 : if (isCommit)
3192 : 0 : allocatedDescs[i].create_subid = parentSubid;
3193 : : else
3194 : : {
3195 : : /* have to recheck the item after FreeDesc (ugly) */
3196 : 0 : FreeDesc(&allocatedDescs[i--]);
3197 : : }
3198 : : }
3199 : : }
3200 : 23017 : }
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 : 656112 : AtEOXact_Files(bool isCommit)
3216 : : {
3217 : 656112 : CleanupTempFiles(isCommit, false);
3218 : 656112 : tempTableSpaces = NULL;
3219 : 656112 : numTempTableSpaces = -1;
3220 : 656112 : }
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 : 26330 : BeforeShmemExit_Files(int code, Datum arg)
3230 : : {
3231 : 26330 : 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 : 26330 : }
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 : 682442 : CleanupTempFiles(bool isCommit, bool isProcExit)
3253 : : {
3254 : : Index i;
3255 : :
3256 : : /*
3257 : : * Careful here: at proc_exit we need extra cleanup, not just
3258 : : * xact_temporary files.
3259 : : */
3260 [ + + + + ]: 682442 : if (isProcExit || have_xact_temporary_files)
3261 : : {
3262 : : Assert(FileIsNotOpen(0)); /* Make sure ring not corrupted */
3263 [ + + ]: 1646999 : for (i = 1; i < SizeVfdCache; i++)
3264 : : {
3265 : 1619661 : unsigned short fdstate = VfdCache[i].fdstate;
3266 : :
3267 [ + + - + ]: 1619661 : if (((fdstate & FD_DELETE_AT_CLOSE) || (fdstate & FD_CLOSE_AT_EOXACT)) &&
3268 [ + - ]: 4 : VfdCache[i].fileName != NULL)
3269 : : {
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 [ + - ]: 4 : if (isProcExit)
3278 : 4 : FileClose(i);
3279 [ # # ]: 0 : else if (fdstate & FD_CLOSE_AT_EOXACT)
3280 : : {
3281 [ # # ]: 0 : elog(WARNING,
3282 : : "temporary file %s not closed at end-of-transaction",
3283 : : VfdCache[i].fileName);
3284 : 0 : FileClose(i);
3285 : : }
3286 : : }
3287 : : }
3288 : :
3289 : 27338 : have_xact_temporary_files = false;
3290 : : }
3291 : :
3292 : : /* Complain if any allocated files remain open at commit. */
3293 [ + + - + ]: 682442 : if (isCommit && numAllocatedDescs > 0)
3294 [ # # ]: 0 : elog(WARNING, "%d temporary files and directories not closed at end-of-transaction",
3295 : : numAllocatedDescs);
3296 : :
3297 : : /* Clean up "allocated" stdio files, dirs and fds. */
3298 [ + + ]: 682477 : while (numAllocatedDescs > 0)
3299 : 35 : FreeDesc(&allocatedDescs[0]);
3300 : 682442 : }
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 : 1073 : RemovePgTempFiles(void)
3325 : : {
3326 : : char temp_path[MAXPGPATH + sizeof(PG_TBLSPC_DIR) + sizeof(TABLESPACE_VERSION_DIRECTORY) + sizeof(PG_TEMP_FILES_DIR)];
3327 : : DIR *spc_dir;
3328 : : struct dirent *spc_de;
3329 : :
3330 : : /*
3331 : : * First process temp files in pg_default ($PGDATA/base)
3332 : : */
3333 : 1073 : snprintf(temp_path, sizeof(temp_path), "base/%s", PG_TEMP_FILES_DIR);
3334 : 1073 : RemovePgTempFilesInDir(temp_path, true, false);
3335 : 1073 : RemovePgTempRelationFiles("base");
3336 : :
3337 : : /*
3338 : : * Cycle through temp directories for all non-default tablespaces.
3339 : : */
3340 : 1073 : spc_dir = AllocateDir(PG_TBLSPC_DIR);
3341 : :
3342 [ + + ]: 3292 : while ((spc_de = ReadDirExtended(spc_dir, PG_TBLSPC_DIR, LOG)) != NULL)
3343 : : {
3344 [ + + ]: 2219 : if (strcmp(spc_de->d_name, ".") == 0 ||
3345 [ + + ]: 1146 : strcmp(spc_de->d_name, "..") == 0)
3346 : 2146 : continue;
3347 : :
3348 : 73 : snprintf(temp_path, sizeof(temp_path), "%s/%s/%s/%s",
3349 : 73 : PG_TBLSPC_DIR, spc_de->d_name, TABLESPACE_VERSION_DIRECTORY,
3350 : : PG_TEMP_FILES_DIR);
3351 : 73 : RemovePgTempFilesInDir(temp_path, true, false);
3352 : :
3353 : 73 : snprintf(temp_path, sizeof(temp_path), "%s/%s/%s",
3354 : 73 : PG_TBLSPC_DIR, spc_de->d_name, TABLESPACE_VERSION_DIRECTORY);
3355 : 73 : RemovePgTempRelationFiles(temp_path);
3356 : : }
3357 : :
3358 : 1073 : 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 : 1073 : }
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 : 1147 : 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 : 1147 : temp_dir = AllocateDir(tmpdirname);
3391 : :
3392 [ + + + - : 1147 : if (temp_dir == NULL && errno == ENOENT && missing_ok)
+ - ]
3393 : 1065 : return;
3394 : :
3395 [ + + ]: 249 : while ((temp_de = ReadDirExtended(temp_dir, tmpdirname, LOG)) != NULL)
3396 : : {
3397 [ + + ]: 167 : if (strcmp(temp_de->d_name, ".") == 0 ||
3398 [ + + ]: 85 : strcmp(temp_de->d_name, "..") == 0)
3399 : 164 : continue;
3400 : :
3401 : 3 : snprintf(rm_path, sizeof(rm_path), "%s/%s",
3402 : 3 : tmpdirname, temp_de->d_name);
3403 : :
3404 [ + - ]: 3 : if (unlink_all ||
3405 [ + - ]: 3 : strncmp(temp_de->d_name,
3406 : : PG_TEMP_FILE_PREFIX,
3407 : : strlen(PG_TEMP_FILE_PREFIX)) == 0)
3408 : 3 : {
3409 : 3 : PGFileType type = get_dirent_type(rm_path, temp_de, false, LOG);
3410 : :
3411 [ - + ]: 3 : if (type == PGFILETYPE_ERROR)
3412 : 0 : continue;
3413 [ + + ]: 3 : else if (type == PGFILETYPE_DIR)
3414 : : {
3415 : : /* recursively remove contents, then directory itself */
3416 : 1 : RemovePgTempFilesInDir(rm_path, false, true);
3417 : :
3418 [ - + ]: 1 : if (rmdir(rm_path) < 0)
3419 [ # # ]: 0 : ereport(LOG,
3420 : : (errcode_for_file_access(),
3421 : : errmsg("could not remove directory \"%s\": %m",
3422 : : rm_path)));
3423 : : }
3424 : : else
3425 : : {
3426 [ - + ]: 2 : if (unlink(rm_path) < 0)
3427 [ # # ]: 0 : ereport(LOG,
3428 : : (errcode_for_file_access(),
3429 : : errmsg("could not remove file \"%s\": %m",
3430 : : rm_path)));
3431 : : }
3432 : : }
3433 : : else
3434 [ # # ]: 0 : ereport(LOG,
3435 : : (errmsg("unexpected file found in temporary-files directory: \"%s\"",
3436 : : rm_path)));
3437 : : }
3438 : :
3439 : 82 : FreeDir(temp_dir);
3440 : : }
3441 : :
3442 : : /* Process one tablespace directory, look for per-DB subdirectories */
3443 : : static void
3444 : 1146 : RemovePgTempRelationFiles(const char *tsdirname)
3445 : : {
3446 : : DIR *ts_dir;
3447 : : struct dirent *de;
3448 : : char dbspace_path[MAXPGPATH * 2];
3449 : :
3450 : 1146 : ts_dir = AllocateDir(tsdirname);
3451 : :
3452 [ + + ]: 7195 : while ((de = ReadDirExtended(ts_dir, tsdirname, LOG)) != NULL)
3453 : : {
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 [ + + ]: 6049 : if (strspn(de->d_name, "0123456789") != strlen(de->d_name))
3460 : 2373 : continue;
3461 : :
3462 : 3676 : snprintf(dbspace_path, sizeof(dbspace_path), "%s/%s",
3463 : 3676 : tsdirname, de->d_name);
3464 : 3676 : RemovePgTempRelationFilesInDbspace(dbspace_path);
3465 : : }
3466 : :
3467 : 1146 : FreeDir(ts_dir);
3468 : 1146 : }
3469 : :
3470 : : /* Process one per-dbspace directory for RemovePgTempRelationFiles */
3471 : : static void
3472 : 3676 : RemovePgTempRelationFilesInDbspace(const char *dbspacedirname)
3473 : : {
3474 : : DIR *dbspace_dir;
3475 : : struct dirent *de;
3476 : : char rm_path[MAXPGPATH * 2];
3477 : :
3478 : 3676 : dbspace_dir = AllocateDir(dbspacedirname);
3479 : :
3480 [ + + ]: 1115370 : while ((de = ReadDirExtended(dbspace_dir, dbspacedirname, LOG)) != NULL)
3481 : : {
3482 [ + + ]: 1111694 : if (!looks_like_temp_rel_name(de->d_name))
3483 : 1111690 : continue;
3484 : :
3485 : 4 : snprintf(rm_path, sizeof(rm_path), "%s/%s",
3486 : 4 : dbspacedirname, de->d_name);
3487 : :
3488 [ - + ]: 4 : if (unlink(rm_path) < 0)
3489 [ # # ]: 0 : ereport(LOG,
3490 : : (errcode_for_file_access(),
3491 : : errmsg("could not remove file \"%s\": %m",
3492 : : rm_path)));
3493 : : }
3494 : :
3495 : 3676 : FreeDir(dbspace_dir);
3496 : 3676 : }
3497 : :
3498 : : /* t<digits>_<digits>, or t<digits>_<digits>_<forkname> */
3499 : : bool
3500 : 1473336 : looks_like_temp_rel_name(const char *name)
3501 : : {
3502 : : int pos;
3503 : : int savepos;
3504 : :
3505 : : /* Must start with "t". */
3506 [ + + ]: 1473336 : if (name[0] != 't')
3507 : 1473296 : return false;
3508 : :
3509 : : /* Followed by a non-empty string of digits and then an underscore. */
3510 [ + + ]: 196 : for (pos = 1; isdigit((unsigned char) name[pos]); ++pos)
3511 : : ;
3512 [ + - - + ]: 40 : if (pos == 1 || name[pos] != '_')
3513 : 0 : return false;
3514 : :
3515 : : /* Followed by another nonempty string of digits. */
3516 [ + + ]: 196 : for (savepos = ++pos; isdigit((unsigned char) name[pos]); ++pos)
3517 : : ;
3518 [ - + ]: 40 : if (savepos == pos)
3519 : 0 : return false;
3520 : :
3521 : : /* We might have _forkname or .segment or both. */
3522 [ + + ]: 40 : if (name[pos] == '_')
3523 : : {
3524 : 20 : int forkchar = forkname_chars(&name[pos + 1], NULL);
3525 : :
3526 [ - + ]: 20 : if (forkchar <= 0)
3527 : 0 : return false;
3528 : 20 : pos += forkchar + 1;
3529 : : }
3530 [ + + ]: 40 : if (name[pos] == '.')
3531 : : {
3532 : : int segchar;
3533 : :
3534 [ + + ]: 40 : for (segchar = 1; isdigit((unsigned char) name[pos + segchar]); ++segchar)
3535 : : ;
3536 [ - + ]: 20 : if (segchar <= 1)
3537 : 0 : return false;
3538 : 20 : pos += segchar;
3539 : : }
3540 : :
3541 : : /* Now we should be at the end. */
3542 [ - + ]: 40 : if (name[pos] != '\0')
3543 : 0 : return false;
3544 : 40 : return true;
3545 : : }
3546 : :
3547 : : #ifdef HAVE_SYNCFS
3548 : : static void
3549 : 0 : do_syncfs(const char *path)
3550 : : {
3551 : : int fd;
3552 : :
3553 [ # # # # ]: 0 : ereport_startup_progress("syncing data directory (syncfs), elapsed time: %ld.%02d s, current path: %s",
3554 : : path);
3555 : :
3556 : 0 : fd = OpenTransientFile(path, O_RDONLY);
3557 [ # # ]: 0 : if (fd < 0)
3558 : : {
3559 [ # # ]: 0 : ereport(LOG,
3560 : : (errcode_for_file_access(),
3561 : : errmsg("could not open file \"%s\": %m", path)));
3562 : 0 : return;
3563 : : }
3564 [ # # ]: 0 : if (syncfs(fd) < 0)
3565 [ # # ]: 0 : ereport(LOG,
3566 : : (errcode_for_file_access(),
3567 : : errmsg("could not synchronize file system for file \"%s\": %m", path)));
3568 : 0 : 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 : 217 : SyncDataDirectory(void)
3596 : : {
3597 : : bool xlog_is_symlink;
3598 : :
3599 : : /* We can skip this whole thing if fsync is disabled. */
3600 [ + - ]: 217 : if (!enableFsync)
3601 : 217 : 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 : : {
3610 : : struct stat st;
3611 : :
3612 [ # # ]: 0 : if (lstat("pg_wal", &st) < 0)
3613 [ # # ]: 0 : ereport(LOG,
3614 : : (errcode_for_file_access(),
3615 : : errmsg("could not stat file \"%s\": %m",
3616 : : "pg_wal")));
3617 [ # # ]: 0 : else if (S_ISLNK(st.st_mode))
3618 : 0 : xlog_is_symlink = true;
3619 : : }
3620 : :
3621 : : #ifdef HAVE_SYNCFS
3622 [ # # ]: 0 : if (recovery_init_sync_method == DATA_DIR_SYNC_METHOD_SYNCFS)
3623 : : {
3624 : : DIR *dir;
3625 : : 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 : : {
3644 : : 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 : : }
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 : : }
3658 : : #endif /* !HAVE_SYNCFS */
3659 : :
3660 : : #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 : : #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 : : }
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 : 265 : walkdir(const char *path,
3710 : : void (*action) (const char *fname, bool isdir, int elevel),
3711 : : bool process_symlinks,
3712 : : int elevel)
3713 : : {
3714 : : DIR *dir;
3715 : : struct dirent *de;
3716 : :
3717 : 265 : dir = AllocateDir(path);
3718 : :
3719 [ + + ]: 2730 : while ((de = ReadDirExtended(dir, path, elevel)) != NULL)
3720 : : {
3721 : : char subpath[MAXPGPATH * 2];
3722 : :
3723 [ + + ]: 2465 : CHECK_FOR_INTERRUPTS();
3724 : :
3725 [ + + ]: 2465 : if (strcmp(de->d_name, ".") == 0 ||
3726 [ + + ]: 2200 : strcmp(de->d_name, "..") == 0)
3727 : 530 : continue;
3728 : :
3729 : 1935 : snprintf(subpath, sizeof(subpath), "%s/%s", path, de->d_name);
3730 : :
3731 [ + - - ]: 1935 : switch (get_dirent_type(subpath, de, process_symlinks, elevel))
3732 : : {
3733 : 1935 : case PGFILETYPE_REG:
3734 : 1935 : (*action) (subpath, false, elevel);
3735 : 1935 : 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 : : }
3748 : : }
3749 : :
3750 : 265 : 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 [ + - ]: 265 : if (dir)
3759 : 265 : (*action) (path, true, elevel);
3760 : 265 : }
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 : 0 : pre_sync_fname(const char *fname, bool isdir, int elevel)
3773 : : {
3774 : : 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 : : fname);
3782 : :
3783 : 0 : fd = OpenTransientFile(fname, O_RDONLY | PG_BINARY);
3784 : :
3785 [ # # ]: 0 : if (fd < 0)
3786 : : {
3787 [ # # ]: 0 : if (errno == EACCES)
3788 : 0 : return;
3789 [ # # ]: 0 : ereport(elevel,
3790 : : (errcode_for_file_access(),
3791 : : errmsg("could not open file \"%s\": %m", fname)));
3792 : 0 : return;
3793 : : }
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 : : (errcode_for_file_access(),
3804 : : errmsg("could not close file \"%s\": %m", fname)));
3805 : : }
3806 : :
3807 : : #endif /* PG_FLUSH_DATA_WORKS */
3808 : :
3809 : : static void
3810 : 0 : datadir_fsync_fname(const char *fname, bool isdir, int elevel)
3811 : : {
3812 [ # # # # ]: 0 : 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 : 0 : fsync_fname_ext(fname, isdir, true, elevel);
3820 : 0 : }
3821 : :
3822 : : static void
3823 : 2200 : unlink_if_exists_fname(const char *fname, bool isdir, int elevel)
3824 : : {
3825 [ + + ]: 2200 : if (isdir)
3826 : : {
3827 [ - + - - ]: 265 : if (rmdir(fname) != 0 && errno != ENOENT)
3828 [ # # ]: 0 : ereport(elevel,
3829 : : (errcode_for_file_access(),
3830 : : errmsg("could not remove directory \"%s\": %m", fname)));
3831 : : }
3832 : : else
3833 : : {
3834 : : /* Use PathNameDeleteTemporaryFile to report filesize */
3835 : 1935 : PathNameDeleteTemporaryFile(fname, false);
3836 : : }
3837 : 2200 : }
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 : 48983 : fsync_fname_ext(const char *fname, bool isdir, bool ignore_perm, int elevel)
3849 : : {
3850 : : int fd;
3851 : : int flags;
3852 : : 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 : 48983 : flags = PG_BINARY;
3861 [ + + ]: 48983 : if (!isdir)
3862 : 18242 : flags |= O_RDWR;
3863 : : else
3864 : 30741 : flags |= O_RDONLY;
3865 : :
3866 : 48983 : 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 [ - + - - : 48983 : if (fd < 0 && isdir && (errno == EISDIR || errno == EACCES))
- - - - ]
3874 : 0 : return 0;
3875 [ - + - - : 48983 : else if (fd < 0 && ignore_perm && errno == EACCES)
- - ]
3876 : 0 : return 0;
3877 [ - + ]: 48983 : else if (fd < 0)
3878 : : {
3879 [ # # ]: 0 : ereport(elevel,
3880 : : (errcode_for_file_access(),
3881 : : errmsg("could not open file \"%s\": %m", fname)));
3882 : 0 : return -1;
3883 : : }
3884 : :
3885 : 48983 : 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 [ - + - - : 48983 : if (returncode != 0 && !(isdir && (errno == EBADF || errno == EINVAL)))
- - - - ]
3892 : : {
3893 : : 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 : : (errcode_for_file_access(),
3902 : : errmsg("could not fsync file \"%s\": %m", fname)));
3903 : 0 : return -1;
3904 : : }
3905 : :
3906 [ - + ]: 48983 : if (CloseTransientFile(fd) != 0)
3907 : : {
3908 [ # # ]: 0 : ereport(elevel,
3909 : : (errcode_for_file_access(),
3910 : : errmsg("could not close file \"%s\": %m", fname)));
3911 : 0 : return -1;
3912 : : }
3913 : :
3914 : 48983 : return 0;
3915 : : }
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 : 8693 : fsync_parent_path(const char *fname, int elevel)
3925 : : {
3926 : : char parentpath[MAXPGPATH];
3927 : :
3928 : 8693 : strlcpy(parentpath, fname, MAXPGPATH);
3929 : 8693 : 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 [ + + ]: 8693 : if (strlen(parentpath) == 0)
3937 : 272 : strlcpy(parentpath, ".", MAXPGPATH);
3938 : :
3939 [ - + ]: 8693 : if (fsync_fname_ext(parentpath, true, false, elevel) != 0)
3940 : 0 : return -1;
3941 : :
3942 : 8693 : return 0;
3943 : : }
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 : 1859 : MakePGDirectory(const char *directoryName)
3965 : : {
3966 : 1859 : return mkdir(directoryName, pg_dir_create_mode);
3967 : : }
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 : 25492 : data_sync_elevel(int elevel)
3988 : : {
3989 [ - + ]: 25492 : return data_sync_retry ? elevel : PANIC;
3990 : : }
3991 : :
3992 : : bool
3993 : 1378 : check_debug_io_direct(char **newval, void **extra, GucSource source)
3994 : : {
3995 : 1378 : bool result = true;
3996 : : 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 : : List *elemlist;
4008 : : ListCell *l;
4009 : : char *rawstring;
4010 : :
4011 : : /* Need a modifiable copy of string */
4012 : 1378 : rawstring = pstrdup(*newval);
4013 : :
4014 [ - + ]: 1378 : if (!SplitGUCList(rawstring, ',', &elemlist))
4015 : : {
4016 : 0 : GUC_check_errdetail("Invalid list syntax in parameter \"%s\".",
4017 : : "debug_io_direct");
4018 : 0 : pfree(rawstring);
4019 : 0 : list_free(elemlist);
4020 : 0 : return false;
4021 : : }
4022 : :
4023 : 1378 : flags = 0;
4024 [ + + + + : 1384 : foreach(l, elemlist)
+ + ]
4025 : : {
4026 : 6 : char *item = (char *) lfirst(l);
4027 : :
4028 [ + + ]: 6 : if (pg_strcasecmp(item, "data") == 0)
4029 : 2 : flags |= IO_DIRECT_DATA;
4030 [ + + ]: 4 : else if (pg_strcasecmp(item, "wal") == 0)
4031 : 2 : flags |= IO_DIRECT_WAL;
4032 [ + - ]: 2 : else if (pg_strcasecmp(item, "wal_init") == 0)
4033 : 2 : flags |= IO_DIRECT_WAL_INIT;
4034 : : else
4035 : : {
4036 : 0 : GUC_check_errdetail("Invalid option \"%s\".", item);
4037 : 0 : result = false;
4038 : 0 : break;
4039 : : }
4040 : : }
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 : 1378 : pfree(rawstring);
4064 : 1378 : list_free(elemlist);
4065 : : #endif
4066 : :
4067 [ - + ]: 1378 : if (!result)
4068 : 0 : return result;
4069 : :
4070 : : /* Save the flags in *extra, for use by assign_debug_io_direct */
4071 : 1378 : *extra = guc_malloc(LOG, sizeof(int));
4072 [ - + ]: 1378 : if (!*extra)
4073 : 0 : return false;
4074 : 1378 : *((int *) *extra) = flags;
4075 : :
4076 : 1378 : return result;
4077 : : }
4078 : :
4079 : : void
4080 : 1378 : assign_debug_io_direct(const char *newval, void *extra)
4081 : : {
4082 : 1378 : int *flags = (int *) extra;
4083 : :
4084 : 1378 : io_direct_flags = *flags;
4085 : 1378 : }
4086 : :
4087 : : /* ResourceOwner callbacks */
4088 : :
4089 : : static void
4090 : 5 : ResOwnerReleaseFile(Datum res)
4091 : : {
4092 : 5 : File file = (File) DatumGetInt32(res);
4093 : : Vfd *vfdP;
4094 : :
4095 : : Assert(FileIsValid(file));
4096 : :
4097 : 5 : vfdP = &VfdCache[file];
4098 : 5 : vfdP->resowner = NULL;
4099 : :
4100 : 5 : FileClose(file);
4101 : 5 : }
4102 : :
4103 : : static char *
4104 : 0 : ResOwnerPrintFile(Datum res)
4105 : : {
4106 : 0 : return psprintf("File %d", DatumGetInt32(res));
4107 : : }
|