1 /*-------------------------------------------------------------------------
4 * Virtual file descriptor code.
6 * Portions Copyright (c) 1996-2011, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
10 * src/backend/storage/file/fd.c
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 256 on many modern
20 * operating systems, but can be as low as 32 on others.)
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
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.
33 * This file used to contain a bunch of stuff to support RAID levels 0
34 * (jbod), 1 (duplex) and 5 (xor parity). That stuff is all gone
35 * because the parallel query processing code that called it is all
36 * gone. If you really need it you could get it from the original
38 *-------------------------------------------------------------------------
44 #include <sys/param.h>
48 #ifdef HAVE_SYS_RESOURCE_H
49 #include <sys/resource.h> /* for getrlimit */
52 #include "miscadmin.h"
53 #include "access/xact.h"
54 #include "catalog/catalog.h"
55 #include "catalog/pg_tablespace.h"
56 #include "storage/fd.h"
57 #include "storage/ipc.h"
58 #include "utils/guc.h"
59 #include "utils/resowner.h"
63 * We must leave some file descriptors free for system(), the dynamic loader,
64 * and other code that tries to open files without consulting fd.c. This
65 * is the number left free. (While we can be pretty sure we won't get
66 * EMFILE, there's never any guarantee that we won't get ENFILE due to
67 * other processes chewing up FDs. So it's a bad idea to try to open files
68 * without consulting fd.c. Nonetheless we cannot control all code.)
70 * Because this is just a fixed setting, we are effectively assuming that
71 * no such code will leave FDs open over the long term; otherwise the slop
72 * is likely to be insufficient. Note in particular that we expect that
73 * loading a shared library does not result in any permanent increase in
74 * the number of open files. (This appears to be true on most if not
75 * all platforms as of Feb 2004.)
77 #define NUM_RESERVED_FDS 10
80 * If we have fewer than this many usable FDs after allowing for the reserved
87 * A number of platforms allow individual processes to open many more files
88 * than they can really support when *many* processes do the same thing.
89 * This GUC parameter lets the DBA limit max_safe_fds to something less than
90 * what the postmaster's initial probe suggests will work.
92 int max_files_per_process = 1000;
95 * Maximum number of file descriptors to open for either VFD entries or
96 * AllocateFile/AllocateDir operations. This is initialized to a conservative
97 * value, and remains that way indefinitely in bootstrap or standalone-backend
98 * cases. In normal postmaster operation, the postmaster calls
99 * set_max_safe_fds() late in initialization to update the value, and that
100 * value is then inherited by forked subprocesses.
102 * Note: the value of max_files_per_process is taken into account while
103 * setting this variable, and so need not be tested separately.
105 static int max_safe_fds = 32; /* default if not changed */
113 #define DO_DB(A) /* A */
116 #define VFD_CLOSED (-1)
118 #define FileIsValid(file) \
119 ((file) > 0 && (file) < (int) SizeVfdCache && VfdCache[file].fileName != NULL)
121 #define FileIsNotOpen(file) (VfdCache[file].fd == VFD_CLOSED)
123 #define FileUnknownPos ((off_t) -1)
125 /* these are the assigned bits in fdstate below: */
126 #define FD_TEMPORARY (1 << 0) /* T = delete when closed */
127 #define FD_XACT_TEMPORARY (1 << 1) /* T = delete at eoXact */
130 * Flag to tell whether it's worth scanning VfdCache looking for temp files to
133 static bool have_xact_temporary_files = false;
137 int fd; /* current FD, or VFD_CLOSED if none */
138 unsigned short fdstate; /* bitflags for VFD's state */
139 ResourceOwner resowner; /* owner, for automatic cleanup */
140 File nextFree; /* link to next free VFD, if in freelist */
141 File lruMoreRecently; /* doubly linked recency-of-use list */
142 File lruLessRecently;
143 off_t seekPos; /* current logical file position */
144 char *fileName; /* name of file, or NULL for unused VFD */
145 /* NB: fileName is malloc'd, and must be free'd when closing the VFD */
146 int fileFlags; /* open(2) flags for (re)opening the file */
147 int fileMode; /* mode to pass to open(2) */
151 * Virtual File Descriptor array pointer and size. This grows as
152 * needed. 'File' values are indexes into this array.
153 * Note that VfdCache[0] is not a usable VFD, just a list header.
155 static Vfd *VfdCache;
156 static Size SizeVfdCache = 0;
159 * Number of file descriptors known to be in use by VFD entries.
161 static int nfile = 0;
164 * List of stdio FILEs and <dirent.h> DIRs opened with AllocateFile
167 * Since we don't want to encourage heavy use of AllocateFile or AllocateDir,
168 * it seems OK to put a pretty small maximum limit on the number of
169 * simultaneously allocated descs.
171 #define MAX_ALLOCATED_DESCS 32
181 AllocateDescKind kind;
187 SubTransactionId create_subid;
190 static int numAllocatedDescs = 0;
191 static AllocateDesc allocatedDescs[MAX_ALLOCATED_DESCS];
194 * Number of temporary files opened during the current session;
195 * this is used in generation of tempfile names.
197 static long tempFileCounter = 0;
200 * Array of OIDs of temp tablespaces. When numTempTableSpaces is -1,
201 * this has not been set in the current transaction.
203 static Oid *tempTableSpaces = NULL;
204 static int numTempTableSpaces = -1;
205 static int nextTempTableSpace = 0;
208 /*--------------------
212 * Delete - delete a file from the Lru ring
213 * LruDelete - remove a file from the Lru ring and close its FD
214 * Insert - put a file at the front of the Lru ring
215 * LruInsert - put a file at the front of the Lru ring and open it
216 * ReleaseLruFile - Release an fd by closing the last entry in the Lru ring
217 * AllocateVfd - grab a free (or new) file record (from VfdArray)
218 * FreeVfd - free a file record
220 * The Least Recently Used ring is a doubly linked list that begins and
221 * ends on element zero. Element zero is special -- it doesn't represent
222 * a file and its "fd" field always == VFD_CLOSED. Element zero is just an
223 * anchor that shows us the beginning/end of the ring.
224 * Only VFD elements that are currently really open (have an FD assigned) are
225 * in the Lru ring. Elements that are "virtually" open can be recognized
226 * by having a non-null fileName field.
230 * /--less----\ /---------\
232 * #0 --more---> LeastRecentlyUsed --more-\ \
234 * \\less--> MostRecentlyUsedFile <---/ |
235 * \more---/ \--less--/
237 *--------------------
239 static void Delete(File file);
240 static void LruDelete(File file);
241 static void Insert(File file);
242 static int LruInsert(File file);
243 static bool ReleaseLruFile(void);
244 static File AllocateVfd(void);
245 static void FreeVfd(File file);
247 static int FileAccess(File file);
248 static File OpenTemporaryFileInTablespace(Oid tblspcOid, bool rejectError);
249 static void AtProcExit_Files(int code, Datum arg);
250 static void CleanupTempFiles(bool isProcExit);
251 static void RemovePgTempFilesInDir(const char *tmpdirname);
252 static void RemovePgTempRelationFiles(const char *tsdirname);
253 static void RemovePgTempRelationFilesInDbspace(const char *dbspacedirname);
254 static bool looks_like_temp_rel_name(const char *name);
258 * pg_fsync --- do fsync with or without writethrough
263 /* #if is to skip the sync_method test if there's no need for it */
264 #if defined(HAVE_FSYNC_WRITETHROUGH) && !defined(FSYNC_WRITETHROUGH_IS_FSYNC)
265 if (sync_method == SYNC_METHOD_FSYNC_WRITETHROUGH)
266 return pg_fsync_writethrough(fd);
269 return pg_fsync_no_writethrough(fd);
274 * pg_fsync_no_writethrough --- same as fsync except does nothing if
278 pg_fsync_no_writethrough(int fd)
287 * pg_fsync_writethrough
290 pg_fsync_writethrough(int fd)
296 #elif defined(F_FULLFSYNC)
297 return (fcntl(fd, F_FULLFSYNC, 0) == -1) ? -1 : 0;
308 * pg_fdatasync --- same as fdatasync except does nothing if enableFsync is off
310 * Not all platforms have fdatasync; treat as fsync if not available.
317 #ifdef HAVE_FDATASYNC
318 return fdatasync(fd);
328 * pg_flush_data --- advise OS that the data described won't be needed soon
330 * Not all platforms have posix_fadvise; treat as noop if not available.
333 pg_flush_data(int fd, off_t offset, off_t amount)
335 #if defined(USE_POSIX_FADVISE) && defined(POSIX_FADV_DONTNEED)
336 return posix_fadvise(fd, offset, amount, POSIX_FADV_DONTNEED);
344 * InitFileAccess --- initialize this module during backend startup
346 * This is called during either normal or standalone backend start.
347 * It is *not* called in the postmaster.
352 Assert(SizeVfdCache == 0); /* call me only once */
354 /* initialize cache header entry */
355 VfdCache = (Vfd *) malloc(sizeof(Vfd));
356 if (VfdCache == NULL)
358 (errcode(ERRCODE_OUT_OF_MEMORY),
359 errmsg("out of memory")));
361 MemSet((char *) &(VfdCache[0]), 0, sizeof(Vfd));
362 VfdCache->fd = VFD_CLOSED;
366 /* register proc-exit hook to ensure temp files are dropped at exit */
367 on_proc_exit(AtProcExit_Files, 0);
371 * count_usable_fds --- count how many FDs the system will let us open,
372 * and estimate how many are already open.
374 * We stop counting if usable_fds reaches max_to_probe. Note: a small
375 * value of max_to_probe might result in an underestimate of already_open;
376 * we must fill in any "gaps" in the set of used FDs before the calculation
377 * of already_open will give the right answer. In practice, max_to_probe
378 * of a couple of dozen should be enough to ensure good results.
380 * We assume stdin (FD 0) is available for dup'ing
383 count_usable_fds(int max_to_probe, int *usable_fds, int *already_open)
391 #ifdef HAVE_GETRLIMIT
393 int getrlimit_status;
397 fd = (int *) palloc(size * sizeof(int));
399 #ifdef HAVE_GETRLIMIT
400 #ifdef RLIMIT_NOFILE /* most platforms use RLIMIT_NOFILE */
401 getrlimit_status = getrlimit(RLIMIT_NOFILE, &rlim);
402 #else /* but BSD doesn't ... */
403 getrlimit_status = getrlimit(RLIMIT_OFILE, &rlim);
404 #endif /* RLIMIT_NOFILE */
405 if (getrlimit_status != 0)
406 ereport(WARNING, (errmsg("getrlimit failed: %m")));
407 #endif /* HAVE_GETRLIMIT */
409 /* dup until failure or probe limit reached */
414 #ifdef HAVE_GETRLIMIT
417 * don't go beyond RLIMIT_NOFILE; causes irritating kernel logs on
420 if (getrlimit_status == 0 && highestfd >= rlim.rlim_cur - 1)
427 /* Expect EMFILE or ENFILE, else it's fishy */
428 if (errno != EMFILE && errno != ENFILE)
429 elog(WARNING, "dup(0) failed after %d successes: %m", used);
436 fd = (int *) repalloc(fd, size * sizeof(int));
440 if (highestfd < thisfd)
443 if (used >= max_to_probe)
447 /* release the files we opened */
448 for (j = 0; j < used; j++)
454 * Return results. usable_fds is just the number of successful dups. We
455 * assume that the system limit is highestfd+1 (remember 0 is a legal FD
456 * number) and so already_open is highestfd+1 - usable_fds.
459 *already_open = highestfd + 1 - used;
464 * Determine number of filedescriptors that fd.c is allowed to use
467 set_max_safe_fds(void)
473 * We want to set max_safe_fds to
474 * MIN(usable_fds, max_files_per_process - already_open)
475 * less the slop factor for files that are opened without consulting
476 * fd.c. This ensures that we won't exceed either max_files_per_process
477 * or the experimentally-determined EMFILE limit.
480 count_usable_fds(max_files_per_process,
481 &usable_fds, &already_open);
483 max_safe_fds = Min(usable_fds, max_files_per_process - already_open);
486 * Take off the FDs reserved for system() etc.
488 max_safe_fds -= NUM_RESERVED_FDS;
491 * Make sure we still have enough to get by.
493 if (max_safe_fds < FD_MINFREE)
495 (errcode(ERRCODE_INSUFFICIENT_RESOURCES),
496 errmsg("insufficient file descriptors available to start server process"),
497 errdetail("System allows %d, we need at least %d.",
498 max_safe_fds + NUM_RESERVED_FDS,
499 FD_MINFREE + NUM_RESERVED_FDS)));
501 elog(DEBUG2, "max_safe_fds = %d, usable_fds = %d, already_open = %d",
502 max_safe_fds, usable_fds, already_open);
506 * BasicOpenFile --- same as open(2) except can free other FDs if needed
508 * This is exported for use by places that really want a plain kernel FD,
509 * but need to be proof against running out of FDs. Once an FD has been
510 * successfully returned, it is the caller's responsibility to ensure that
511 * it will not be leaked on ereport()! Most users should *not* call this
512 * routine directly, but instead use the VFD abstraction level, which
513 * provides protection against descriptor leaks as well as management of
514 * files that need to be open for more than a short period of time.
516 * Ideally this should be the *only* direct call of open() in the backend.
517 * In practice, the postmaster calls open() directly, and there are some
518 * direct open() calls done early in backend startup. Those are OK since
519 * this module wouldn't have any open files to close at that point anyway.
522 BasicOpenFile(FileName fileName, int fileFlags, int fileMode)
527 fd = open(fileName, fileFlags, fileMode);
530 return fd; /* success! */
532 if (errno == EMFILE || errno == ENFILE)
534 int save_errno = errno;
537 (errcode(ERRCODE_INSUFFICIENT_RESOURCES),
538 errmsg("out of file descriptors: %m; release and retry")));
540 if (ReleaseLruFile())
545 return -1; /* failure */
553 int mru = VfdCache[0].lruLessRecently;
554 Vfd *vfdP = &VfdCache[mru];
557 snprintf(buf, sizeof(buf), "LRU: MOST %d ", mru);
560 mru = vfdP->lruLessRecently;
561 vfdP = &VfdCache[mru];
562 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%d ", mru);
564 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "LEAST");
565 elog(LOG, "%s", buf);
576 DO_DB(elog(LOG, "Delete %d (%s)",
577 file, VfdCache[file].fileName));
580 vfdP = &VfdCache[file];
582 VfdCache[vfdP->lruLessRecently].lruMoreRecently = vfdP->lruMoreRecently;
583 VfdCache[vfdP->lruMoreRecently].lruLessRecently = vfdP->lruLessRecently;
595 DO_DB(elog(LOG, "LruDelete %d (%s)",
596 file, VfdCache[file].fileName));
598 vfdP = &VfdCache[file];
600 /* delete the vfd record from the LRU ring */
603 /* save the seek position */
604 vfdP->seekPos = lseek(vfdP->fd, (off_t) 0, SEEK_CUR);
605 Assert(vfdP->seekPos != (off_t) -1);
609 elog(ERROR, "could not close file \"%s\": %m", vfdP->fileName);
612 vfdP->fd = VFD_CLOSED;
622 DO_DB(elog(LOG, "Insert %d (%s)",
623 file, VfdCache[file].fileName));
626 vfdP = &VfdCache[file];
628 vfdP->lruMoreRecently = 0;
629 vfdP->lruLessRecently = VfdCache[0].lruLessRecently;
630 VfdCache[0].lruLessRecently = file;
631 VfdCache[vfdP->lruLessRecently].lruMoreRecently = file;
636 /* returns 0 on success, -1 on re-open failure (with errno set) */
644 DO_DB(elog(LOG, "LruInsert %d (%s)",
645 file, VfdCache[file].fileName));
647 vfdP = &VfdCache[file];
649 if (FileIsNotOpen(file))
651 while (nfile + numAllocatedDescs >= max_safe_fds)
653 if (!ReleaseLruFile())
658 * The open could still fail for lack of file descriptors, eg due to
659 * overall system file table being full. So, be prepared to release
660 * another FD if necessary...
662 vfdP->fd = BasicOpenFile(vfdP->fileName, vfdP->fileFlags,
666 DO_DB(elog(LOG, "RE_OPEN FAILED: %d", errno));
671 DO_DB(elog(LOG, "RE_OPEN SUCCESS"));
675 /* seek to the right position */
676 if (vfdP->seekPos != (off_t) 0)
680 returnValue = lseek(vfdP->fd, vfdP->seekPos, SEEK_SET);
681 Assert(returnValue != (off_t) -1);
686 * put it at the head of the Lru ring
697 DO_DB(elog(LOG, "ReleaseLruFile. Opened %d", nfile));
702 * There are opened files and so there should be at least one used vfd
705 Assert(VfdCache[0].lruMoreRecently != 0);
706 LruDelete(VfdCache[0].lruMoreRecently);
707 return true; /* freed a file */
709 return false; /* no files available to free */
718 DO_DB(elog(LOG, "AllocateVfd. Size %lu", SizeVfdCache));
720 Assert(SizeVfdCache > 0); /* InitFileAccess not called? */
722 if (VfdCache[0].nextFree == 0)
725 * The free list is empty so it is time to increase the size of the
726 * array. We choose to double it each time this happens. However,
727 * there's not much point in starting *real* small.
729 Size newCacheSize = SizeVfdCache * 2;
732 if (newCacheSize < 32)
736 * Be careful not to clobber VfdCache ptr if realloc fails.
738 newVfdCache = (Vfd *) realloc(VfdCache, sizeof(Vfd) * newCacheSize);
739 if (newVfdCache == NULL)
741 (errcode(ERRCODE_OUT_OF_MEMORY),
742 errmsg("out of memory")));
743 VfdCache = newVfdCache;
746 * Initialize the new entries and link them into the free list.
748 for (i = SizeVfdCache; i < newCacheSize; i++)
750 MemSet((char *) &(VfdCache[i]), 0, sizeof(Vfd));
751 VfdCache[i].nextFree = i + 1;
752 VfdCache[i].fd = VFD_CLOSED;
754 VfdCache[newCacheSize - 1].nextFree = 0;
755 VfdCache[0].nextFree = SizeVfdCache;
758 * Record the new size
760 SizeVfdCache = newCacheSize;
763 file = VfdCache[0].nextFree;
765 VfdCache[0].nextFree = VfdCache[file].nextFree;
773 Vfd *vfdP = &VfdCache[file];
775 DO_DB(elog(LOG, "FreeVfd: %d (%s)",
776 file, vfdP->fileName ? vfdP->fileName : ""));
778 if (vfdP->fileName != NULL)
780 free(vfdP->fileName);
781 vfdP->fileName = NULL;
785 vfdP->nextFree = VfdCache[0].nextFree;
786 VfdCache[0].nextFree = file;
789 /* returns 0 on success, -1 on re-open failure (with errno set) */
791 FileAccess(File file)
795 DO_DB(elog(LOG, "FileAccess %d (%s)",
796 file, VfdCache[file].fileName));
799 * Is the file open? If not, open it and put it at the head of the LRU
800 * ring (possibly closing the least recently used file to get an FD).
803 if (FileIsNotOpen(file))
805 returnValue = LruInsert(file);
806 if (returnValue != 0)
809 else if (VfdCache[0].lruLessRecently != file)
812 * We now know that the file is open and that it is not the last one
813 * accessed, so we need to move it to the head of the Lru ring.
824 * Called when we get a shared invalidation message on some relation.
828 FileInvalidate(File file)
830 Assert(FileIsValid(file));
831 if (!FileIsNotOpen(file))
837 * open a file in an arbitrary directory
839 * NB: if the passed pathname is relative (which it usually is),
840 * it will be interpreted relative to the process' working directory
841 * (which should always be $PGDATA when this code is running).
844 PathNameOpenFile(FileName fileName, int fileFlags, int fileMode)
850 DO_DB(elog(LOG, "PathNameOpenFile: %s %x %o",
851 fileName, fileFlags, fileMode));
854 * We need a malloc'd copy of the file name; fail cleanly if no room.
856 fnamecopy = strdup(fileName);
857 if (fnamecopy == NULL)
859 (errcode(ERRCODE_OUT_OF_MEMORY),
860 errmsg("out of memory")));
862 file = AllocateVfd();
863 vfdP = &VfdCache[file];
865 while (nfile + numAllocatedDescs >= max_safe_fds)
867 if (!ReleaseLruFile())
871 vfdP->fd = BasicOpenFile(fileName, fileFlags, fileMode);
880 DO_DB(elog(LOG, "PathNameOpenFile: success %d",
885 vfdP->fileName = fnamecopy;
886 /* Saved flags are adjusted to be OK for re-opening file */
887 vfdP->fileFlags = fileFlags & ~(O_CREAT | O_TRUNC | O_EXCL);
888 vfdP->fileMode = fileMode;
891 vfdP->resowner = NULL;
897 * Open a temporary file that will disappear when we close it.
899 * This routine takes care of generating an appropriate tempfile name.
900 * There's no need to pass in fileFlags or fileMode either, since only
901 * one setting makes any sense for a temp file.
903 * Unless interXact is true, the file is remembered by CurrentResourceOwner
904 * to ensure it's closed and deleted when it's no longer needed, typically at
905 * the end-of-transaction. In most cases, you don't want temporary files to
906 * outlive the transaction that created them, so this should be false -- but
907 * if you need "somewhat" temporary storage, this might be useful. In either
908 * case, the file is removed when the File is explicitly closed.
911 OpenTemporaryFile(bool interXact)
916 * If some temp tablespace(s) have been given to us, try to use the next
917 * one. If a given tablespace can't be found, we silently fall back to
918 * the database's default tablespace.
920 * BUT: if the temp file is slated to outlive the current transaction,
921 * force it into the database's default tablespace, so that it will not
922 * pose a threat to possible tablespace drop attempts.
924 if (numTempTableSpaces > 0 && !interXact)
926 Oid tblspcOid = GetNextTempTableSpace();
928 if (OidIsValid(tblspcOid))
929 file = OpenTemporaryFileInTablespace(tblspcOid, false);
933 * If not, or if tablespace is bad, create in database's default
934 * tablespace. MyDatabaseTableSpace should normally be set before we get
935 * here, but just in case it isn't, fall back to pg_default tablespace.
938 file = OpenTemporaryFileInTablespace(MyDatabaseTableSpace ?
939 MyDatabaseTableSpace :
940 DEFAULTTABLESPACE_OID,
943 /* Mark it for deletion at close */
944 VfdCache[file].fdstate |= FD_TEMPORARY;
946 /* Register it with the current resource owner */
949 VfdCache[file].fdstate |= FD_XACT_TEMPORARY;
951 ResourceOwnerEnlargeFiles(CurrentResourceOwner);
952 ResourceOwnerRememberFile(CurrentResourceOwner, file);
953 VfdCache[file].resowner = CurrentResourceOwner;
955 /* ensure cleanup happens at eoxact */
956 have_xact_temporary_files = true;
963 * Open a temporary file in a specific tablespace.
964 * Subroutine for OpenTemporaryFile, which see for details.
967 OpenTemporaryFileInTablespace(Oid tblspcOid, bool rejectError)
969 char tempdirpath[MAXPGPATH];
970 char tempfilepath[MAXPGPATH];
974 * Identify the tempfile directory for this tablespace.
976 * If someone tries to specify pg_global, use pg_default instead.
978 if (tblspcOid == DEFAULTTABLESPACE_OID ||
979 tblspcOid == GLOBALTABLESPACE_OID)
981 /* The default tablespace is {datadir}/base */
982 snprintf(tempdirpath, sizeof(tempdirpath), "base/%s",
987 /* All other tablespaces are accessed via symlinks */
988 snprintf(tempdirpath, sizeof(tempdirpath), "pg_tblspc/%u/%s/%s",
989 tblspcOid, TABLESPACE_VERSION_DIRECTORY, PG_TEMP_FILES_DIR);
993 * Generate a tempfile name that should be unique within the current
996 snprintf(tempfilepath, sizeof(tempfilepath), "%s/%s%d.%ld",
997 tempdirpath, PG_TEMP_FILE_PREFIX, MyProcPid, tempFileCounter++);
1000 * Open the file. Note: we don't use O_EXCL, in case there is an orphaned
1001 * temp file that can be reused.
1003 file = PathNameOpenFile(tempfilepath,
1004 O_RDWR | O_CREAT | O_TRUNC | PG_BINARY,
1009 * We might need to create the tablespace's tempfile directory, if no
1010 * one has yet done so.
1012 * Don't check for error from mkdir; it could fail if someone else
1013 * just did the same thing. If it doesn't work then we'll bomb out on
1014 * the second create attempt, instead.
1016 mkdir(tempdirpath, S_IRWXU);
1018 file = PathNameOpenFile(tempfilepath,
1019 O_RDWR | O_CREAT | O_TRUNC | PG_BINARY,
1021 if (file <= 0 && rejectError)
1022 elog(ERROR, "could not create temporary file \"%s\": %m",
1030 * close a file when done with it
1033 FileClose(File file)
1037 Assert(FileIsValid(file));
1039 DO_DB(elog(LOG, "FileClose: %d (%s)",
1040 file, VfdCache[file].fileName));
1042 vfdP = &VfdCache[file];
1044 if (!FileIsNotOpen(file))
1046 /* remove the file from the lru ring */
1049 /* close the file */
1050 if (close(vfdP->fd))
1051 elog(ERROR, "could not close file \"%s\": %m", vfdP->fileName);
1054 vfdP->fd = VFD_CLOSED;
1058 * Delete the file if it was temporary, and make a log entry if wanted
1060 if (vfdP->fdstate & FD_TEMPORARY)
1063 * If we get an error, as could happen within the ereport/elog calls,
1064 * we'll come right back here during transaction abort. Reset the
1065 * flag to ensure that we can't get into an infinite loop. This code
1066 * is arranged to ensure that the worst-case consequence is failing to
1067 * emit log message(s), not failing to attempt the unlink.
1069 vfdP->fdstate &= ~FD_TEMPORARY;
1071 if (log_temp_files >= 0)
1073 struct stat filestats;
1076 /* first try the stat() */
1077 if (stat(vfdP->fileName, &filestats))
1082 /* in any case do the unlink */
1083 if (unlink(vfdP->fileName))
1084 elog(LOG, "could not unlink file \"%s\": %m", vfdP->fileName);
1086 /* and last report the stat results */
1087 if (stat_errno == 0)
1089 if ((filestats.st_size / 1024) >= log_temp_files)
1091 (errmsg("temporary file: path \"%s\", size %lu",
1093 (unsigned long) filestats.st_size)));
1098 elog(LOG, "could not stat file \"%s\": %m", vfdP->fileName);
1103 /* easy case, just do the unlink */
1104 if (unlink(vfdP->fileName))
1105 elog(LOG, "could not unlink file \"%s\": %m", vfdP->fileName);
1109 /* Unregister it from the resource owner */
1111 ResourceOwnerForgetFile(vfdP->resowner, file);
1114 * Return the Vfd slot to the free list
1120 * FilePrefetch - initiate asynchronous read of a given range of the file.
1121 * The logical seek position is unaffected.
1123 * Currently the only implementation of this function is using posix_fadvise
1124 * which is the simplest standardized interface that accomplishes this.
1125 * We could add an implementation using libaio in the future; but note that
1126 * this API is inappropriate for libaio, which wants to have a buffer provided
1130 FilePrefetch(File file, off_t offset, int amount)
1132 #if defined(USE_POSIX_FADVISE) && defined(POSIX_FADV_WILLNEED)
1135 Assert(FileIsValid(file));
1137 DO_DB(elog(LOG, "FilePrefetch: %d (%s) " INT64_FORMAT " %d",
1138 file, VfdCache[file].fileName,
1139 (int64) offset, amount));
1141 returnCode = FileAccess(file);
1145 returnCode = posix_fadvise(VfdCache[file].fd, offset, amount,
1146 POSIX_FADV_WILLNEED);
1150 Assert(FileIsValid(file));
1156 FileRead(File file, char *buffer, int amount)
1160 Assert(FileIsValid(file));
1162 DO_DB(elog(LOG, "FileRead: %d (%s) " INT64_FORMAT " %d %p",
1163 file, VfdCache[file].fileName,
1164 (int64) VfdCache[file].seekPos,
1167 returnCode = FileAccess(file);
1172 returnCode = read(VfdCache[file].fd, buffer, amount);
1174 if (returnCode >= 0)
1175 VfdCache[file].seekPos += returnCode;
1179 * Windows may run out of kernel buffers and return "Insufficient
1180 * system resources" error. Wait a bit and retry to solve it.
1182 * It is rumored that EINTR is also possible on some Unix filesystems,
1183 * in which case immediate retry is indicated.
1186 DWORD error = GetLastError();
1190 case ERROR_NO_SYSTEM_RESOURCES:
1199 /* OK to retry if interrupted */
1203 /* Trouble, so assume we don't know the file position anymore */
1204 VfdCache[file].seekPos = FileUnknownPos;
1211 FileWrite(File file, char *buffer, int amount)
1215 Assert(FileIsValid(file));
1217 DO_DB(elog(LOG, "FileWrite: %d (%s) " INT64_FORMAT " %d %p",
1218 file, VfdCache[file].fileName,
1219 (int64) VfdCache[file].seekPos,
1222 returnCode = FileAccess(file);
1228 returnCode = write(VfdCache[file].fd, buffer, amount);
1230 /* if write didn't set errno, assume problem is no disk space */
1231 if (returnCode != amount && errno == 0)
1234 if (returnCode >= 0)
1235 VfdCache[file].seekPos += returnCode;
1239 * See comments in FileRead()
1242 DWORD error = GetLastError();
1246 case ERROR_NO_SYSTEM_RESOURCES:
1255 /* OK to retry if interrupted */
1259 /* Trouble, so assume we don't know the file position anymore */
1260 VfdCache[file].seekPos = FileUnknownPos;
1271 Assert(FileIsValid(file));
1273 DO_DB(elog(LOG, "FileSync: %d (%s)",
1274 file, VfdCache[file].fileName));
1276 returnCode = FileAccess(file);
1280 return pg_fsync(VfdCache[file].fd);
1284 FileSeek(File file, off_t offset, int whence)
1288 Assert(FileIsValid(file));
1290 DO_DB(elog(LOG, "FileSeek: %d (%s) " INT64_FORMAT " " INT64_FORMAT " %d",
1291 file, VfdCache[file].fileName,
1292 (int64) VfdCache[file].seekPos,
1293 (int64) offset, whence));
1295 if (FileIsNotOpen(file))
1301 elog(ERROR, "invalid seek offset: " INT64_FORMAT,
1303 VfdCache[file].seekPos = offset;
1306 VfdCache[file].seekPos += offset;
1309 returnCode = FileAccess(file);
1312 VfdCache[file].seekPos = lseek(VfdCache[file].fd,
1316 elog(ERROR, "invalid whence: %d", whence);
1326 elog(ERROR, "invalid seek offset: " INT64_FORMAT,
1328 if (VfdCache[file].seekPos != offset)
1329 VfdCache[file].seekPos = lseek(VfdCache[file].fd,
1333 if (offset != 0 || VfdCache[file].seekPos == FileUnknownPos)
1334 VfdCache[file].seekPos = lseek(VfdCache[file].fd,
1338 VfdCache[file].seekPos = lseek(VfdCache[file].fd,
1342 elog(ERROR, "invalid whence: %d", whence);
1346 return VfdCache[file].seekPos;
1350 * XXX not actually used but here for completeness
1356 Assert(FileIsValid(file));
1357 DO_DB(elog(LOG, "FileTell %d (%s)",
1358 file, VfdCache[file].fileName));
1359 return VfdCache[file].seekPos;
1364 FileTruncate(File file, off_t offset)
1368 Assert(FileIsValid(file));
1370 DO_DB(elog(LOG, "FileTruncate %d (%s)",
1371 file, VfdCache[file].fileName));
1373 returnCode = FileAccess(file);
1377 returnCode = ftruncate(VfdCache[file].fd, offset);
1382 * Return the pathname associated with an open file.
1384 * The returned string points to an internal buffer, which is valid until
1385 * the file is closed.
1388 FilePathName(File file)
1390 Assert(FileIsValid(file));
1392 return VfdCache[file].fileName;
1397 * Routines that want to use stdio (ie, FILE*) should use AllocateFile
1398 * rather than plain fopen(). This lets fd.c deal with freeing FDs if
1399 * necessary to open the file. When done, call FreeFile rather than fclose.
1401 * Note that files that will be open for any significant length of time
1402 * should NOT be handled this way, since they cannot share kernel file
1403 * descriptors with other files; there is grave risk of running out of FDs
1404 * if anyone locks down too many FDs. Most callers of this routine are
1405 * simply reading a config file that they will read and close immediately.
1407 * fd.c will automatically close all files opened with AllocateFile at
1408 * transaction commit or abort; this prevents FD leakage if a routine
1409 * that calls AllocateFile is terminated prematurely by ereport(ERROR).
1411 * Ideally this should be the *only* direct call of fopen() in the backend.
1414 AllocateFile(const char *name, const char *mode)
1418 DO_DB(elog(LOG, "AllocateFile: Allocated %d (%s)",
1419 numAllocatedDescs, name));
1422 * The test against MAX_ALLOCATED_DESCS prevents us from overflowing
1423 * allocatedFiles[]; the test against max_safe_fds prevents AllocateFile
1424 * from hogging every one of the available FDs, which'd lead to infinite
1427 if (numAllocatedDescs >= MAX_ALLOCATED_DESCS ||
1428 numAllocatedDescs >= max_safe_fds - 1)
1429 elog(ERROR, "exceeded MAX_ALLOCATED_DESCS while trying to open file \"%s\"",
1433 if ((file = fopen(name, mode)) != NULL)
1435 AllocateDesc *desc = &allocatedDescs[numAllocatedDescs];
1437 desc->kind = AllocateDescFile;
1438 desc->desc.file = file;
1439 desc->create_subid = GetCurrentSubTransactionId();
1440 numAllocatedDescs++;
1441 return desc->desc.file;
1444 if (errno == EMFILE || errno == ENFILE)
1446 int save_errno = errno;
1449 (errcode(ERRCODE_INSUFFICIENT_RESOURCES),
1450 errmsg("out of file descriptors: %m; release and retry")));
1452 if (ReleaseLruFile())
1461 * Free an AllocateDesc of either type.
1463 * The argument *must* point into the allocatedDescs[] array.
1466 FreeDesc(AllocateDesc *desc)
1470 /* Close the underlying object */
1473 case AllocateDescFile:
1474 result = fclose(desc->desc.file);
1476 case AllocateDescDir:
1477 result = closedir(desc->desc.dir);
1480 elog(ERROR, "AllocateDesc kind not recognized");
1481 result = 0; /* keep compiler quiet */
1485 /* Compact storage in the allocatedDescs array */
1486 numAllocatedDescs--;
1487 *desc = allocatedDescs[numAllocatedDescs];
1493 * Close a file returned by AllocateFile.
1495 * Note we do not check fclose's return value --- it is up to the caller
1496 * to handle close errors.
1499 FreeFile(FILE *file)
1503 DO_DB(elog(LOG, "FreeFile: Allocated %d", numAllocatedDescs));
1505 /* Remove file from list of allocated files, if it's present */
1506 for (i = numAllocatedDescs; --i >= 0;)
1508 AllocateDesc *desc = &allocatedDescs[i];
1510 if (desc->kind == AllocateDescFile && desc->desc.file == file)
1511 return FreeDesc(desc);
1514 /* Only get here if someone passes us a file not in allocatedDescs */
1515 elog(WARNING, "file passed to FreeFile was not obtained from AllocateFile");
1517 return fclose(file);
1522 * Routines that want to use <dirent.h> (ie, DIR*) should use AllocateDir
1523 * rather than plain opendir(). This lets fd.c deal with freeing FDs if
1524 * necessary to open the directory, and with closing it after an elog.
1525 * When done, call FreeDir rather than closedir.
1527 * Ideally this should be the *only* direct call of opendir() in the backend.
1530 AllocateDir(const char *dirname)
1534 DO_DB(elog(LOG, "AllocateDir: Allocated %d (%s)",
1535 numAllocatedDescs, dirname));
1538 * The test against MAX_ALLOCATED_DESCS prevents us from overflowing
1539 * allocatedDescs[]; the test against max_safe_fds prevents AllocateDir
1540 * from hogging every one of the available FDs, which'd lead to infinite
1543 if (numAllocatedDescs >= MAX_ALLOCATED_DESCS ||
1544 numAllocatedDescs >= max_safe_fds - 1)
1545 elog(ERROR, "exceeded MAX_ALLOCATED_DESCS while trying to open directory \"%s\"",
1549 if ((dir = opendir(dirname)) != NULL)
1551 AllocateDesc *desc = &allocatedDescs[numAllocatedDescs];
1553 desc->kind = AllocateDescDir;
1554 desc->desc.dir = dir;
1555 desc->create_subid = GetCurrentSubTransactionId();
1556 numAllocatedDescs++;
1557 return desc->desc.dir;
1560 if (errno == EMFILE || errno == ENFILE)
1562 int save_errno = errno;
1565 (errcode(ERRCODE_INSUFFICIENT_RESOURCES),
1566 errmsg("out of file descriptors: %m; release and retry")));
1568 if (ReleaseLruFile())
1577 * Read a directory opened with AllocateDir, ereport'ing any error.
1579 * This is easier to use than raw readdir() since it takes care of some
1580 * otherwise rather tedious and error-prone manipulation of errno. Also,
1581 * if you are happy with a generic error message for AllocateDir failure,
1584 * dir = AllocateDir(path);
1585 * while ((dirent = ReadDir(dir, path)) != NULL)
1589 * since a NULL dir parameter is taken as indicating AllocateDir failed.
1590 * (Make sure errno hasn't been changed since AllocateDir if you use this
1593 * The pathname passed to AllocateDir must be passed to this routine too,
1594 * but it is only used for error reporting.
1597 ReadDir(DIR *dir, const char *dirname)
1599 struct dirent *dent;
1601 /* Give a generic message for AllocateDir failure, if caller didn't */
1604 (errcode_for_file_access(),
1605 errmsg("could not open directory \"%s\": %m",
1609 if ((dent = readdir(dir)) != NULL)
1615 * This fix is in mingw cvs (runtime/mingwex/dirent.c rev 1.4), but not in
1618 if (GetLastError() == ERROR_NO_MORE_FILES)
1624 (errcode_for_file_access(),
1625 errmsg("could not read directory \"%s\": %m",
1631 * Close a directory opened with AllocateDir.
1633 * Note we do not check closedir's return value --- it is up to the caller
1634 * to handle close errors.
1641 DO_DB(elog(LOG, "FreeDir: Allocated %d", numAllocatedDescs));
1643 /* Remove dir from list of allocated dirs, if it's present */
1644 for (i = numAllocatedDescs; --i >= 0;)
1646 AllocateDesc *desc = &allocatedDescs[i];
1648 if (desc->kind == AllocateDescDir && desc->desc.dir == dir)
1649 return FreeDesc(desc);
1652 /* Only get here if someone passes us a dir not in allocatedDescs */
1653 elog(WARNING, "dir passed to FreeDir was not obtained from AllocateDir");
1655 return closedir(dir);
1662 * Force all VFDs into the physically-closed state, so that the fewest
1663 * possible number of kernel file descriptors are in use. There is no
1664 * change in the logical state of the VFDs.
1671 if (SizeVfdCache > 0)
1673 Assert(FileIsNotOpen(0)); /* Make sure ring not corrupted */
1674 for (i = 1; i < SizeVfdCache; i++)
1676 if (!FileIsNotOpen(i))
1684 * SetTempTablespaces
1686 * Define a list (actually an array) of OIDs of tablespaces to use for
1687 * temporary files. This list will be used until end of transaction,
1688 * unless this function is called again before then. It is caller's
1689 * responsibility that the passed-in array has adequate lifespan (typically
1690 * it'd be allocated in TopTransactionContext).
1693 SetTempTablespaces(Oid *tableSpaces, int numSpaces)
1695 Assert(numSpaces >= 0);
1696 tempTableSpaces = tableSpaces;
1697 numTempTableSpaces = numSpaces;
1700 * Select a random starting point in the list. This is to minimize
1701 * conflicts between backends that are most likely sharing the same list
1702 * of temp tablespaces. Note that if we create multiple temp files in the
1703 * same transaction, we'll advance circularly through the list --- this
1704 * ensures that large temporary sort files are nicely spread across all
1705 * available tablespaces.
1708 nextTempTableSpace = random() % numSpaces;
1710 nextTempTableSpace = 0;
1714 * TempTablespacesAreSet
1716 * Returns TRUE if SetTempTablespaces has been called in current transaction.
1717 * (This is just so that tablespaces.c doesn't need its own per-transaction
1721 TempTablespacesAreSet(void)
1723 return (numTempTableSpaces >= 0);
1727 * GetNextTempTableSpace
1729 * Select the next temp tablespace to use. A result of InvalidOid means
1730 * to use the current database's default tablespace.
1733 GetNextTempTableSpace(void)
1735 if (numTempTableSpaces > 0)
1737 /* Advance nextTempTableSpace counter with wraparound */
1738 if (++nextTempTableSpace >= numTempTableSpaces)
1739 nextTempTableSpace = 0;
1740 return tempTableSpaces[nextTempTableSpace];
1749 * Take care of subtransaction commit/abort. At abort, we close temp files
1750 * that the subtransaction may have opened. At commit, we reassign the
1751 * files that were opened to the parent subtransaction.
1754 AtEOSubXact_Files(bool isCommit, SubTransactionId mySubid,
1755 SubTransactionId parentSubid)
1759 for (i = 0; i < numAllocatedDescs; i++)
1761 if (allocatedDescs[i].create_subid == mySubid)
1764 allocatedDescs[i].create_subid = parentSubid;
1767 /* have to recheck the item after FreeDesc (ugly) */
1768 FreeDesc(&allocatedDescs[i--]);
1777 * This routine is called during transaction commit or abort (it doesn't
1778 * particularly care which). All still-open per-transaction temporary file
1779 * VFDs are closed, which also causes the underlying files to be deleted
1780 * (although they should've been closed already by the ResourceOwner
1781 * cleanup). Furthermore, all "allocated" stdio files are closed. We also
1782 * forget any transaction-local temp tablespace list.
1785 AtEOXact_Files(void)
1787 CleanupTempFiles(false);
1788 tempTableSpaces = NULL;
1789 numTempTableSpaces = -1;
1795 * on_proc_exit hook to clean up temp files during backend shutdown.
1796 * Here, we want to clean up *all* temp files including interXact ones.
1799 AtProcExit_Files(int code, Datum arg)
1801 CleanupTempFiles(true);
1805 * Close temporary files and delete their underlying files.
1807 * isProcExit: if true, this is being called as the backend process is
1808 * exiting. If that's the case, we should remove all temporary files; if
1809 * that's not the case, we are being called for transaction commit/abort
1810 * and should only remove transaction-local temp files. In either case,
1811 * also clean up "allocated" stdio files and dirs.
1814 CleanupTempFiles(bool isProcExit)
1819 * Careful here: at proc_exit we need extra cleanup, not just
1820 * xact_temporary files.
1822 if (isProcExit || have_xact_temporary_files)
1824 Assert(FileIsNotOpen(0)); /* Make sure ring not corrupted */
1825 for (i = 1; i < SizeVfdCache; i++)
1827 unsigned short fdstate = VfdCache[i].fdstate;
1829 if ((fdstate & FD_TEMPORARY) && VfdCache[i].fileName != NULL)
1832 * If we're in the process of exiting a backend process, close
1833 * all temporary files. Otherwise, only close temporary files
1834 * local to the current transaction. They should be closed by
1835 * the ResourceOwner mechanism already, so this is just a
1836 * debugging cross-check.
1840 else if (fdstate & FD_XACT_TEMPORARY)
1843 "temporary file %s not closed at end-of-transaction",
1844 VfdCache[i].fileName);
1850 have_xact_temporary_files = false;
1853 /* Clean up "allocated" stdio files and dirs. */
1854 while (numAllocatedDescs > 0)
1855 FreeDesc(&allocatedDescs[0]);
1860 * Remove temporary and temporary relation files left over from a prior
1861 * postmaster session
1863 * This should be called during postmaster startup. It will forcibly
1864 * remove any leftover files created by OpenTemporaryFile and any leftover
1865 * temporary relation files created by mdcreate.
1867 * NOTE: we could, but don't, call this during a post-backend-crash restart
1868 * cycle. The argument for not doing it is that someone might want to examine
1869 * the temp files for debugging purposes. This does however mean that
1870 * OpenTemporaryFile had better allow for collision with an existing temp
1874 RemovePgTempFiles(void)
1876 char temp_path[MAXPGPATH];
1878 struct dirent *spc_de;
1881 * First process temp files in pg_default ($PGDATA/base)
1883 snprintf(temp_path, sizeof(temp_path), "base/%s", PG_TEMP_FILES_DIR);
1884 RemovePgTempFilesInDir(temp_path);
1885 RemovePgTempRelationFiles("base");
1888 * Cycle through temp directories for all non-default tablespaces.
1890 spc_dir = AllocateDir("pg_tblspc");
1892 while ((spc_de = ReadDir(spc_dir, "pg_tblspc")) != NULL)
1894 if (strcmp(spc_de->d_name, ".") == 0 ||
1895 strcmp(spc_de->d_name, "..") == 0)
1898 snprintf(temp_path, sizeof(temp_path), "pg_tblspc/%s/%s/%s",
1899 spc_de->d_name, TABLESPACE_VERSION_DIRECTORY, PG_TEMP_FILES_DIR);
1900 RemovePgTempFilesInDir(temp_path);
1902 snprintf(temp_path, sizeof(temp_path), "pg_tblspc/%s/%s",
1903 spc_de->d_name, TABLESPACE_VERSION_DIRECTORY);
1904 RemovePgTempRelationFiles(temp_path);
1910 * In EXEC_BACKEND case there is a pgsql_tmp directory at the top level of
1914 RemovePgTempFilesInDir(PG_TEMP_FILES_DIR);
1918 /* Process one pgsql_tmp directory for RemovePgTempFiles */
1920 RemovePgTempFilesInDir(const char *tmpdirname)
1923 struct dirent *temp_de;
1924 char rm_path[MAXPGPATH];
1926 temp_dir = AllocateDir(tmpdirname);
1927 if (temp_dir == NULL)
1929 /* anything except ENOENT is fishy */
1930 if (errno != ENOENT)
1932 "could not open temporary-files directory \"%s\": %m",
1937 while ((temp_de = ReadDir(temp_dir, tmpdirname)) != NULL)
1939 if (strcmp(temp_de->d_name, ".") == 0 ||
1940 strcmp(temp_de->d_name, "..") == 0)
1943 snprintf(rm_path, sizeof(rm_path), "%s/%s",
1944 tmpdirname, temp_de->d_name);
1946 if (strncmp(temp_de->d_name,
1947 PG_TEMP_FILE_PREFIX,
1948 strlen(PG_TEMP_FILE_PREFIX)) == 0)
1949 unlink(rm_path); /* note we ignore any error */
1952 "unexpected file found in temporary-files directory: \"%s\"",
1959 /* Process one tablespace directory, look for per-DB subdirectories */
1961 RemovePgTempRelationFiles(const char *tsdirname)
1965 char dbspace_path[MAXPGPATH];
1967 ts_dir = AllocateDir(tsdirname);
1970 /* anything except ENOENT is fishy */
1971 if (errno != ENOENT)
1973 "could not open tablespace directory \"%s\": %m",
1978 while ((de = ReadDir(ts_dir, tsdirname)) != NULL)
1983 * We're only interested in the per-database directories, which have
1984 * numeric names. Note that this code will also (properly) ignore "."
1987 while (isdigit((unsigned char) de->d_name[i]))
1989 if (de->d_name[i] != '\0' || i == 0)
1992 snprintf(dbspace_path, sizeof(dbspace_path), "%s/%s",
1993 tsdirname, de->d_name);
1994 RemovePgTempRelationFilesInDbspace(dbspace_path);
2000 /* Process one per-dbspace directory for RemovePgTempRelationFiles */
2002 RemovePgTempRelationFilesInDbspace(const char *dbspacedirname)
2006 char rm_path[MAXPGPATH];
2008 dbspace_dir = AllocateDir(dbspacedirname);
2009 if (dbspace_dir == NULL)
2011 /* we just saw this directory, so it really ought to be there */
2013 "could not open dbspace directory \"%s\": %m",
2018 while ((de = ReadDir(dbspace_dir, dbspacedirname)) != NULL)
2020 if (!looks_like_temp_rel_name(de->d_name))
2023 snprintf(rm_path, sizeof(rm_path), "%s/%s",
2024 dbspacedirname, de->d_name);
2026 unlink(rm_path); /* note we ignore any error */
2029 FreeDir(dbspace_dir);
2032 /* t<digits>_<digits>, or t<digits>_<digits>_<forkname> */
2034 looks_like_temp_rel_name(const char *name)
2039 /* Must start with "t". */
2043 /* Followed by a non-empty string of digits and then an underscore. */
2044 for (pos = 1; isdigit((unsigned char) name[pos]); ++pos)
2046 if (pos == 1 || name[pos] != '_')
2049 /* Followed by another nonempty string of digits. */
2050 for (savepos = ++pos; isdigit((unsigned char) name[pos]); ++pos)
2055 /* We might have _forkname or .segment or both. */
2056 if (name[pos] == '_')
2058 int forkchar = forkname_chars(&name[pos + 1], NULL);
2062 pos += forkchar + 1;
2064 if (name[pos] == '.')
2068 for (segchar = 1; isdigit((unsigned char) name[pos + segchar]); ++segchar)
2075 /* Now we should be at the end. */
2076 if (name[pos] != '\0')