OSDN Git Service

387092724d26d3b0665939f9973634c416462e59
[pg-rex/syncrep.git] / src / backend / storage / file / fd.c
1 /*-------------------------------------------------------------------------
2  *
3  * fd.c
4  *        Virtual file descriptor code.
5  *
6  * Portions Copyright (c) 1996-2011, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  * IDENTIFICATION
10  *        src/backend/storage/file/fd.c
11  *
12  * NOTES:
13  *
14  * This code manages a cache of 'virtual' file descriptors (VFDs).
15  * The server opens many file descriptors for a variety of reasons,
16  * including base tables, scratch files (e.g., sort and hash spool
17  * files), and random calls to C library routines like system(3); it
18  * is quite easy to exceed system limits on the number of open files a
19  * single process can have.  (This is around 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 #ifdef HAVE_SYS_RESOURCE_H
49 #include <sys/resource.h>               /* for getrlimit */
50 #endif
51
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"
60
61
62 /*
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.)
69  *
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.)
76  */
77 #define NUM_RESERVED_FDS                10
78
79 /*
80  * If we have fewer than this many usable FDs after allowing for the reserved
81  * ones, choke.
82  */
83 #define FD_MINFREE                              10
84
85
86 /*
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.
91  */
92 int                     max_files_per_process = 1000;
93
94 /*
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.
101  *
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.
104  */
105 static int      max_safe_fds = 32;      /* default if not changed */
106
107
108 /* Debugging.... */
109
110 #ifdef FDDEBUG
111 #define DO_DB(A) A
112 #else
113 #define DO_DB(A)                                /* A */
114 #endif
115
116 #define VFD_CLOSED (-1)
117
118 #define FileIsValid(file) \
119         ((file) > 0 && (file) < (int) SizeVfdCache && VfdCache[file].fileName != NULL)
120
121 #define FileIsNotOpen(file) (VfdCache[file].fd == VFD_CLOSED)
122
123 #define FileUnknownPos ((off_t) -1)
124
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 */
128
129 /*
130  * Flag to tell whether it's worth scanning VfdCache looking for temp files to
131  * close
132  */
133 static bool have_xact_temporary_files = false;
134
135 typedef struct vfd
136 {
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) */
148 } Vfd;
149
150 /*
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.
154  */
155 static Vfd *VfdCache;
156 static Size SizeVfdCache = 0;
157
158 /*
159  * Number of file descriptors known to be in use by VFD entries.
160  */
161 static int      nfile = 0;
162
163 /*
164  * List of stdio FILEs and <dirent.h> DIRs opened with AllocateFile
165  * and AllocateDir.
166  *
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.
170  */
171 #define MAX_ALLOCATED_DESCS  32
172
173 typedef enum
174 {
175         AllocateDescFile,
176         AllocateDescDir
177 } AllocateDescKind;
178
179 typedef struct
180 {
181         AllocateDescKind kind;
182         union
183         {
184                 FILE       *file;
185                 DIR                *dir;
186         }                       desc;
187         SubTransactionId create_subid;
188 } AllocateDesc;
189
190 static int      numAllocatedDescs = 0;
191 static AllocateDesc allocatedDescs[MAX_ALLOCATED_DESCS];
192
193 /*
194  * Number of temporary files opened during the current session;
195  * this is used in generation of tempfile names.
196  */
197 static long tempFileCounter = 0;
198
199 /*
200  * Array of OIDs of temp tablespaces.  When numTempTableSpaces is -1,
201  * this has not been set in the current transaction.
202  */
203 static Oid *tempTableSpaces = NULL;
204 static int      numTempTableSpaces = -1;
205 static int      nextTempTableSpace = 0;
206
207
208 /*--------------------
209  *
210  * Private Routines
211  *
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
219  *
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.
227  *
228  * example:
229  *
230  *         /--less----\                            /---------\
231  *         v               \                      v                       \
232  *       #0 --more---> LeastRecentlyUsed --more-\ \
233  *        ^\                                                                    | |
234  *         \\less--> MostRecentlyUsedFile       <---/ |
235  *              \more---/                                        \--less--/
236  *
237  *--------------------
238  */
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);
246
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);
255
256
257 /*
258  * pg_fsync --- do fsync with or without writethrough
259  */
260 int
261 pg_fsync(int fd)
262 {
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);
267         else
268 #endif
269                 return pg_fsync_no_writethrough(fd);
270 }
271
272
273 /*
274  * pg_fsync_no_writethrough --- same as fsync except does nothing if
275  *      enableFsync is off
276  */
277 int
278 pg_fsync_no_writethrough(int fd)
279 {
280         if (enableFsync)
281                 return fsync(fd);
282         else
283                 return 0;
284 }
285
286 /*
287  * pg_fsync_writethrough
288  */
289 int
290 pg_fsync_writethrough(int fd)
291 {
292         if (enableFsync)
293         {
294 #ifdef WIN32
295                 return _commit(fd);
296 #elif defined(F_FULLFSYNC)
297                 return (fcntl(fd, F_FULLFSYNC, 0) == -1) ? -1 : 0;
298 #else
299                 errno = ENOSYS;
300                 return -1;
301 #endif
302         }
303         else
304                 return 0;
305 }
306
307 /*
308  * pg_fdatasync --- same as fdatasync except does nothing if enableFsync is off
309  *
310  * Not all platforms have fdatasync; treat as fsync if not available.
311  */
312 int
313 pg_fdatasync(int fd)
314 {
315         if (enableFsync)
316         {
317 #ifdef HAVE_FDATASYNC
318                 return fdatasync(fd);
319 #else
320                 return fsync(fd);
321 #endif
322         }
323         else
324                 return 0;
325 }
326
327 /*
328  * pg_flush_data --- advise OS that the data described won't be needed soon
329  *
330  * Not all platforms have posix_fadvise; treat as noop if not available.
331  */
332 int
333 pg_flush_data(int fd, off_t offset, off_t amount)
334 {
335 #if defined(USE_POSIX_FADVISE) && defined(POSIX_FADV_DONTNEED)
336         return posix_fadvise(fd, offset, amount, POSIX_FADV_DONTNEED);
337 #else
338         return 0;
339 #endif
340 }
341
342
343 /*
344  * InitFileAccess --- initialize this module during backend startup
345  *
346  * This is called during either normal or standalone backend start.
347  * It is *not* called in the postmaster.
348  */
349 void
350 InitFileAccess(void)
351 {
352         Assert(SizeVfdCache == 0);      /* call me only once */
353
354         /* initialize cache header entry */
355         VfdCache = (Vfd *) malloc(sizeof(Vfd));
356         if (VfdCache == NULL)
357                 ereport(FATAL,
358                                 (errcode(ERRCODE_OUT_OF_MEMORY),
359                                  errmsg("out of memory")));
360
361         MemSet((char *) &(VfdCache[0]), 0, sizeof(Vfd));
362         VfdCache->fd = VFD_CLOSED;
363
364         SizeVfdCache = 1;
365
366         /* register proc-exit hook to ensure temp files are dropped at exit */
367         on_proc_exit(AtProcExit_Files, 0);
368 }
369
370 /*
371  * count_usable_fds --- count how many FDs the system will let us open,
372  *              and estimate how many are already open.
373  *
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.
379  *
380  * We assume stdin (FD 0) is available for dup'ing
381  */
382 static void
383 count_usable_fds(int max_to_probe, int *usable_fds, int *already_open)
384 {
385         int                *fd;
386         int                     size;
387         int                     used = 0;
388         int                     highestfd = 0;
389         int                     j;
390
391 #ifdef HAVE_GETRLIMIT
392         struct rlimit rlim;
393         int                     getrlimit_status;
394 #endif
395
396         size = 1024;
397         fd = (int *) palloc(size * sizeof(int));
398
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 */
408
409         /* dup until failure or probe limit reached */
410         for (;;)
411         {
412                 int                     thisfd;
413
414 #ifdef HAVE_GETRLIMIT
415
416                 /*
417                  * don't go beyond RLIMIT_NOFILE; causes irritating kernel logs on
418                  * some platforms
419                  */
420                 if (getrlimit_status == 0 && highestfd >= rlim.rlim_cur - 1)
421                         break;
422 #endif
423
424                 thisfd = dup(0);
425                 if (thisfd < 0)
426                 {
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);
430                         break;
431                 }
432
433                 if (used >= size)
434                 {
435                         size *= 2;
436                         fd = (int *) repalloc(fd, size * sizeof(int));
437                 }
438                 fd[used++] = thisfd;
439
440                 if (highestfd < thisfd)
441                         highestfd = thisfd;
442
443                 if (used >= max_to_probe)
444                         break;
445         }
446
447         /* release the files we opened */
448         for (j = 0; j < used; j++)
449                 close(fd[j]);
450
451         pfree(fd);
452
453         /*
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.
457          */
458         *usable_fds = used;
459         *already_open = highestfd + 1 - used;
460 }
461
462 /*
463  * set_max_safe_fds
464  *              Determine number of filedescriptors that fd.c is allowed to use
465  */
466 void
467 set_max_safe_fds(void)
468 {
469         int                     usable_fds;
470         int                     already_open;
471
472         /*----------
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.
478          *----------
479          */
480         count_usable_fds(max_files_per_process,
481                                          &usable_fds, &already_open);
482
483         max_safe_fds = Min(usable_fds, max_files_per_process - already_open);
484
485         /*
486          * Take off the FDs reserved for system() etc.
487          */
488         max_safe_fds -= NUM_RESERVED_FDS;
489
490         /*
491          * Make sure we still have enough to get by.
492          */
493         if (max_safe_fds < FD_MINFREE)
494                 ereport(FATAL,
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)));
500
501         elog(DEBUG2, "max_safe_fds = %d, usable_fds = %d, already_open = %d",
502                  max_safe_fds, usable_fds, already_open);
503 }
504
505 /*
506  * BasicOpenFile --- same as open(2) except can free other FDs if needed
507  *
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.
515  *
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.
520  */
521 int
522 BasicOpenFile(FileName fileName, int fileFlags, int fileMode)
523 {
524         int                     fd;
525
526 tryAgain:
527         fd = open(fileName, fileFlags, fileMode);
528
529         if (fd >= 0)
530                 return fd;                              /* success! */
531
532         if (errno == EMFILE || errno == ENFILE)
533         {
534                 int                     save_errno = errno;
535
536                 ereport(LOG,
537                                 (errcode(ERRCODE_INSUFFICIENT_RESOURCES),
538                                  errmsg("out of file descriptors: %m; release and retry")));
539                 errno = 0;
540                 if (ReleaseLruFile())
541                         goto tryAgain;
542                 errno = save_errno;
543         }
544
545         return -1;                                      /* failure */
546 }
547
548 #if defined(FDDEBUG)
549
550 static void
551 _dump_lru(void)
552 {
553         int                     mru = VfdCache[0].lruLessRecently;
554         Vfd                *vfdP = &VfdCache[mru];
555         char            buf[2048];
556
557         snprintf(buf, sizeof(buf), "LRU: MOST %d ", mru);
558         while (mru != 0)
559         {
560                 mru = vfdP->lruLessRecently;
561                 vfdP = &VfdCache[mru];
562                 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%d ", mru);
563         }
564         snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "LEAST");
565         elog(LOG, "%s", buf);
566 }
567 #endif   /* FDDEBUG */
568
569 static void
570 Delete(File file)
571 {
572         Vfd                *vfdP;
573
574         Assert(file != 0);
575
576         DO_DB(elog(LOG, "Delete %d (%s)",
577                            file, VfdCache[file].fileName));
578         DO_DB(_dump_lru());
579
580         vfdP = &VfdCache[file];
581
582         VfdCache[vfdP->lruLessRecently].lruMoreRecently = vfdP->lruMoreRecently;
583         VfdCache[vfdP->lruMoreRecently].lruLessRecently = vfdP->lruLessRecently;
584
585         DO_DB(_dump_lru());
586 }
587
588 static void
589 LruDelete(File file)
590 {
591         Vfd                *vfdP;
592
593         Assert(file != 0);
594
595         DO_DB(elog(LOG, "LruDelete %d (%s)",
596                            file, VfdCache[file].fileName));
597
598         vfdP = &VfdCache[file];
599
600         /* delete the vfd record from the LRU ring */
601         Delete(file);
602
603         /* save the seek position */
604         vfdP->seekPos = lseek(vfdP->fd, (off_t) 0, SEEK_CUR);
605         Assert(vfdP->seekPos != (off_t) -1);
606
607         /* close the file */
608         if (close(vfdP->fd))
609                 elog(ERROR, "could not close file \"%s\": %m", vfdP->fileName);
610
611         --nfile;
612         vfdP->fd = VFD_CLOSED;
613 }
614
615 static void
616 Insert(File file)
617 {
618         Vfd                *vfdP;
619
620         Assert(file != 0);
621
622         DO_DB(elog(LOG, "Insert %d (%s)",
623                            file, VfdCache[file].fileName));
624         DO_DB(_dump_lru());
625
626         vfdP = &VfdCache[file];
627
628         vfdP->lruMoreRecently = 0;
629         vfdP->lruLessRecently = VfdCache[0].lruLessRecently;
630         VfdCache[0].lruLessRecently = file;
631         VfdCache[vfdP->lruLessRecently].lruMoreRecently = file;
632
633         DO_DB(_dump_lru());
634 }
635
636 /* returns 0 on success, -1 on re-open failure (with errno set) */
637 static int
638 LruInsert(File file)
639 {
640         Vfd                *vfdP;
641
642         Assert(file != 0);
643
644         DO_DB(elog(LOG, "LruInsert %d (%s)",
645                            file, VfdCache[file].fileName));
646
647         vfdP = &VfdCache[file];
648
649         if (FileIsNotOpen(file))
650         {
651                 while (nfile + numAllocatedDescs >= max_safe_fds)
652                 {
653                         if (!ReleaseLruFile())
654                                 break;
655                 }
656
657                 /*
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...
661                  */
662                 vfdP->fd = BasicOpenFile(vfdP->fileName, vfdP->fileFlags,
663                                                                  vfdP->fileMode);
664                 if (vfdP->fd < 0)
665                 {
666                         DO_DB(elog(LOG, "RE_OPEN FAILED: %d", errno));
667                         return vfdP->fd;
668                 }
669                 else
670                 {
671                         DO_DB(elog(LOG, "RE_OPEN SUCCESS"));
672                         ++nfile;
673                 }
674
675                 /* seek to the right position */
676                 if (vfdP->seekPos != (off_t) 0)
677                 {
678                         off_t           returnValue;
679
680                         returnValue = lseek(vfdP->fd, vfdP->seekPos, SEEK_SET);
681                         Assert(returnValue != (off_t) -1);
682                 }
683         }
684
685         /*
686          * put it at the head of the Lru ring
687          */
688
689         Insert(file);
690
691         return 0;
692 }
693
694 static bool
695 ReleaseLruFile(void)
696 {
697         DO_DB(elog(LOG, "ReleaseLruFile. Opened %d", nfile));
698
699         if (nfile > 0)
700         {
701                 /*
702                  * There are opened files and so there should be at least one used vfd
703                  * in the ring.
704                  */
705                 Assert(VfdCache[0].lruMoreRecently != 0);
706                 LruDelete(VfdCache[0].lruMoreRecently);
707                 return true;                    /* freed a file */
708         }
709         return false;                           /* no files available to free */
710 }
711
712 static File
713 AllocateVfd(void)
714 {
715         Index           i;
716         File            file;
717
718         DO_DB(elog(LOG, "AllocateVfd. Size %lu", SizeVfdCache));
719
720         Assert(SizeVfdCache > 0);       /* InitFileAccess not called? */
721
722         if (VfdCache[0].nextFree == 0)
723         {
724                 /*
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.
728                  */
729                 Size            newCacheSize = SizeVfdCache * 2;
730                 Vfd                *newVfdCache;
731
732                 if (newCacheSize < 32)
733                         newCacheSize = 32;
734
735                 /*
736                  * Be careful not to clobber VfdCache ptr if realloc fails.
737                  */
738                 newVfdCache = (Vfd *) realloc(VfdCache, sizeof(Vfd) * newCacheSize);
739                 if (newVfdCache == NULL)
740                         ereport(ERROR,
741                                         (errcode(ERRCODE_OUT_OF_MEMORY),
742                                          errmsg("out of memory")));
743                 VfdCache = newVfdCache;
744
745                 /*
746                  * Initialize the new entries and link them into the free list.
747                  */
748                 for (i = SizeVfdCache; i < newCacheSize; i++)
749                 {
750                         MemSet((char *) &(VfdCache[i]), 0, sizeof(Vfd));
751                         VfdCache[i].nextFree = i + 1;
752                         VfdCache[i].fd = VFD_CLOSED;
753                 }
754                 VfdCache[newCacheSize - 1].nextFree = 0;
755                 VfdCache[0].nextFree = SizeVfdCache;
756
757                 /*
758                  * Record the new size
759                  */
760                 SizeVfdCache = newCacheSize;
761         }
762
763         file = VfdCache[0].nextFree;
764
765         VfdCache[0].nextFree = VfdCache[file].nextFree;
766
767         return file;
768 }
769
770 static void
771 FreeVfd(File file)
772 {
773         Vfd                *vfdP = &VfdCache[file];
774
775         DO_DB(elog(LOG, "FreeVfd: %d (%s)",
776                            file, vfdP->fileName ? vfdP->fileName : ""));
777
778         if (vfdP->fileName != NULL)
779         {
780                 free(vfdP->fileName);
781                 vfdP->fileName = NULL;
782         }
783         vfdP->fdstate = 0x0;
784
785         vfdP->nextFree = VfdCache[0].nextFree;
786         VfdCache[0].nextFree = file;
787 }
788
789 /* returns 0 on success, -1 on re-open failure (with errno set) */
790 static int
791 FileAccess(File file)
792 {
793         int                     returnValue;
794
795         DO_DB(elog(LOG, "FileAccess %d (%s)",
796                            file, VfdCache[file].fileName));
797
798         /*
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).
801          */
802
803         if (FileIsNotOpen(file))
804         {
805                 returnValue = LruInsert(file);
806                 if (returnValue != 0)
807                         return returnValue;
808         }
809         else if (VfdCache[0].lruLessRecently != file)
810         {
811                 /*
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.
814                  */
815
816                 Delete(file);
817                 Insert(file);
818         }
819
820         return 0;
821 }
822
823 /*
824  *      Called when we get a shared invalidation message on some relation.
825  */
826 #ifdef NOT_USED
827 void
828 FileInvalidate(File file)
829 {
830         Assert(FileIsValid(file));
831         if (!FileIsNotOpen(file))
832                 LruDelete(file);
833 }
834 #endif
835
836 /*
837  * open a file in an arbitrary directory
838  *
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).
842  */
843 File
844 PathNameOpenFile(FileName fileName, int fileFlags, int fileMode)
845 {
846         char       *fnamecopy;
847         File            file;
848         Vfd                *vfdP;
849
850         DO_DB(elog(LOG, "PathNameOpenFile: %s %x %o",
851                            fileName, fileFlags, fileMode));
852
853         /*
854          * We need a malloc'd copy of the file name; fail cleanly if no room.
855          */
856         fnamecopy = strdup(fileName);
857         if (fnamecopy == NULL)
858                 ereport(ERROR,
859                                 (errcode(ERRCODE_OUT_OF_MEMORY),
860                                  errmsg("out of memory")));
861
862         file = AllocateVfd();
863         vfdP = &VfdCache[file];
864
865         while (nfile + numAllocatedDescs >= max_safe_fds)
866         {
867                 if (!ReleaseLruFile())
868                         break;
869         }
870
871         vfdP->fd = BasicOpenFile(fileName, fileFlags, fileMode);
872
873         if (vfdP->fd < 0)
874         {
875                 FreeVfd(file);
876                 free(fnamecopy);
877                 return -1;
878         }
879         ++nfile;
880         DO_DB(elog(LOG, "PathNameOpenFile: success %d",
881                            vfdP->fd));
882
883         Insert(file);
884
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;
889         vfdP->seekPos = 0;
890         vfdP->fdstate = 0x0;
891         vfdP->resowner = NULL;
892
893         return file;
894 }
895
896 /*
897  * Open a temporary file that will disappear when we close it.
898  *
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.
902  *
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.
909  */
910 File
911 OpenTemporaryFile(bool interXact)
912 {
913         File            file = 0;
914
915         /*
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.
919          *
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.
923          */
924         if (numTempTableSpaces > 0 && !interXact)
925         {
926                 Oid                     tblspcOid = GetNextTempTableSpace();
927
928                 if (OidIsValid(tblspcOid))
929                         file = OpenTemporaryFileInTablespace(tblspcOid, false);
930         }
931
932         /*
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.
936          */
937         if (file <= 0)
938                 file = OpenTemporaryFileInTablespace(MyDatabaseTableSpace ?
939                                                                                          MyDatabaseTableSpace :
940                                                                                          DEFAULTTABLESPACE_OID,
941                                                                                          true);
942
943         /* Mark it for deletion at close */
944         VfdCache[file].fdstate |= FD_TEMPORARY;
945
946         /* Register it with the current resource owner */
947         if (!interXact)
948         {
949                 VfdCache[file].fdstate |= FD_XACT_TEMPORARY;
950
951                 ResourceOwnerEnlargeFiles(CurrentResourceOwner);
952                 ResourceOwnerRememberFile(CurrentResourceOwner, file);
953                 VfdCache[file].resowner = CurrentResourceOwner;
954
955                 /* ensure cleanup happens at eoxact */
956                 have_xact_temporary_files = true;
957         }
958
959         return file;
960 }
961
962 /*
963  * Open a temporary file in a specific tablespace.
964  * Subroutine for OpenTemporaryFile, which see for details.
965  */
966 static File
967 OpenTemporaryFileInTablespace(Oid tblspcOid, bool rejectError)
968 {
969         char            tempdirpath[MAXPGPATH];
970         char            tempfilepath[MAXPGPATH];
971         File            file;
972
973         /*
974          * Identify the tempfile directory for this tablespace.
975          *
976          * If someone tries to specify pg_global, use pg_default instead.
977          */
978         if (tblspcOid == DEFAULTTABLESPACE_OID ||
979                 tblspcOid == GLOBALTABLESPACE_OID)
980         {
981                 /* The default tablespace is {datadir}/base */
982                 snprintf(tempdirpath, sizeof(tempdirpath), "base/%s",
983                                  PG_TEMP_FILES_DIR);
984         }
985         else
986         {
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);
990         }
991
992         /*
993          * Generate a tempfile name that should be unique within the current
994          * database instance.
995          */
996         snprintf(tempfilepath, sizeof(tempfilepath), "%s/%s%d.%ld",
997                          tempdirpath, PG_TEMP_FILE_PREFIX, MyProcPid, tempFileCounter++);
998
999         /*
1000          * Open the file.  Note: we don't use O_EXCL, in case there is an orphaned
1001          * temp file that can be reused.
1002          */
1003         file = PathNameOpenFile(tempfilepath,
1004                                                         O_RDWR | O_CREAT | O_TRUNC | PG_BINARY,
1005                                                         0600);
1006         if (file <= 0)
1007         {
1008                 /*
1009                  * We might need to create the tablespace's tempfile directory, if no
1010                  * one has yet done so.
1011                  *
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.
1015                  */
1016                 mkdir(tempdirpath, S_IRWXU);
1017
1018                 file = PathNameOpenFile(tempfilepath,
1019                                                                 O_RDWR | O_CREAT | O_TRUNC | PG_BINARY,
1020                                                                 0600);
1021                 if (file <= 0 && rejectError)
1022                         elog(ERROR, "could not create temporary file \"%s\": %m",
1023                                  tempfilepath);
1024         }
1025
1026         return file;
1027 }
1028
1029 /*
1030  * close a file when done with it
1031  */
1032 void
1033 FileClose(File file)
1034 {
1035         Vfd                *vfdP;
1036
1037         Assert(FileIsValid(file));
1038
1039         DO_DB(elog(LOG, "FileClose: %d (%s)",
1040                            file, VfdCache[file].fileName));
1041
1042         vfdP = &VfdCache[file];
1043
1044         if (!FileIsNotOpen(file))
1045         {
1046                 /* remove the file from the lru ring */
1047                 Delete(file);
1048
1049                 /* close the file */
1050                 if (close(vfdP->fd))
1051                         elog(ERROR, "could not close file \"%s\": %m", vfdP->fileName);
1052
1053                 --nfile;
1054                 vfdP->fd = VFD_CLOSED;
1055         }
1056
1057         /*
1058          * Delete the file if it was temporary, and make a log entry if wanted
1059          */
1060         if (vfdP->fdstate & FD_TEMPORARY)
1061         {
1062                 /*
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.
1068                  */
1069                 vfdP->fdstate &= ~FD_TEMPORARY;
1070
1071                 if (log_temp_files >= 0)
1072                 {
1073                         struct stat filestats;
1074                         int                     stat_errno;
1075
1076                         /* first try the stat() */
1077                         if (stat(vfdP->fileName, &filestats))
1078                                 stat_errno = errno;
1079                         else
1080                                 stat_errno = 0;
1081
1082                         /* in any case do the unlink */
1083                         if (unlink(vfdP->fileName))
1084                                 elog(LOG, "could not unlink file \"%s\": %m", vfdP->fileName);
1085
1086                         /* and last report the stat results */
1087                         if (stat_errno == 0)
1088                         {
1089                                 if ((filestats.st_size / 1024) >= log_temp_files)
1090                                         ereport(LOG,
1091                                                         (errmsg("temporary file: path \"%s\", size %lu",
1092                                                                         vfdP->fileName,
1093                                                                         (unsigned long) filestats.st_size)));
1094                         }
1095                         else
1096                         {
1097                                 errno = stat_errno;
1098                                 elog(LOG, "could not stat file \"%s\": %m", vfdP->fileName);
1099                         }
1100                 }
1101                 else
1102                 {
1103                         /* easy case, just do the unlink */
1104                         if (unlink(vfdP->fileName))
1105                                 elog(LOG, "could not unlink file \"%s\": %m", vfdP->fileName);
1106                 }
1107         }
1108
1109         /* Unregister it from the resource owner */
1110         if (vfdP->resowner)
1111                 ResourceOwnerForgetFile(vfdP->resowner, file);
1112
1113         /*
1114          * Return the Vfd slot to the free list
1115          */
1116         FreeVfd(file);
1117 }
1118
1119 /*
1120  * FilePrefetch - initiate asynchronous read of a given range of the file.
1121  * The logical seek position is unaffected.
1122  *
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
1127  * to read into.
1128  */
1129 int
1130 FilePrefetch(File file, off_t offset, int amount)
1131 {
1132 #if defined(USE_POSIX_FADVISE) && defined(POSIX_FADV_WILLNEED)
1133         int                     returnCode;
1134
1135         Assert(FileIsValid(file));
1136
1137         DO_DB(elog(LOG, "FilePrefetch: %d (%s) " INT64_FORMAT " %d",
1138                            file, VfdCache[file].fileName,
1139                            (int64) offset, amount));
1140
1141         returnCode = FileAccess(file);
1142         if (returnCode < 0)
1143                 return returnCode;
1144
1145         returnCode = posix_fadvise(VfdCache[file].fd, offset, amount,
1146                                                            POSIX_FADV_WILLNEED);
1147
1148         return returnCode;
1149 #else
1150         Assert(FileIsValid(file));
1151         return 0;
1152 #endif
1153 }
1154
1155 int
1156 FileRead(File file, char *buffer, int amount)
1157 {
1158         int                     returnCode;
1159
1160         Assert(FileIsValid(file));
1161
1162         DO_DB(elog(LOG, "FileRead: %d (%s) " INT64_FORMAT " %d %p",
1163                            file, VfdCache[file].fileName,
1164                            (int64) VfdCache[file].seekPos,
1165                            amount, buffer));
1166
1167         returnCode = FileAccess(file);
1168         if (returnCode < 0)
1169                 return returnCode;
1170
1171 retry:
1172         returnCode = read(VfdCache[file].fd, buffer, amount);
1173
1174         if (returnCode >= 0)
1175                 VfdCache[file].seekPos += returnCode;
1176         else
1177         {
1178                 /*
1179                  * Windows may run out of kernel buffers and return "Insufficient
1180                  * system resources" error.  Wait a bit and retry to solve it.
1181                  *
1182                  * It is rumored that EINTR is also possible on some Unix filesystems,
1183                  * in which case immediate retry is indicated.
1184                  */
1185 #ifdef WIN32
1186                 DWORD           error = GetLastError();
1187
1188                 switch (error)
1189                 {
1190                         case ERROR_NO_SYSTEM_RESOURCES:
1191                                 pg_usleep(1000L);
1192                                 errno = EINTR;
1193                                 break;
1194                         default:
1195                                 _dosmaperr(error);
1196                                 break;
1197                 }
1198 #endif
1199                 /* OK to retry if interrupted */
1200                 if (errno == EINTR)
1201                         goto retry;
1202
1203                 /* Trouble, so assume we don't know the file position anymore */
1204                 VfdCache[file].seekPos = FileUnknownPos;
1205         }
1206
1207         return returnCode;
1208 }
1209
1210 int
1211 FileWrite(File file, char *buffer, int amount)
1212 {
1213         int                     returnCode;
1214
1215         Assert(FileIsValid(file));
1216
1217         DO_DB(elog(LOG, "FileWrite: %d (%s) " INT64_FORMAT " %d %p",
1218                            file, VfdCache[file].fileName,
1219                            (int64) VfdCache[file].seekPos,
1220                            amount, buffer));
1221
1222         returnCode = FileAccess(file);
1223         if (returnCode < 0)
1224                 return returnCode;
1225
1226 retry:
1227         errno = 0;
1228         returnCode = write(VfdCache[file].fd, buffer, amount);
1229
1230         /* if write didn't set errno, assume problem is no disk space */
1231         if (returnCode != amount && errno == 0)
1232                 errno = ENOSPC;
1233
1234         if (returnCode >= 0)
1235                 VfdCache[file].seekPos += returnCode;
1236         else
1237         {
1238                 /*
1239                  * See comments in FileRead()
1240                  */
1241 #ifdef WIN32
1242                 DWORD           error = GetLastError();
1243
1244                 switch (error)
1245                 {
1246                         case ERROR_NO_SYSTEM_RESOURCES:
1247                                 pg_usleep(1000L);
1248                                 errno = EINTR;
1249                                 break;
1250                         default:
1251                                 _dosmaperr(error);
1252                                 break;
1253                 }
1254 #endif
1255                 /* OK to retry if interrupted */
1256                 if (errno == EINTR)
1257                         goto retry;
1258
1259                 /* Trouble, so assume we don't know the file position anymore */
1260                 VfdCache[file].seekPos = FileUnknownPos;
1261         }
1262
1263         return returnCode;
1264 }
1265
1266 int
1267 FileSync(File file)
1268 {
1269         int                     returnCode;
1270
1271         Assert(FileIsValid(file));
1272
1273         DO_DB(elog(LOG, "FileSync: %d (%s)",
1274                            file, VfdCache[file].fileName));
1275
1276         returnCode = FileAccess(file);
1277         if (returnCode < 0)
1278                 return returnCode;
1279
1280         return pg_fsync(VfdCache[file].fd);
1281 }
1282
1283 off_t
1284 FileSeek(File file, off_t offset, int whence)
1285 {
1286         int                     returnCode;
1287
1288         Assert(FileIsValid(file));
1289
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));
1294
1295         if (FileIsNotOpen(file))
1296         {
1297                 switch (whence)
1298                 {
1299                         case SEEK_SET:
1300                                 if (offset < 0)
1301                                         elog(ERROR, "invalid seek offset: " INT64_FORMAT,
1302                                                  (int64) offset);
1303                                 VfdCache[file].seekPos = offset;
1304                                 break;
1305                         case SEEK_CUR:
1306                                 VfdCache[file].seekPos += offset;
1307                                 break;
1308                         case SEEK_END:
1309                                 returnCode = FileAccess(file);
1310                                 if (returnCode < 0)
1311                                         return returnCode;
1312                                 VfdCache[file].seekPos = lseek(VfdCache[file].fd,
1313                                                                                            offset, whence);
1314                                 break;
1315                         default:
1316                                 elog(ERROR, "invalid whence: %d", whence);
1317                                 break;
1318                 }
1319         }
1320         else
1321         {
1322                 switch (whence)
1323                 {
1324                         case SEEK_SET:
1325                                 if (offset < 0)
1326                                         elog(ERROR, "invalid seek offset: " INT64_FORMAT,
1327                                                  (int64) offset);
1328                                 if (VfdCache[file].seekPos != offset)
1329                                         VfdCache[file].seekPos = lseek(VfdCache[file].fd,
1330                                                                                                    offset, whence);
1331                                 break;
1332                         case SEEK_CUR:
1333                                 if (offset != 0 || VfdCache[file].seekPos == FileUnknownPos)
1334                                         VfdCache[file].seekPos = lseek(VfdCache[file].fd,
1335                                                                                                    offset, whence);
1336                                 break;
1337                         case SEEK_END:
1338                                 VfdCache[file].seekPos = lseek(VfdCache[file].fd,
1339                                                                                            offset, whence);
1340                                 break;
1341                         default:
1342                                 elog(ERROR, "invalid whence: %d", whence);
1343                                 break;
1344                 }
1345         }
1346         return VfdCache[file].seekPos;
1347 }
1348
1349 /*
1350  * XXX not actually used but here for completeness
1351  */
1352 #ifdef NOT_USED
1353 off_t
1354 FileTell(File file)
1355 {
1356         Assert(FileIsValid(file));
1357         DO_DB(elog(LOG, "FileTell %d (%s)",
1358                            file, VfdCache[file].fileName));
1359         return VfdCache[file].seekPos;
1360 }
1361 #endif
1362
1363 int
1364 FileTruncate(File file, off_t offset)
1365 {
1366         int                     returnCode;
1367
1368         Assert(FileIsValid(file));
1369
1370         DO_DB(elog(LOG, "FileTruncate %d (%s)",
1371                            file, VfdCache[file].fileName));
1372
1373         returnCode = FileAccess(file);
1374         if (returnCode < 0)
1375                 return returnCode;
1376
1377         returnCode = ftruncate(VfdCache[file].fd, offset);
1378         return returnCode;
1379 }
1380
1381 /*
1382  * Return the pathname associated with an open file.
1383  *
1384  * The returned string points to an internal buffer, which is valid until
1385  * the file is closed.
1386  */
1387 char *
1388 FilePathName(File file)
1389 {
1390         Assert(FileIsValid(file));
1391
1392         return VfdCache[file].fileName;
1393 }
1394
1395
1396 /*
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.
1400  *
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.
1406  *
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).
1410  *
1411  * Ideally this should be the *only* direct call of fopen() in the backend.
1412  */
1413 FILE *
1414 AllocateFile(const char *name, const char *mode)
1415 {
1416         FILE       *file;
1417
1418         DO_DB(elog(LOG, "AllocateFile: Allocated %d (%s)",
1419                            numAllocatedDescs, name));
1420
1421         /*
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
1425          * looping.
1426          */
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\"",
1430                          name);
1431
1432 TryAgain:
1433         if ((file = fopen(name, mode)) != NULL)
1434         {
1435                 AllocateDesc *desc = &allocatedDescs[numAllocatedDescs];
1436
1437                 desc->kind = AllocateDescFile;
1438                 desc->desc.file = file;
1439                 desc->create_subid = GetCurrentSubTransactionId();
1440                 numAllocatedDescs++;
1441                 return desc->desc.file;
1442         }
1443
1444         if (errno == EMFILE || errno == ENFILE)
1445         {
1446                 int                     save_errno = errno;
1447
1448                 ereport(LOG,
1449                                 (errcode(ERRCODE_INSUFFICIENT_RESOURCES),
1450                                  errmsg("out of file descriptors: %m; release and retry")));
1451                 errno = 0;
1452                 if (ReleaseLruFile())
1453                         goto TryAgain;
1454                 errno = save_errno;
1455         }
1456
1457         return NULL;
1458 }
1459
1460 /*
1461  * Free an AllocateDesc of either type.
1462  *
1463  * The argument *must* point into the allocatedDescs[] array.
1464  */
1465 static int
1466 FreeDesc(AllocateDesc *desc)
1467 {
1468         int                     result;
1469
1470         /* Close the underlying object */
1471         switch (desc->kind)
1472         {
1473                 case AllocateDescFile:
1474                         result = fclose(desc->desc.file);
1475                         break;
1476                 case AllocateDescDir:
1477                         result = closedir(desc->desc.dir);
1478                         break;
1479                 default:
1480                         elog(ERROR, "AllocateDesc kind not recognized");
1481                         result = 0;                     /* keep compiler quiet */
1482                         break;
1483         }
1484
1485         /* Compact storage in the allocatedDescs array */
1486         numAllocatedDescs--;
1487         *desc = allocatedDescs[numAllocatedDescs];
1488
1489         return result;
1490 }
1491
1492 /*
1493  * Close a file returned by AllocateFile.
1494  *
1495  * Note we do not check fclose's return value --- it is up to the caller
1496  * to handle close errors.
1497  */
1498 int
1499 FreeFile(FILE *file)
1500 {
1501         int                     i;
1502
1503         DO_DB(elog(LOG, "FreeFile: Allocated %d", numAllocatedDescs));
1504
1505         /* Remove file from list of allocated files, if it's present */
1506         for (i = numAllocatedDescs; --i >= 0;)
1507         {
1508                 AllocateDesc *desc = &allocatedDescs[i];
1509
1510                 if (desc->kind == AllocateDescFile && desc->desc.file == file)
1511                         return FreeDesc(desc);
1512         }
1513
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");
1516
1517         return fclose(file);
1518 }
1519
1520
1521 /*
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.
1526  *
1527  * Ideally this should be the *only* direct call of opendir() in the backend.
1528  */
1529 DIR *
1530 AllocateDir(const char *dirname)
1531 {
1532         DIR                *dir;
1533
1534         DO_DB(elog(LOG, "AllocateDir: Allocated %d (%s)",
1535                            numAllocatedDescs, dirname));
1536
1537         /*
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
1541          * looping.
1542          */
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\"",
1546                          dirname);
1547
1548 TryAgain:
1549         if ((dir = opendir(dirname)) != NULL)
1550         {
1551                 AllocateDesc *desc = &allocatedDescs[numAllocatedDescs];
1552
1553                 desc->kind = AllocateDescDir;
1554                 desc->desc.dir = dir;
1555                 desc->create_subid = GetCurrentSubTransactionId();
1556                 numAllocatedDescs++;
1557                 return desc->desc.dir;
1558         }
1559
1560         if (errno == EMFILE || errno == ENFILE)
1561         {
1562                 int                     save_errno = errno;
1563
1564                 ereport(LOG,
1565                                 (errcode(ERRCODE_INSUFFICIENT_RESOURCES),
1566                                  errmsg("out of file descriptors: %m; release and retry")));
1567                 errno = 0;
1568                 if (ReleaseLruFile())
1569                         goto TryAgain;
1570                 errno = save_errno;
1571         }
1572
1573         return NULL;
1574 }
1575
1576 /*
1577  * Read a directory opened with AllocateDir, ereport'ing any error.
1578  *
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,
1582  * you can just do
1583  *
1584  *              dir = AllocateDir(path);
1585  *              while ((dirent = ReadDir(dir, path)) != NULL)
1586  *                      process dirent;
1587  *              FreeDir(dir);
1588  *
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
1591  * shortcut.)
1592  *
1593  * The pathname passed to AllocateDir must be passed to this routine too,
1594  * but it is only used for error reporting.
1595  */
1596 struct dirent *
1597 ReadDir(DIR *dir, const char *dirname)
1598 {
1599         struct dirent *dent;
1600
1601         /* Give a generic message for AllocateDir failure, if caller didn't */
1602         if (dir == NULL)
1603                 ereport(ERROR,
1604                                 (errcode_for_file_access(),
1605                                  errmsg("could not open directory \"%s\": %m",
1606                                                 dirname)));
1607
1608         errno = 0;
1609         if ((dent = readdir(dir)) != NULL)
1610                 return dent;
1611
1612 #ifdef WIN32
1613
1614         /*
1615          * This fix is in mingw cvs (runtime/mingwex/dirent.c rev 1.4), but not in
1616          * released version
1617          */
1618         if (GetLastError() == ERROR_NO_MORE_FILES)
1619                 errno = 0;
1620 #endif
1621
1622         if (errno)
1623                 ereport(ERROR,
1624                                 (errcode_for_file_access(),
1625                                  errmsg("could not read directory \"%s\": %m",
1626                                                 dirname)));
1627         return NULL;
1628 }
1629
1630 /*
1631  * Close a directory opened with AllocateDir.
1632  *
1633  * Note we do not check closedir's return value --- it is up to the caller
1634  * to handle close errors.
1635  */
1636 int
1637 FreeDir(DIR *dir)
1638 {
1639         int                     i;
1640
1641         DO_DB(elog(LOG, "FreeDir: Allocated %d", numAllocatedDescs));
1642
1643         /* Remove dir from list of allocated dirs, if it's present */
1644         for (i = numAllocatedDescs; --i >= 0;)
1645         {
1646                 AllocateDesc *desc = &allocatedDescs[i];
1647
1648                 if (desc->kind == AllocateDescDir && desc->desc.dir == dir)
1649                         return FreeDesc(desc);
1650         }
1651
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");
1654
1655         return closedir(dir);
1656 }
1657
1658
1659 /*
1660  * closeAllVfds
1661  *
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.
1665  */
1666 void
1667 closeAllVfds(void)
1668 {
1669         Index           i;
1670
1671         if (SizeVfdCache > 0)
1672         {
1673                 Assert(FileIsNotOpen(0));               /* Make sure ring not corrupted */
1674                 for (i = 1; i < SizeVfdCache; i++)
1675                 {
1676                         if (!FileIsNotOpen(i))
1677                                 LruDelete(i);
1678                 }
1679         }
1680 }
1681
1682
1683 /*
1684  * SetTempTablespaces
1685  *
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).
1691  */
1692 void
1693 SetTempTablespaces(Oid *tableSpaces, int numSpaces)
1694 {
1695         Assert(numSpaces >= 0);
1696         tempTableSpaces = tableSpaces;
1697         numTempTableSpaces = numSpaces;
1698
1699         /*
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.
1706          */
1707         if (numSpaces > 1)
1708                 nextTempTableSpace = random() % numSpaces;
1709         else
1710                 nextTempTableSpace = 0;
1711 }
1712
1713 /*
1714  * TempTablespacesAreSet
1715  *
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
1718  * state.)
1719  */
1720 bool
1721 TempTablespacesAreSet(void)
1722 {
1723         return (numTempTableSpaces >= 0);
1724 }
1725
1726 /*
1727  * GetNextTempTableSpace
1728  *
1729  * Select the next temp tablespace to use.      A result of InvalidOid means
1730  * to use the current database's default tablespace.
1731  */
1732 Oid
1733 GetNextTempTableSpace(void)
1734 {
1735         if (numTempTableSpaces > 0)
1736         {
1737                 /* Advance nextTempTableSpace counter with wraparound */
1738                 if (++nextTempTableSpace >= numTempTableSpaces)
1739                         nextTempTableSpace = 0;
1740                 return tempTableSpaces[nextTempTableSpace];
1741         }
1742         return InvalidOid;
1743 }
1744
1745
1746 /*
1747  * AtEOSubXact_Files
1748  *
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.
1752  */
1753 void
1754 AtEOSubXact_Files(bool isCommit, SubTransactionId mySubid,
1755                                   SubTransactionId parentSubid)
1756 {
1757         Index           i;
1758
1759         for (i = 0; i < numAllocatedDescs; i++)
1760         {
1761                 if (allocatedDescs[i].create_subid == mySubid)
1762                 {
1763                         if (isCommit)
1764                                 allocatedDescs[i].create_subid = parentSubid;
1765                         else
1766                         {
1767                                 /* have to recheck the item after FreeDesc (ugly) */
1768                                 FreeDesc(&allocatedDescs[i--]);
1769                         }
1770                 }
1771         }
1772 }
1773
1774 /*
1775  * AtEOXact_Files
1776  *
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.
1783  */
1784 void
1785 AtEOXact_Files(void)
1786 {
1787         CleanupTempFiles(false);
1788         tempTableSpaces = NULL;
1789         numTempTableSpaces = -1;
1790 }
1791
1792 /*
1793  * AtProcExit_Files
1794  *
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.
1797  */
1798 static void
1799 AtProcExit_Files(int code, Datum arg)
1800 {
1801         CleanupTempFiles(true);
1802 }
1803
1804 /*
1805  * Close temporary files and delete their underlying files.
1806  *
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.
1812  */
1813 static void
1814 CleanupTempFiles(bool isProcExit)
1815 {
1816         Index           i;
1817
1818         /*
1819          * Careful here: at proc_exit we need extra cleanup, not just
1820          * xact_temporary files.
1821          */
1822         if (isProcExit || have_xact_temporary_files)
1823         {
1824                 Assert(FileIsNotOpen(0));               /* Make sure ring not corrupted */
1825                 for (i = 1; i < SizeVfdCache; i++)
1826                 {
1827                         unsigned short fdstate = VfdCache[i].fdstate;
1828
1829                         if ((fdstate & FD_TEMPORARY) && VfdCache[i].fileName != NULL)
1830                         {
1831                                 /*
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.
1837                                  */
1838                                 if (isProcExit)
1839                                         FileClose(i);
1840                                 else if (fdstate & FD_XACT_TEMPORARY)
1841                                 {
1842                                         elog(WARNING,
1843                                                  "temporary file %s not closed at end-of-transaction",
1844                                                  VfdCache[i].fileName);
1845                                         FileClose(i);
1846                                 }
1847                         }
1848                 }
1849
1850                 have_xact_temporary_files = false;
1851         }
1852
1853         /* Clean up "allocated" stdio files and dirs. */
1854         while (numAllocatedDescs > 0)
1855                 FreeDesc(&allocatedDescs[0]);
1856 }
1857
1858
1859 /*
1860  * Remove temporary and temporary relation files left over from a prior
1861  * postmaster session
1862  *
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.
1866  *
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
1871  * file name.
1872  */
1873 void
1874 RemovePgTempFiles(void)
1875 {
1876         char            temp_path[MAXPGPATH];
1877         DIR                *spc_dir;
1878         struct dirent *spc_de;
1879
1880         /*
1881          * First process temp files in pg_default ($PGDATA/base)
1882          */
1883         snprintf(temp_path, sizeof(temp_path), "base/%s", PG_TEMP_FILES_DIR);
1884         RemovePgTempFilesInDir(temp_path);
1885         RemovePgTempRelationFiles("base");
1886
1887         /*
1888          * Cycle through temp directories for all non-default tablespaces.
1889          */
1890         spc_dir = AllocateDir("pg_tblspc");
1891
1892         while ((spc_de = ReadDir(spc_dir, "pg_tblspc")) != NULL)
1893         {
1894                 if (strcmp(spc_de->d_name, ".") == 0 ||
1895                         strcmp(spc_de->d_name, "..") == 0)
1896                         continue;
1897
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);
1901
1902                 snprintf(temp_path, sizeof(temp_path), "pg_tblspc/%s/%s",
1903                                  spc_de->d_name, TABLESPACE_VERSION_DIRECTORY);
1904                 RemovePgTempRelationFiles(temp_path);
1905         }
1906
1907         FreeDir(spc_dir);
1908
1909         /*
1910          * In EXEC_BACKEND case there is a pgsql_tmp directory at the top level of
1911          * DataDir as well.
1912          */
1913 #ifdef EXEC_BACKEND
1914         RemovePgTempFilesInDir(PG_TEMP_FILES_DIR);
1915 #endif
1916 }
1917
1918 /* Process one pgsql_tmp directory for RemovePgTempFiles */
1919 static void
1920 RemovePgTempFilesInDir(const char *tmpdirname)
1921 {
1922         DIR                *temp_dir;
1923         struct dirent *temp_de;
1924         char            rm_path[MAXPGPATH];
1925
1926         temp_dir = AllocateDir(tmpdirname);
1927         if (temp_dir == NULL)
1928         {
1929                 /* anything except ENOENT is fishy */
1930                 if (errno != ENOENT)
1931                         elog(LOG,
1932                                  "could not open temporary-files directory \"%s\": %m",
1933                                  tmpdirname);
1934                 return;
1935         }
1936
1937         while ((temp_de = ReadDir(temp_dir, tmpdirname)) != NULL)
1938         {
1939                 if (strcmp(temp_de->d_name, ".") == 0 ||
1940                         strcmp(temp_de->d_name, "..") == 0)
1941                         continue;
1942
1943                 snprintf(rm_path, sizeof(rm_path), "%s/%s",
1944                                  tmpdirname, temp_de->d_name);
1945
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 */
1950                 else
1951                         elog(LOG,
1952                                  "unexpected file found in temporary-files directory: \"%s\"",
1953                                  rm_path);
1954         }
1955
1956         FreeDir(temp_dir);
1957 }
1958
1959 /* Process one tablespace directory, look for per-DB subdirectories */
1960 static void
1961 RemovePgTempRelationFiles(const char *tsdirname)
1962 {
1963         DIR                *ts_dir;
1964         struct dirent *de;
1965         char            dbspace_path[MAXPGPATH];
1966
1967         ts_dir = AllocateDir(tsdirname);
1968         if (ts_dir == NULL)
1969         {
1970                 /* anything except ENOENT is fishy */
1971                 if (errno != ENOENT)
1972                         elog(LOG,
1973                                  "could not open tablespace directory \"%s\": %m",
1974                                  tsdirname);
1975                 return;
1976         }
1977
1978         while ((de = ReadDir(ts_dir, tsdirname)) != NULL)
1979         {
1980                 int                     i = 0;
1981
1982                 /*
1983                  * We're only interested in the per-database directories, which have
1984                  * numeric names.  Note that this code will also (properly) ignore "."
1985                  * and "..".
1986                  */
1987                 while (isdigit((unsigned char) de->d_name[i]))
1988                         ++i;
1989                 if (de->d_name[i] != '\0' || i == 0)
1990                         continue;
1991
1992                 snprintf(dbspace_path, sizeof(dbspace_path), "%s/%s",
1993                                  tsdirname, de->d_name);
1994                 RemovePgTempRelationFilesInDbspace(dbspace_path);
1995         }
1996
1997         FreeDir(ts_dir);
1998 }
1999
2000 /* Process one per-dbspace directory for RemovePgTempRelationFiles */
2001 static void
2002 RemovePgTempRelationFilesInDbspace(const char *dbspacedirname)
2003 {
2004         DIR                *dbspace_dir;
2005         struct dirent *de;
2006         char            rm_path[MAXPGPATH];
2007
2008         dbspace_dir = AllocateDir(dbspacedirname);
2009         if (dbspace_dir == NULL)
2010         {
2011                 /* we just saw this directory, so it really ought to be there */
2012                 elog(LOG,
2013                          "could not open dbspace directory \"%s\": %m",
2014                          dbspacedirname);
2015                 return;
2016         }
2017
2018         while ((de = ReadDir(dbspace_dir, dbspacedirname)) != NULL)
2019         {
2020                 if (!looks_like_temp_rel_name(de->d_name))
2021                         continue;
2022
2023                 snprintf(rm_path, sizeof(rm_path), "%s/%s",
2024                                  dbspacedirname, de->d_name);
2025
2026                 unlink(rm_path);                /* note we ignore any error */
2027         }
2028
2029         FreeDir(dbspace_dir);
2030 }
2031
2032 /* t<digits>_<digits>, or t<digits>_<digits>_<forkname> */
2033 static bool
2034 looks_like_temp_rel_name(const char *name)
2035 {
2036         int                     pos;
2037         int                     savepos;
2038
2039         /* Must start with "t". */
2040         if (name[0] != 't')
2041                 return false;
2042
2043         /* Followed by a non-empty string of digits and then an underscore. */
2044         for (pos = 1; isdigit((unsigned char) name[pos]); ++pos)
2045                 ;
2046         if (pos == 1 || name[pos] != '_')
2047                 return false;
2048
2049         /* Followed by another nonempty string of digits. */
2050         for (savepos = ++pos; isdigit((unsigned char) name[pos]); ++pos)
2051                 ;
2052         if (savepos == pos)
2053                 return false;
2054
2055         /* We might have _forkname or .segment or both. */
2056         if (name[pos] == '_')
2057         {
2058                 int                     forkchar = forkname_chars(&name[pos + 1], NULL);
2059
2060                 if (forkchar <= 0)
2061                         return false;
2062                 pos += forkchar + 1;
2063         }
2064         if (name[pos] == '.')
2065         {
2066                 int                     segchar;
2067
2068                 for (segchar = 1; isdigit((unsigned char) name[pos + segchar]); ++segchar)
2069                         ;
2070                 if (segchar <= 1)
2071                         return false;
2072                 pos += segchar;
2073         }
2074
2075         /* Now we should be at the end. */
2076         if (name[pos] != '\0')
2077                 return false;
2078         return true;
2079 }