]> granicus.if.org Git - postgresql/blob - src/backend/storage/file/fd.c
Cause ShutdownPostgres to do a normal transaction abort during backend
[postgresql] / src / backend / storage / file / fd.c
1 /*-------------------------------------------------------------------------
2  *
3  * fd.c
4  *        Virtual file descriptor code.
5  *
6  * Portions Copyright (c) 1996-2005, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  * IDENTIFICATION
10  *        $PostgreSQL: pgsql/src/backend/storage/file/fd.c,v 1.120 2005/08/08 03:11:49 tgl Exp $
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 256 on many modern
20  * operating systems, but can be as low as 32 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  * 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
37  * POSTGRES source.
38  *-------------------------------------------------------------------------
39  */
40
41 #include "postgres.h"
42
43 #include <sys/file.h>
44 #include <sys/param.h>
45 #include <sys/stat.h>
46 #include <unistd.h>
47 #include <fcntl.h>
48
49 #include "miscadmin.h"
50 #include "access/xact.h"
51 #include "storage/fd.h"
52 #include "storage/ipc.h"
53
54
55 /*
56  * We must leave some file descriptors free for system(), the dynamic loader,
57  * and other code that tries to open files without consulting fd.c.  This
58  * is the number left free.  (While we can be pretty sure we won't get
59  * EMFILE, there's never any guarantee that we won't get ENFILE due to
60  * other processes chewing up FDs.      So it's a bad idea to try to open files
61  * without consulting fd.c.  Nonetheless we cannot control all code.)
62  *
63  * Because this is just a fixed setting, we are effectively assuming that
64  * no such code will leave FDs open over the long term; otherwise the slop
65  * is likely to be insufficient.  Note in particular that we expect that
66  * loading a shared library does not result in any permanent increase in
67  * the number of open files.  (This appears to be true on most if not
68  * all platforms as of Feb 2004.)
69  */
70 #define NUM_RESERVED_FDS                10
71
72 /*
73  * If we have fewer than this many usable FDs after allowing for the reserved
74  * ones, choke.
75  */
76 #define FD_MINFREE                              10
77
78
79 /*
80  * A number of platforms allow individual processes to open many more files
81  * than they can really support when *many* processes do the same thing.
82  * This GUC parameter lets the DBA limit max_safe_fds to something less than
83  * what the postmaster's initial probe suggests will work.
84  */
85 int                     max_files_per_process = 1000;
86
87 /*
88  * Maximum number of file descriptors to open for either VFD entries or
89  * AllocateFile/AllocateDir operations.  This is initialized to a conservative
90  * value, and remains that way indefinitely in bootstrap or standalone-backend
91  * cases.  In normal postmaster operation, the postmaster calls
92  * set_max_safe_fds() late in initialization to update the value, and that
93  * value is then inherited by forked subprocesses.
94  *
95  * Note: the value of max_files_per_process is taken into account while
96  * setting this variable, and so need not be tested separately.
97  */
98 static int      max_safe_fds = 32;      /* default if not changed */
99
100
101 /* Debugging.... */
102
103 #ifdef FDDEBUG
104 #define DO_DB(A) A
105 #else
106 #define DO_DB(A)                                /* A */
107 #endif
108
109 #define VFD_CLOSED (-1)
110
111 #define FileIsValid(file) \
112         ((file) > 0 && (file) < (int) SizeVfdCache && VfdCache[file].fileName != NULL)
113
114 #define FileIsNotOpen(file) (VfdCache[file].fd == VFD_CLOSED)
115
116 #define FileUnknownPos (-1L)
117
118 /* these are the assigned bits in fdstate below: */
119 #define FD_TEMPORARY            (1 << 0)        /* T = delete when closed */
120 #define FD_XACT_TEMPORARY       (1 << 1)        /* T = delete at eoXact */
121
122 typedef struct vfd
123 {
124         signed short fd;                        /* current FD, or VFD_CLOSED if none */
125         unsigned short fdstate;         /* bitflags for VFD's state */
126         SubTransactionId create_subid;  /* for TEMPORARY fds, creating subxact */
127         File            nextFree;               /* link to next free VFD, if in freelist */
128         File            lruMoreRecently;        /* doubly linked recency-of-use list */
129         File            lruLessRecently;
130         long            seekPos;                /* current logical file position */
131         char       *fileName;           /* name of file, or NULL for unused VFD */
132         /* NB: fileName is malloc'd, and must be free'd when closing the VFD */
133         int                     fileFlags;              /* open(2) flags for (re)opening the file */
134         int                     fileMode;               /* mode to pass to open(2) */
135 } Vfd;
136
137 /*
138  * Virtual File Descriptor array pointer and size.      This grows as
139  * needed.      'File' values are indexes into this array.
140  * Note that VfdCache[0] is not a usable VFD, just a list header.
141  */
142 static Vfd *VfdCache;
143 static Size SizeVfdCache = 0;
144
145 /*
146  * Number of file descriptors known to be in use by VFD entries.
147  */
148 static int      nfile = 0;
149
150 /*
151  * List of stdio FILEs and <dirent.h> DIRs opened with AllocateFile
152  * and AllocateDir.
153  *
154  * Since we don't want to encourage heavy use of AllocateFile or AllocateDir,
155  * it seems OK to put a pretty small maximum limit on the number of
156  * simultaneously allocated descs.
157  */
158 #define MAX_ALLOCATED_DESCS  32
159
160 typedef enum
161 {
162         AllocateDescFile,
163         AllocateDescDir
164 } AllocateDescKind;
165
166 typedef struct
167 {
168         AllocateDescKind kind;
169         union
170         {
171                 FILE       *file;
172                 DIR                *dir;
173         }                       desc;
174         SubTransactionId create_subid;
175 } AllocateDesc;
176
177 static int      numAllocatedDescs = 0;
178 static AllocateDesc allocatedDescs[MAX_ALLOCATED_DESCS];
179
180 /*
181  * Number of temporary files opened during the current session;
182  * this is used in generation of tempfile names.
183  */
184 static long tempFileCounter = 0;
185
186
187 /*--------------------
188  *
189  * Private Routines
190  *
191  * Delete                  - delete a file from the Lru ring
192  * LruDelete       - remove a file from the Lru ring and close its FD
193  * Insert                  - put a file at the front of the Lru ring
194  * LruInsert       - put a file at the front of the Lru ring and open it
195  * ReleaseLruFile  - Release an fd by closing the last entry in the Lru ring
196  * AllocateVfd     - grab a free (or new) file record (from VfdArray)
197  * FreeVfd                 - free a file record
198  *
199  * The Least Recently Used ring is a doubly linked list that begins and
200  * ends on element zero.  Element zero is special -- it doesn't represent
201  * a file and its "fd" field always == VFD_CLOSED.      Element zero is just an
202  * anchor that shows us the beginning/end of the ring.
203  * Only VFD elements that are currently really open (have an FD assigned) are
204  * in the Lru ring.  Elements that are "virtually" open can be recognized
205  * by having a non-null fileName field.
206  *
207  * example:
208  *
209  *         /--less----\                            /---------\
210  *         v               \                      v                       \
211  *       #0 --more---> LeastRecentlyUsed --more-\ \
212  *        ^\                                                                    | |
213  *         \\less--> MostRecentlyUsedFile       <---/ |
214  *              \more---/                                        \--less--/
215  *
216  *--------------------
217  */
218 static void Delete(File file);
219 static void LruDelete(File file);
220 static void Insert(File file);
221 static int      LruInsert(File file);
222 static bool ReleaseLruFile(void);
223 static File AllocateVfd(void);
224 static void FreeVfd(File file);
225
226 static int      FileAccess(File file);
227 static char *make_database_relative(const char *filename);
228 static void AtProcExit_Files(int code, Datum arg);
229 static void CleanupTempFiles(bool isProcExit);
230 static void RemovePgTempFilesInDir(const char *tmpdirname);
231
232
233 /*
234  * pg_fsync --- do fsync with or without writethrough
235  */
236 int
237 pg_fsync(int fd)
238 {
239 #ifndef HAVE_FSYNC_WRITETHROUGH_ONLY
240         if (sync_method != SYNC_METHOD_FSYNC_WRITETHROUGH)
241                 return pg_fsync_no_writethrough(fd);
242         else
243 #endif
244                 return pg_fsync_writethrough(fd);
245 }
246
247
248 /*
249  * pg_fsync_no_writethrough --- same as fsync except does nothing if
250  *      enableFsync is off
251  */
252 int
253 pg_fsync_no_writethrough(int fd)
254 {
255         if (enableFsync)
256                 return fsync(fd);
257         else
258                 return 0;
259 }
260
261 /*
262  * pg_fsync_writethrough
263  */
264 int
265 pg_fsync_writethrough(int fd)
266 {
267         if (enableFsync)
268 #ifdef WIN32
269                 return _commit(fd);
270 #elif defined(__darwin__)
271                 return (fcntl(fd, F_FULLFSYNC, 0) == -1) ? -1 : 0;
272 #else
273                 return -1;
274 #endif
275         else
276                 return 0;
277 }
278
279 /*
280  * pg_fdatasync --- same as fdatasync except does nothing if enableFsync is off
281  *
282  * Not all platforms have fdatasync; treat as fsync if not available.
283  */
284 int
285 pg_fdatasync(int fd)
286 {
287         if (enableFsync)
288         {
289 #ifdef HAVE_FDATASYNC
290                 return fdatasync(fd);
291 #else
292                 return fsync(fd);
293 #endif
294         }
295         else
296                 return 0;
297 }
298
299 /*
300  * InitFileAccess --- initialize this module during backend startup
301  *
302  * This is called during either normal or standalone backend start.
303  * It is *not* called in the postmaster.
304  */
305 void
306 InitFileAccess(void)
307 {
308         Assert(SizeVfdCache == 0);                      /* call me only once */
309
310         /* initialize cache header entry */
311         VfdCache = (Vfd *) malloc(sizeof(Vfd));
312         if (VfdCache == NULL)
313                 ereport(FATAL,
314                                 (errcode(ERRCODE_OUT_OF_MEMORY),
315                                  errmsg("out of memory")));
316
317         MemSet((char *) &(VfdCache[0]), 0, sizeof(Vfd));
318         VfdCache->fd = VFD_CLOSED;
319
320         SizeVfdCache = 1;
321
322         /* register proc-exit hook to ensure temp files are dropped at exit */
323         on_proc_exit(AtProcExit_Files, 0);
324 }
325
326 /*
327  * count_usable_fds --- count how many FDs the system will let us open,
328  *              and estimate how many are already open.
329  *
330  * We stop counting if usable_fds reaches max_to_probe.  Note: a small
331  * value of max_to_probe might result in an underestimate of already_open;
332  * we must fill in any "gaps" in the set of used FDs before the calculation
333  * of already_open will give the right answer.  In practice, max_to_probe
334  * of a couple of dozen should be enough to ensure good results.
335  *
336  * We assume stdin (FD 0) is available for dup'ing
337  */
338 static void
339 count_usable_fds(int max_to_probe, int *usable_fds, int *already_open)
340 {
341         int                *fd;
342         int                     size;
343         int                     used = 0;
344         int                     highestfd = 0;
345         int                     j;
346
347         size = 1024;
348         fd = (int *) palloc(size * sizeof(int));
349
350         /* dup until failure or probe limit reached */
351         for (;;)
352         {
353                 int                     thisfd;
354
355                 thisfd = dup(0);
356                 if (thisfd < 0)
357                 {
358                         /* Expect EMFILE or ENFILE, else it's fishy */
359                         if (errno != EMFILE && errno != ENFILE)
360                                 elog(WARNING, "dup(0) failed after %d successes: %m", used);
361                         break;
362                 }
363
364                 if (used >= size)
365                 {
366                         size *= 2;
367                         fd = (int *) repalloc(fd, size * sizeof(int));
368                 }
369                 fd[used++] = thisfd;
370
371                 if (highestfd < thisfd)
372                         highestfd = thisfd;
373
374                 if (used >= max_to_probe)
375                         break;
376         }
377
378         /* release the files we opened */
379         for (j = 0; j < used; j++)
380                 close(fd[j]);
381
382         pfree(fd);
383
384         /*
385          * Return results.      usable_fds is just the number of successful dups.
386          * We assume that the system limit is highestfd+1 (remember 0 is a
387          * legal FD number) and so already_open is highestfd+1 - usable_fds.
388          */
389         *usable_fds = used;
390         *already_open = highestfd + 1 - used;
391 }
392
393 /*
394  * set_max_safe_fds
395  *              Determine number of filedescriptors that fd.c is allowed to use
396  */
397 void
398 set_max_safe_fds(void)
399 {
400         int                     usable_fds;
401         int                     already_open;
402
403         /*----------
404          * We want to set max_safe_fds to
405          *                      MIN(usable_fds, max_files_per_process - already_open)
406          * less the slop factor for files that are opened without consulting
407          * fd.c.  This ensures that we won't exceed either max_files_per_process
408          * or the experimentally-determined EMFILE limit.
409          *----------
410          */
411         count_usable_fds(max_files_per_process,
412                                          &usable_fds, &already_open);
413
414         max_safe_fds = Min(usable_fds, max_files_per_process - already_open);
415
416         /*
417          * Take off the FDs reserved for system() etc.
418          */
419         max_safe_fds -= NUM_RESERVED_FDS;
420
421         /*
422          * Make sure we still have enough to get by.
423          */
424         if (max_safe_fds < FD_MINFREE)
425                 ereport(FATAL,
426                                 (errcode(ERRCODE_INSUFFICIENT_RESOURCES),
427                                  errmsg("insufficient file descriptors available to start server process"),
428                                  errdetail("System allows %d, we need at least %d.",
429                                                    max_safe_fds + NUM_RESERVED_FDS,
430                                                    FD_MINFREE + NUM_RESERVED_FDS)));
431
432         elog(DEBUG2, "max_safe_fds = %d, usable_fds = %d, already_open = %d",
433                  max_safe_fds, usable_fds, already_open);
434 }
435
436 /*
437  * BasicOpenFile --- same as open(2) except can free other FDs if needed
438  *
439  * This is exported for use by places that really want a plain kernel FD,
440  * but need to be proof against running out of FDs.  Once an FD has been
441  * successfully returned, it is the caller's responsibility to ensure that
442  * it will not be leaked on ereport()!  Most users should *not* call this
443  * routine directly, but instead use the VFD abstraction level, which
444  * provides protection against descriptor leaks as well as management of
445  * files that need to be open for more than a short period of time.
446  *
447  * Ideally this should be the *only* direct call of open() in the backend.
448  * In practice, the postmaster calls open() directly, and there are some
449  * direct open() calls done early in backend startup.  Those are OK since
450  * this module wouldn't have any open files to close at that point anyway.
451  */
452 int
453 BasicOpenFile(FileName fileName, int fileFlags, int fileMode)
454 {
455         int                     fd;
456
457 tryAgain:
458         fd = open(fileName, fileFlags, fileMode);
459
460         if (fd >= 0)
461                 return fd;                              /* success! */
462
463         if (errno == EMFILE || errno == ENFILE)
464         {
465                 int                     save_errno = errno;
466
467                 ereport(LOG,
468                                 (errcode(ERRCODE_INSUFFICIENT_RESOURCES),
469                           errmsg("out of file descriptors: %m; release and retry")));
470                 errno = 0;
471                 if (ReleaseLruFile())
472                         goto tryAgain;
473                 errno = save_errno;
474         }
475
476         return -1;                                      /* failure */
477 }
478
479 #if defined(FDDEBUG)
480
481 static void
482 _dump_lru(void)
483 {
484         int                     mru = VfdCache[0].lruLessRecently;
485         Vfd                *vfdP = &VfdCache[mru];
486         char            buf[2048];
487
488         snprintf(buf, sizeof(buf), "LRU: MOST %d ", mru);
489         while (mru != 0)
490         {
491                 mru = vfdP->lruLessRecently;
492                 vfdP = &VfdCache[mru];
493                 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%d ", mru);
494         }
495         snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "LEAST");
496         elog(LOG, buf);
497 }
498 #endif   /* FDDEBUG */
499
500 static void
501 Delete(File file)
502 {
503         Vfd                *vfdP;
504
505         Assert(file != 0);
506
507         DO_DB(elog(LOG, "Delete %d (%s)",
508                            file, VfdCache[file].fileName));
509         DO_DB(_dump_lru());
510
511         vfdP = &VfdCache[file];
512
513         VfdCache[vfdP->lruLessRecently].lruMoreRecently = vfdP->lruMoreRecently;
514         VfdCache[vfdP->lruMoreRecently].lruLessRecently = vfdP->lruLessRecently;
515
516         DO_DB(_dump_lru());
517 }
518
519 static void
520 LruDelete(File file)
521 {
522         Vfd                *vfdP;
523
524         Assert(file != 0);
525
526         DO_DB(elog(LOG, "LruDelete %d (%s)",
527                            file, VfdCache[file].fileName));
528
529         vfdP = &VfdCache[file];
530
531         /* delete the vfd record from the LRU ring */
532         Delete(file);
533
534         /* save the seek position */
535         vfdP->seekPos = (long) lseek(vfdP->fd, 0L, SEEK_CUR);
536         Assert(vfdP->seekPos != -1L);
537
538         /* close the file */
539         if (close(vfdP->fd))
540                 elog(ERROR, "failed to close \"%s\": %m",
541                          vfdP->fileName);
542
543         --nfile;
544         vfdP->fd = VFD_CLOSED;
545 }
546
547 static void
548 Insert(File file)
549 {
550         Vfd                *vfdP;
551
552         Assert(file != 0);
553
554         DO_DB(elog(LOG, "Insert %d (%s)",
555                            file, VfdCache[file].fileName));
556         DO_DB(_dump_lru());
557
558         vfdP = &VfdCache[file];
559
560         vfdP->lruMoreRecently = 0;
561         vfdP->lruLessRecently = VfdCache[0].lruLessRecently;
562         VfdCache[0].lruLessRecently = file;
563         VfdCache[vfdP->lruLessRecently].lruMoreRecently = file;
564
565         DO_DB(_dump_lru());
566 }
567
568 /* returns 0 on success, -1 on re-open failure (with errno set) */
569 static int
570 LruInsert(File file)
571 {
572         Vfd                *vfdP;
573
574         Assert(file != 0);
575
576         DO_DB(elog(LOG, "LruInsert %d (%s)",
577                            file, VfdCache[file].fileName));
578
579         vfdP = &VfdCache[file];
580
581         if (FileIsNotOpen(file))
582         {
583                 while (nfile + numAllocatedDescs >= max_safe_fds)
584                 {
585                         if (!ReleaseLruFile())
586                                 break;
587                 }
588
589                 /*
590                  * The open could still fail for lack of file descriptors, eg due
591                  * to overall system file table being full.  So, be prepared to
592                  * release another FD if necessary...
593                  */
594                 vfdP->fd = BasicOpenFile(vfdP->fileName, vfdP->fileFlags,
595                                                                  vfdP->fileMode);
596                 if (vfdP->fd < 0)
597                 {
598                         DO_DB(elog(LOG, "RE_OPEN FAILED: %d", errno));
599                         return vfdP->fd;
600                 }
601                 else
602                 {
603                         DO_DB(elog(LOG, "RE_OPEN SUCCESS"));
604                         ++nfile;
605                 }
606
607                 /* seek to the right position */
608                 if (vfdP->seekPos != 0L)
609                 {
610                         long            returnValue;
611
612                         returnValue = (long) lseek(vfdP->fd, vfdP->seekPos, SEEK_SET);
613                         Assert(returnValue != -1L);
614                 }
615         }
616
617         /*
618          * put it at the head of the Lru ring
619          */
620
621         Insert(file);
622
623         return 0;
624 }
625
626 static bool
627 ReleaseLruFile(void)
628 {
629         DO_DB(elog(LOG, "ReleaseLruFile. Opened %d", nfile));
630
631         if (nfile > 0)
632         {
633                 /*
634                  * There are opened files and so there should be at least one used
635                  * vfd in the ring.
636                  */
637                 Assert(VfdCache[0].lruMoreRecently != 0);
638                 LruDelete(VfdCache[0].lruMoreRecently);
639                 return true;                    /* freed a file */
640         }
641         return false;                           /* no files available to free */
642 }
643
644 static File
645 AllocateVfd(void)
646 {
647         Index           i;
648         File            file;
649
650         DO_DB(elog(LOG, "AllocateVfd. Size %d", SizeVfdCache));
651
652         Assert(SizeVfdCache > 0);                       /* InitFileAccess not called? */
653
654         if (VfdCache[0].nextFree == 0)
655         {
656                 /*
657                  * The free list is empty so it is time to increase the size of
658                  * the array.  We choose to double it each time this happens.
659                  * However, there's not much point in starting *real* small.
660                  */
661                 Size            newCacheSize = SizeVfdCache * 2;
662                 Vfd                *newVfdCache;
663
664                 if (newCacheSize < 32)
665                         newCacheSize = 32;
666
667                 /*
668                  * Be careful not to clobber VfdCache ptr if realloc fails.
669                  */
670                 newVfdCache = (Vfd *) realloc(VfdCache, sizeof(Vfd) * newCacheSize);
671                 if (newVfdCache == NULL)
672                         ereport(ERROR,
673                                         (errcode(ERRCODE_OUT_OF_MEMORY),
674                                          errmsg("out of memory")));
675                 VfdCache = newVfdCache;
676
677                 /*
678                  * Initialize the new entries and link them into the free list.
679                  */
680                 for (i = SizeVfdCache; i < newCacheSize; i++)
681                 {
682                         MemSet((char *) &(VfdCache[i]), 0, sizeof(Vfd));
683                         VfdCache[i].nextFree = i + 1;
684                         VfdCache[i].fd = VFD_CLOSED;
685                 }
686                 VfdCache[newCacheSize - 1].nextFree = 0;
687                 VfdCache[0].nextFree = SizeVfdCache;
688
689                 /*
690                  * Record the new size
691                  */
692                 SizeVfdCache = newCacheSize;
693         }
694
695         file = VfdCache[0].nextFree;
696
697         VfdCache[0].nextFree = VfdCache[file].nextFree;
698
699         return file;
700 }
701
702 static void
703 FreeVfd(File file)
704 {
705         Vfd                *vfdP = &VfdCache[file];
706
707         DO_DB(elog(LOG, "FreeVfd: %d (%s)",
708                            file, vfdP->fileName ? vfdP->fileName : ""));
709
710         if (vfdP->fileName != NULL)
711         {
712                 free(vfdP->fileName);
713                 vfdP->fileName = NULL;
714         }
715         vfdP->fdstate = 0x0;
716
717         vfdP->nextFree = VfdCache[0].nextFree;
718         VfdCache[0].nextFree = file;
719 }
720
721 /*
722  * make_database_relative()
723  *              Prepend DatabasePath to the given file name.
724  *
725  * Result is a palloc'd string.
726  */
727 static char *
728 make_database_relative(const char *filename)
729 {
730         char       *buf;
731
732         Assert(!is_absolute_path(filename));
733         buf = (char *) palloc(strlen(DatabasePath) + strlen(filename) + 2);
734         sprintf(buf, "%s/%s", DatabasePath, filename);
735         return buf;
736 }
737
738 /* returns 0 on success, -1 on re-open failure (with errno set) */
739 static int
740 FileAccess(File file)
741 {
742         int                     returnValue;
743
744         DO_DB(elog(LOG, "FileAccess %d (%s)",
745                            file, VfdCache[file].fileName));
746
747         /*
748          * Is the file open?  If not, open it and put it at the head of the
749          * LRU ring (possibly closing the least recently used file to get an
750          * FD).
751          */
752
753         if (FileIsNotOpen(file))
754         {
755                 returnValue = LruInsert(file);
756                 if (returnValue != 0)
757                         return returnValue;
758         }
759         else if (VfdCache[0].lruLessRecently != file)
760         {
761                 /*
762                  * We now know that the file is open and that it is not the last
763                  * one accessed, so we need to move it to the head of the Lru
764                  * ring.
765                  */
766
767                 Delete(file);
768                 Insert(file);
769         }
770
771         return 0;
772 }
773
774 /*
775  *      Called when we get a shared invalidation message on some relation.
776  */
777 #ifdef NOT_USED
778 void
779 FileInvalidate(File file)
780 {
781         Assert(FileIsValid(file));
782         if (!FileIsNotOpen(file))
783                 LruDelete(file);
784 }
785 #endif
786
787 /*
788  * open a file in an arbitrary directory
789  *
790  * NB: if the passed pathname is relative (which it usually is),
791  * it will be interpreted relative to the process' working directory
792  * (which should always be $PGDATA when this code is running).
793  */
794 File
795 PathNameOpenFile(FileName fileName, int fileFlags, int fileMode)
796 {
797         char       *fnamecopy;
798         File            file;
799         Vfd                *vfdP;
800
801         DO_DB(elog(LOG, "PathNameOpenFile: %s %x %o",
802                            fileName, fileFlags, fileMode));
803
804         /*
805          * We need a malloc'd copy of the file name; fail cleanly if no room.
806          */
807         fnamecopy = strdup(fileName);
808         if (fnamecopy == NULL)
809                 ereport(ERROR,
810                                 (errcode(ERRCODE_OUT_OF_MEMORY),
811                                  errmsg("out of memory")));
812
813         file = AllocateVfd();
814         vfdP = &VfdCache[file];
815
816         while (nfile + numAllocatedDescs >= max_safe_fds)
817         {
818                 if (!ReleaseLruFile())
819                         break;
820         }
821
822         vfdP->fd = BasicOpenFile(fileName, fileFlags, fileMode);
823
824         if (vfdP->fd < 0)
825         {
826                 FreeVfd(file);
827                 free(fnamecopy);
828                 return -1;
829         }
830         ++nfile;
831         DO_DB(elog(LOG, "PathNameOpenFile: success %d",
832                            vfdP->fd));
833
834         Insert(file);
835
836         vfdP->fileName = fnamecopy;
837         /* Saved flags are adjusted to be OK for re-opening file */
838         vfdP->fileFlags = fileFlags & ~(O_CREAT | O_TRUNC | O_EXCL);
839         vfdP->fileMode = fileMode;
840         vfdP->seekPos = 0;
841         vfdP->fdstate = 0x0;
842
843         return file;
844 }
845
846 /*
847  * open a file in the database directory ($PGDATA/base/DIROID/)
848  *
849  * The passed name MUST be a relative path.  Effectively, this
850  * prepends DatabasePath to it and then acts like PathNameOpenFile.
851  */
852 File
853 FileNameOpenFile(FileName fileName, int fileFlags, int fileMode)
854 {
855         File            fd;
856         char       *fname;
857
858         fname = make_database_relative(fileName);
859         fd = PathNameOpenFile(fname, fileFlags, fileMode);
860         pfree(fname);
861         return fd;
862 }
863
864 /*
865  * Open a temporary file that will disappear when we close it.
866  *
867  * This routine takes care of generating an appropriate tempfile name.
868  * There's no need to pass in fileFlags or fileMode either, since only
869  * one setting makes any sense for a temp file.
870  *
871  * interXact: if true, don't close the file at end-of-transaction. In
872  * most cases, you don't want temporary files to outlive the transaction
873  * that created them, so this should be false -- but if you need
874  * "somewhat" temporary storage, this might be useful. In either case,
875  * the file is removed when the File is explicitly closed.
876  */
877 File
878 OpenTemporaryFile(bool interXact)
879 {
880         char            tempfilepath[MAXPGPATH];
881         File            file;
882
883         /*
884          * Generate a tempfile name that should be unique within the current
885          * database instance.
886          */
887         snprintf(tempfilepath, sizeof(tempfilepath),
888                          "%s/%s%d.%ld", PG_TEMP_FILES_DIR, PG_TEMP_FILE_PREFIX,
889                          MyProcPid, tempFileCounter++);
890
891         /*
892          * Open the file.  Note: we don't use O_EXCL, in case there is an
893          * orphaned temp file that can be reused.
894          */
895         file = FileNameOpenFile(tempfilepath,
896                                                         O_RDWR | O_CREAT | O_TRUNC | PG_BINARY,
897                                                         0600);
898         if (file <= 0)
899         {
900                 char       *dirpath;
901
902                 /*
903                  * We might need to create the pg_tempfiles subdirectory, if no
904                  * one has yet done so.
905                  *
906                  * Don't check for error from mkdir; it could fail if someone else
907                  * just did the same thing.  If it doesn't work then we'll bomb
908                  * out on the second create attempt, instead.
909                  */
910                 dirpath = make_database_relative(PG_TEMP_FILES_DIR);
911                 mkdir(dirpath, S_IRWXU);
912                 pfree(dirpath);
913
914                 file = FileNameOpenFile(tempfilepath,
915                                                                 O_RDWR | O_CREAT | O_TRUNC | PG_BINARY,
916                                                                 0600);
917                 if (file <= 0)
918                         elog(ERROR, "could not create temporary file \"%s\": %m",
919                                  tempfilepath);
920         }
921
922         /* Mark it for deletion at close */
923         VfdCache[file].fdstate |= FD_TEMPORARY;
924
925         /* Mark it for deletion at EOXact */
926         if (!interXact)
927         {
928                 VfdCache[file].fdstate |= FD_XACT_TEMPORARY;
929                 VfdCache[file].create_subid = GetCurrentSubTransactionId();
930         }
931
932         return file;
933 }
934
935 /*
936  * close a file when done with it
937  */
938 void
939 FileClose(File file)
940 {
941         Vfd                *vfdP;
942
943         Assert(FileIsValid(file));
944
945         DO_DB(elog(LOG, "FileClose: %d (%s)",
946                            file, VfdCache[file].fileName));
947
948         vfdP = &VfdCache[file];
949
950         if (!FileIsNotOpen(file))
951         {
952                 /* remove the file from the lru ring */
953                 Delete(file);
954
955                 /* close the file */
956                 if (close(vfdP->fd))
957                         elog(ERROR, "failed to close \"%s\": %m",
958                                  vfdP->fileName);
959
960                 --nfile;
961                 vfdP->fd = VFD_CLOSED;
962         }
963
964         /*
965          * Delete the file if it was temporary
966          */
967         if (vfdP->fdstate & FD_TEMPORARY)
968         {
969                 /* reset flag so that die() interrupt won't cause problems */
970                 vfdP->fdstate &= ~FD_TEMPORARY;
971                 if (unlink(vfdP->fileName))
972                         elog(LOG, "failed to unlink \"%s\": %m",
973                                  vfdP->fileName);
974         }
975
976         /*
977          * Return the Vfd slot to the free list
978          */
979         FreeVfd(file);
980 }
981
982 /*
983  * close a file and forcibly delete the underlying Unix file
984  */
985 void
986 FileUnlink(File file)
987 {
988         Assert(FileIsValid(file));
989
990         DO_DB(elog(LOG, "FileUnlink: %d (%s)",
991                            file, VfdCache[file].fileName));
992
993         /* force FileClose to delete it */
994         VfdCache[file].fdstate |= FD_TEMPORARY;
995
996         FileClose(file);
997 }
998
999 int
1000 FileRead(File file, char *buffer, int amount)
1001 {
1002         int                     returnCode;
1003
1004         Assert(FileIsValid(file));
1005
1006         DO_DB(elog(LOG, "FileRead: %d (%s) %ld %d %p",
1007                            file, VfdCache[file].fileName,
1008                            VfdCache[file].seekPos, amount, buffer));
1009
1010         returnCode = FileAccess(file);
1011         if (returnCode < 0)
1012                 return returnCode;
1013
1014         returnCode = read(VfdCache[file].fd, buffer, amount);
1015         if (returnCode > 0)
1016                 VfdCache[file].seekPos += returnCode;
1017         else
1018                 VfdCache[file].seekPos = FileUnknownPos;
1019
1020         return returnCode;
1021 }
1022
1023 int
1024 FileWrite(File file, char *buffer, int amount)
1025 {
1026         int                     returnCode;
1027
1028         Assert(FileIsValid(file));
1029
1030         DO_DB(elog(LOG, "FileWrite: %d (%s) %ld %d %p",
1031                            file, VfdCache[file].fileName,
1032                            VfdCache[file].seekPos, amount, buffer));
1033
1034         returnCode = FileAccess(file);
1035         if (returnCode < 0)
1036                 return returnCode;
1037
1038         errno = 0;
1039         returnCode = write(VfdCache[file].fd, buffer, amount);
1040
1041         /* if write didn't set errno, assume problem is no disk space */
1042         if (returnCode != amount && errno == 0)
1043                 errno = ENOSPC;
1044
1045         if (returnCode > 0)
1046                 VfdCache[file].seekPos += returnCode;
1047         else
1048                 VfdCache[file].seekPos = FileUnknownPos;
1049
1050         return returnCode;
1051 }
1052
1053 int
1054 FileSync(File file)
1055 {
1056         int                     returnCode;
1057
1058         Assert(FileIsValid(file));
1059
1060         DO_DB(elog(LOG, "FileSync: %d (%s)",
1061                            file, VfdCache[file].fileName));
1062
1063         returnCode = FileAccess(file);
1064         if (returnCode < 0)
1065                 return returnCode;
1066
1067         return pg_fsync(VfdCache[file].fd);
1068 }
1069
1070 long
1071 FileSeek(File file, long offset, int whence)
1072 {
1073         int                     returnCode;
1074
1075         Assert(FileIsValid(file));
1076
1077         DO_DB(elog(LOG, "FileSeek: %d (%s) %ld %ld %d",
1078                            file, VfdCache[file].fileName,
1079                            VfdCache[file].seekPos, offset, whence));
1080
1081         if (FileIsNotOpen(file))
1082         {
1083                 switch (whence)
1084                 {
1085                         case SEEK_SET:
1086                                 if (offset < 0)
1087                                         elog(ERROR, "invalid seek offset: %ld", offset);
1088                                 VfdCache[file].seekPos = offset;
1089                                 break;
1090                         case SEEK_CUR:
1091                                 VfdCache[file].seekPos += offset;
1092                                 break;
1093                         case SEEK_END:
1094                                 returnCode = FileAccess(file);
1095                                 if (returnCode < 0)
1096                                         return returnCode;
1097                                 VfdCache[file].seekPos = lseek(VfdCache[file].fd,
1098                                                                                            offset, whence);
1099                                 break;
1100                         default:
1101                                 elog(ERROR, "invalid whence: %d", whence);
1102                                 break;
1103                 }
1104         }
1105         else
1106         {
1107                 switch (whence)
1108                 {
1109                         case SEEK_SET:
1110                                 if (offset < 0)
1111                                         elog(ERROR, "invalid seek offset: %ld", offset);
1112                                 if (VfdCache[file].seekPos != offset)
1113                                         VfdCache[file].seekPos = lseek(VfdCache[file].fd,
1114                                                                                                    offset, whence);
1115                                 break;
1116                         case SEEK_CUR:
1117                                 if (offset != 0 || VfdCache[file].seekPos == FileUnknownPos)
1118                                         VfdCache[file].seekPos = lseek(VfdCache[file].fd,
1119                                                                                                    offset, whence);
1120                                 break;
1121                         case SEEK_END:
1122                                 VfdCache[file].seekPos = lseek(VfdCache[file].fd,
1123                                                                                            offset, whence);
1124                                 break;
1125                         default:
1126                                 elog(ERROR, "invalid whence: %d", whence);
1127                                 break;
1128                 }
1129         }
1130         return VfdCache[file].seekPos;
1131 }
1132
1133 /*
1134  * XXX not actually used but here for completeness
1135  */
1136 #ifdef NOT_USED
1137 long
1138 FileTell(File file)
1139 {
1140         Assert(FileIsValid(file));
1141         DO_DB(elog(LOG, "FileTell %d (%s)",
1142                            file, VfdCache[file].fileName));
1143         return VfdCache[file].seekPos;
1144 }
1145 #endif
1146
1147 int
1148 FileTruncate(File file, long offset)
1149 {
1150         int                     returnCode;
1151
1152         Assert(FileIsValid(file));
1153
1154         DO_DB(elog(LOG, "FileTruncate %d (%s)",
1155                            file, VfdCache[file].fileName));
1156
1157         returnCode = FileAccess(file);
1158         if (returnCode < 0)
1159                 return returnCode;
1160
1161         returnCode = ftruncate(VfdCache[file].fd, (size_t) offset);
1162         return returnCode;
1163 }
1164
1165
1166 /*
1167  * Routines that want to use stdio (ie, FILE*) should use AllocateFile
1168  * rather than plain fopen().  This lets fd.c deal with freeing FDs if
1169  * necessary to open the file.  When done, call FreeFile rather than fclose.
1170  *
1171  * Note that files that will be open for any significant length of time
1172  * should NOT be handled this way, since they cannot share kernel file
1173  * descriptors with other files; there is grave risk of running out of FDs
1174  * if anyone locks down too many FDs.  Most callers of this routine are
1175  * simply reading a config file that they will read and close immediately.
1176  *
1177  * fd.c will automatically close all files opened with AllocateFile at
1178  * transaction commit or abort; this prevents FD leakage if a routine
1179  * that calls AllocateFile is terminated prematurely by ereport(ERROR).
1180  *
1181  * Ideally this should be the *only* direct call of fopen() in the backend.
1182  */
1183 FILE *
1184 AllocateFile(char *name, char *mode)
1185 {
1186         FILE       *file;
1187
1188         DO_DB(elog(LOG, "AllocateFile: Allocated %d (%s)",
1189                            numAllocatedDescs, name));
1190
1191         /*
1192          * The test against MAX_ALLOCATED_DESCS prevents us from overflowing
1193          * allocatedFiles[]; the test against max_safe_fds prevents
1194          * AllocateFile from hogging every one of the available FDs, which'd
1195          * lead to infinite looping.
1196          */
1197         if (numAllocatedDescs >= MAX_ALLOCATED_DESCS ||
1198                 numAllocatedDescs >= max_safe_fds - 1)
1199                 elog(ERROR, "too many private files demanded");
1200
1201 TryAgain:
1202         if ((file = fopen(name, mode)) != NULL)
1203         {
1204                 AllocateDesc *desc = &allocatedDescs[numAllocatedDescs];
1205
1206                 desc->kind = AllocateDescFile;
1207                 desc->desc.file = file;
1208                 desc->create_subid = GetCurrentSubTransactionId();
1209                 numAllocatedDescs++;
1210                 return desc->desc.file;
1211         }
1212
1213         if (errno == EMFILE || errno == ENFILE)
1214         {
1215                 int                     save_errno = errno;
1216
1217                 ereport(LOG,
1218                                 (errcode(ERRCODE_INSUFFICIENT_RESOURCES),
1219                           errmsg("out of file descriptors: %m; release and retry")));
1220                 errno = 0;
1221                 if (ReleaseLruFile())
1222                         goto TryAgain;
1223                 errno = save_errno;
1224         }
1225
1226         return NULL;
1227 }
1228
1229 /*
1230  * Free an AllocateDesc of either type.
1231  *
1232  * The argument *must* point into the allocatedDescs[] array.
1233  */
1234 static int
1235 FreeDesc(AllocateDesc *desc)
1236 {
1237         int                     result;
1238
1239         /* Close the underlying object */
1240         switch (desc->kind)
1241         {
1242                 case AllocateDescFile:
1243                         result = fclose(desc->desc.file);
1244                         break;
1245                 case AllocateDescDir:
1246                         result = closedir(desc->desc.dir);
1247                         break;
1248                 default:
1249                         elog(ERROR, "AllocateDesc kind not recognized");
1250                         result = 0;                     /* keep compiler quiet */
1251                         break;
1252         }
1253
1254         /* Compact storage in the allocatedDescs array */
1255         numAllocatedDescs--;
1256         *desc = allocatedDescs[numAllocatedDescs];
1257
1258         return result;
1259 }
1260
1261 /*
1262  * Close a file returned by AllocateFile.
1263  *
1264  * Note we do not check fclose's return value --- it is up to the caller
1265  * to handle close errors.
1266  */
1267 int
1268 FreeFile(FILE *file)
1269 {
1270         int                     i;
1271
1272         DO_DB(elog(LOG, "FreeFile: Allocated %d", numAllocatedDescs));
1273
1274         /* Remove file from list of allocated files, if it's present */
1275         for (i = numAllocatedDescs; --i >= 0;)
1276         {
1277                 AllocateDesc *desc = &allocatedDescs[i];
1278
1279                 if (desc->kind == AllocateDescFile && desc->desc.file == file)
1280                         return FreeDesc(desc);
1281         }
1282
1283         /* Only get here if someone passes us a file not in allocatedDescs */
1284         elog(WARNING, "file passed to FreeFile was not obtained from AllocateFile");
1285
1286         return fclose(file);
1287 }
1288
1289
1290 /*
1291  * Routines that want to use <dirent.h> (ie, DIR*) should use AllocateDir
1292  * rather than plain opendir().  This lets fd.c deal with freeing FDs if
1293  * necessary to open the directory, and with closing it after an elog.
1294  * When done, call FreeDir rather than closedir.
1295  *
1296  * Ideally this should be the *only* direct call of opendir() in the backend.
1297  */
1298 DIR *
1299 AllocateDir(const char *dirname)
1300 {
1301         DIR                *dir;
1302
1303         DO_DB(elog(LOG, "AllocateDir: Allocated %d (%s)",
1304                            numAllocatedDescs, dirname));
1305
1306         /*
1307          * The test against MAX_ALLOCATED_DESCS prevents us from overflowing
1308          * allocatedDescs[]; the test against max_safe_fds prevents
1309          * AllocateDir from hogging every one of the available FDs, which'd
1310          * lead to infinite looping.
1311          */
1312         if (numAllocatedDescs >= MAX_ALLOCATED_DESCS ||
1313                 numAllocatedDescs >= max_safe_fds - 1)
1314                 elog(ERROR, "too many private dirs demanded");
1315
1316 TryAgain:
1317         if ((dir = opendir(dirname)) != NULL)
1318         {
1319                 AllocateDesc *desc = &allocatedDescs[numAllocatedDescs];
1320
1321                 desc->kind = AllocateDescDir;
1322                 desc->desc.dir = dir;
1323                 desc->create_subid = GetCurrentSubTransactionId();
1324                 numAllocatedDescs++;
1325                 return desc->desc.dir;
1326         }
1327
1328         if (errno == EMFILE || errno == ENFILE)
1329         {
1330                 int                     save_errno = errno;
1331
1332                 ereport(LOG,
1333                                 (errcode(ERRCODE_INSUFFICIENT_RESOURCES),
1334                           errmsg("out of file descriptors: %m; release and retry")));
1335                 errno = 0;
1336                 if (ReleaseLruFile())
1337                         goto TryAgain;
1338                 errno = save_errno;
1339         }
1340
1341         return NULL;
1342 }
1343
1344 /*
1345  * Read a directory opened with AllocateDir, ereport'ing any error.
1346  *
1347  * This is easier to use than raw readdir() since it takes care of some
1348  * otherwise rather tedious and error-prone manipulation of errno.  Also,
1349  * if you are happy with a generic error message for AllocateDir failure,
1350  * you can just do
1351  *
1352  *              dir = AllocateDir(path);
1353  *              while ((dirent = ReadDir(dir, path)) != NULL)
1354  *                      process dirent;
1355  *              FreeDir(path);
1356  *
1357  * since a NULL dir parameter is taken as indicating AllocateDir failed.
1358  * (Make sure errno hasn't been changed since AllocateDir if you use this
1359  * shortcut.)
1360  *
1361  * The pathname passed to AllocateDir must be passed to this routine too,
1362  * but it is only used for error reporting.
1363  */
1364 struct dirent *
1365 ReadDir(DIR *dir, const char *dirname)
1366 {
1367         struct dirent *dent;
1368
1369         /* Give a generic message for AllocateDir failure, if caller didn't */
1370         if (dir == NULL)
1371                 ereport(ERROR,
1372                                 (errcode_for_file_access(),
1373                                  errmsg("could not open directory \"%s\": %m",
1374                                                 dirname)));
1375
1376         errno = 0;
1377         if ((dent = readdir(dir)) != NULL)
1378                 return dent;
1379
1380 #ifdef WIN32
1381         /*
1382          * This fix is in mingw cvs (runtime/mingwex/dirent.c rev 1.4), but
1383          * not in released version
1384          */
1385         if (GetLastError() == ERROR_NO_MORE_FILES)
1386                 errno = 0;
1387 #endif
1388
1389         if (errno)
1390                 ereport(ERROR,
1391                                 (errcode_for_file_access(),
1392                                  errmsg("could not read directory \"%s\": %m",
1393                                                 dirname)));
1394         return NULL;
1395 }
1396
1397 /*
1398  * Close a directory opened with AllocateDir.
1399  *
1400  * Note we do not check closedir's return value --- it is up to the caller
1401  * to handle close errors.
1402  */
1403 int
1404 FreeDir(DIR *dir)
1405 {
1406         int                     i;
1407
1408         DO_DB(elog(LOG, "FreeDir: Allocated %d", numAllocatedDescs));
1409
1410         /* Remove dir from list of allocated dirs, if it's present */
1411         for (i = numAllocatedDescs; --i >= 0;)
1412         {
1413                 AllocateDesc *desc = &allocatedDescs[i];
1414
1415                 if (desc->kind == AllocateDescDir && desc->desc.dir == dir)
1416                         return FreeDesc(desc);
1417         }
1418
1419         /* Only get here if someone passes us a dir not in allocatedDescs */
1420         elog(WARNING, "dir passed to FreeDir was not obtained from AllocateDir");
1421
1422         return closedir(dir);
1423 }
1424
1425
1426 /*
1427  * closeAllVfds
1428  *
1429  * Force all VFDs into the physically-closed state, so that the fewest
1430  * possible number of kernel file descriptors are in use.  There is no
1431  * change in the logical state of the VFDs.
1432  */
1433 void
1434 closeAllVfds(void)
1435 {
1436         Index           i;
1437
1438         if (SizeVfdCache > 0)
1439         {
1440                 Assert(FileIsNotOpen(0));               /* Make sure ring not corrupted */
1441                 for (i = 1; i < SizeVfdCache; i++)
1442                 {
1443                         if (!FileIsNotOpen(i))
1444                                 LruDelete(i);
1445                 }
1446         }
1447 }
1448
1449 /*
1450  * AtEOSubXact_Files
1451  *
1452  * Take care of subtransaction commit/abort.  At abort, we close temp files
1453  * that the subtransaction may have opened.  At commit, we reassign the
1454  * files that were opened to the parent subtransaction.
1455  */
1456 void
1457 AtEOSubXact_Files(bool isCommit, SubTransactionId mySubid,
1458                                   SubTransactionId parentSubid)
1459 {
1460         Index           i;
1461
1462         if (SizeVfdCache > 0)
1463         {
1464                 Assert(FileIsNotOpen(0));               /* Make sure ring not corrupted */
1465                 for (i = 1; i < SizeVfdCache; i++)
1466                 {
1467                         unsigned short fdstate = VfdCache[i].fdstate;
1468
1469                         if ((fdstate & FD_XACT_TEMPORARY) &&
1470                                 VfdCache[i].create_subid == mySubid)
1471                         {
1472                                 if (isCommit)
1473                                         VfdCache[i].create_subid = parentSubid;
1474                                 else if (VfdCache[i].fileName != NULL)
1475                                         FileClose(i);
1476                         }
1477                 }
1478         }
1479
1480         for (i = 0; i < numAllocatedDescs; i++)
1481         {
1482                 if (allocatedDescs[i].create_subid == mySubid)
1483                 {
1484                         if (isCommit)
1485                                 allocatedDescs[i].create_subid = parentSubid;
1486                         else
1487                         {
1488                                 /* have to recheck the item after FreeDesc (ugly) */
1489                                 FreeDesc(&allocatedDescs[i--]);
1490                         }
1491                 }
1492         }
1493 }
1494
1495 /*
1496  * AtEOXact_Files
1497  *
1498  * This routine is called during transaction commit or abort (it doesn't
1499  * particularly care which).  All still-open per-transaction temporary file
1500  * VFDs are closed, which also causes the underlying files to be
1501  * deleted. Furthermore, all "allocated" stdio files are closed.
1502  */
1503 void
1504 AtEOXact_Files(void)
1505 {
1506         CleanupTempFiles(false);
1507 }
1508
1509 /*
1510  * AtProcExit_Files
1511  *
1512  * on_proc_exit hook to clean up temp files during backend shutdown.
1513  * Here, we want to clean up *all* temp files including interXact ones.
1514  */
1515 static void
1516 AtProcExit_Files(int code, Datum arg)
1517 {
1518         CleanupTempFiles(true);
1519 }
1520
1521 /*
1522  * Close temporary files and delete their underlying files.
1523  *
1524  * isProcExit: if true, this is being called as the backend process is
1525  * exiting. If that's the case, we should remove all temporary files; if
1526  * that's not the case, we are being called for transaction commit/abort
1527  * and should only remove transaction-local temp files.  In either case,
1528  * also clean up "allocated" stdio files and dirs.
1529  */
1530 static void
1531 CleanupTempFiles(bool isProcExit)
1532 {
1533         Index           i;
1534
1535         if (SizeVfdCache > 0)
1536         {
1537                 Assert(FileIsNotOpen(0));               /* Make sure ring not corrupted */
1538                 for (i = 1; i < SizeVfdCache; i++)
1539                 {
1540                         unsigned short fdstate = VfdCache[i].fdstate;
1541
1542                         if ((fdstate & FD_TEMPORARY) && VfdCache[i].fileName != NULL)
1543                         {
1544                                 /*
1545                                  * If we're in the process of exiting a backend process,
1546                                  * close all temporary files. Otherwise, only close
1547                                  * temporary files local to the current transaction.
1548                                  */
1549                                 if (isProcExit || (fdstate & FD_XACT_TEMPORARY))
1550                                         FileClose(i);
1551                         }
1552                 }
1553         }
1554
1555         while (numAllocatedDescs > 0)
1556                 FreeDesc(&allocatedDescs[0]);
1557 }
1558
1559
1560 /*
1561  * Remove temporary files left over from a prior postmaster session
1562  *
1563  * This should be called during postmaster startup.  It will forcibly
1564  * remove any leftover files created by OpenTemporaryFile.
1565  *
1566  * NOTE: we could, but don't, call this during a post-backend-crash restart
1567  * cycle.  The argument for not doing it is that someone might want to examine
1568  * the temp files for debugging purposes.  This does however mean that
1569  * OpenTemporaryFile had better allow for collision with an existing temp
1570  * file name.
1571  */
1572 void
1573 RemovePgTempFiles(void)
1574 {
1575         char            temp_path[MAXPGPATH];
1576         DIR                *db_dir;
1577         struct dirent *db_de;
1578
1579         /*
1580          * Cycle through pgsql_tmp directories for all databases and remove old
1581          * temp files.
1582          */
1583         db_dir = AllocateDir("base");
1584
1585         while ((db_de = ReadDir(db_dir, "base")) != NULL)
1586         {
1587                 if (strcmp(db_de->d_name, ".") == 0 ||
1588                         strcmp(db_de->d_name, "..") == 0)
1589                         continue;
1590
1591                 snprintf(temp_path, sizeof(temp_path), "base/%s/%s",
1592                                  db_de->d_name, PG_TEMP_FILES_DIR);
1593                 RemovePgTempFilesInDir(temp_path);
1594         }
1595
1596         FreeDir(db_dir);
1597
1598         /*
1599          * In EXEC_BACKEND case there is a pgsql_tmp directory at the top
1600          * level of DataDir as well.
1601          */
1602 #ifdef EXEC_BACKEND
1603         RemovePgTempFilesInDir(PG_TEMP_FILES_DIR);
1604 #endif
1605 }
1606
1607 /* Process one pgsql_tmp directory for RemovePgTempFiles */
1608 static void
1609 RemovePgTempFilesInDir(const char *tmpdirname)
1610 {
1611         DIR                *temp_dir;
1612         struct dirent *temp_de;
1613         char            rm_path[MAXPGPATH];
1614
1615         temp_dir = AllocateDir(tmpdirname);
1616         if (temp_dir == NULL)
1617         {
1618                 /* anything except ENOENT is fishy */
1619                 if (errno != ENOENT)
1620                         elog(LOG,
1621                                  "could not open temporary-files directory \"%s\": %m",
1622                                  tmpdirname);
1623                 return;
1624         }
1625
1626         while ((temp_de = ReadDir(temp_dir, tmpdirname)) != NULL)
1627         {
1628                 if (strcmp(temp_de->d_name, ".") == 0 ||
1629                         strcmp(temp_de->d_name, "..") == 0)
1630                         continue;
1631
1632                 snprintf(rm_path, sizeof(rm_path), "%s/%s",
1633                                  tmpdirname, temp_de->d_name);
1634
1635                 if (strncmp(temp_de->d_name,
1636                                         PG_TEMP_FILE_PREFIX,
1637                                         strlen(PG_TEMP_FILE_PREFIX)) == 0)
1638                         unlink(rm_path);        /* note we ignore any error */
1639                 else
1640                         elog(LOG,
1641                                  "unexpected file found in temporary-files directory: \"%s\"",
1642                                  rm_path);
1643         }
1644
1645         FreeDir(temp_dir);
1646 }