1 /*-------------------------------------------------------------------------
4 * Management of large buffered temporary files.
6 * Portions Copyright (c) 1996-2018, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
10 * src/backend/storage/file/buffile.c
14 * BufFiles provide a very incomplete emulation of stdio atop virtual Files
15 * (as managed by fd.c). Currently, we only support the buffered-I/O
16 * aspect of stdio: a read or write of the low-level File occurs only
17 * when the buffer is filled or emptied. This is an even bigger win
18 * for virtual Files than for ordinary kernel files, since reducing the
19 * frequency with which a virtual File is touched reduces "thrashing"
20 * of opening/closing file descriptors.
22 * Note that BufFile structs are allocated with palloc(), and therefore
23 * will go away automatically at query/transaction end. Since the underlying
24 * virtual Files are made with OpenTemporaryFile, all resources for
25 * the file are certain to be cleaned up even if processing is aborted
26 * by ereport(ERROR). The data structures required are made in the
27 * palloc context that was current when the BufFile was created, and
28 * any external resources such as temp files are owned by the ResourceOwner
29 * that was current at that time.
31 * BufFile also supports temporary files that exceed the OS file size limit
32 * (by opening multiple fd.c temporary files). This is an essential feature
33 * for sorts and hashjoins on large amounts of data.
35 * BufFile supports temporary files that can be made read-only and shared with
36 * other backends, as infrastructure for parallel execution. Such files need
37 * to be created as a member of a SharedFileSet that all participants are
39 *-------------------------------------------------------------------------
44 #include "executor/instrument.h"
45 #include "miscadmin.h"
47 #include "storage/fd.h"
48 #include "storage/buffile.h"
49 #include "storage/buf_internals.h"
50 #include "utils/resowner.h"
53 * We break BufFiles into gigabyte-sized segments, regardless of RELSEG_SIZE.
54 * The reason is that we'd like large BufFiles to be spread across multiple
55 * tablespaces when available.
57 #define MAX_PHYSICAL_FILESIZE 0x40000000
58 #define BUFFILE_SEG_SIZE (MAX_PHYSICAL_FILESIZE / BLCKSZ)
61 * This data structure represents a buffered file that consists of one or
62 * more physical files (each accessed through a virtual file descriptor
67 int numFiles; /* number of physical files in set */
68 /* all files except the last have length exactly MAX_PHYSICAL_FILESIZE */
69 File *files; /* palloc'd array with numFiles entries */
70 off_t *offsets; /* palloc'd array with numFiles entries */
73 * offsets[i] is the current seek position of files[i]. We use this to
74 * avoid making redundant FileSeek calls.
77 bool isInterXact; /* keep open over transactions? */
78 bool dirty; /* does buffer need to be written? */
79 bool readOnly; /* has the file been set to read only? */
81 SharedFileSet *fileset; /* space for segment files if shared */
82 const char *name; /* name of this BufFile if shared */
85 * resowner is the ResourceOwner to use for underlying temp files. (We
86 * don't need to remember the memory context we're using explicitly,
87 * because after creation we only repalloc our arrays larger.)
89 ResourceOwner resowner;
92 * "current pos" is position of start of buffer within the logical file.
93 * Position as seen by user of BufFile is (curFile, curOffset + pos).
95 int curFile; /* file index (0..n) part of current pos */
96 off_t curOffset; /* offset part of current pos */
97 int pos; /* next read/write position in buffer */
98 int nbytes; /* total # of valid bytes in buffer */
99 PGAlignedBlock buffer;
102 static BufFile *makeBufFileCommon(int nfiles);
103 static BufFile *makeBufFile(File firstfile);
104 static void extendBufFile(BufFile *file);
105 static void BufFileLoadBuffer(BufFile *file);
106 static void BufFileDumpBuffer(BufFile *file);
107 static int BufFileFlush(BufFile *file);
108 static File MakeNewSharedSegment(BufFile *file, int segment);
111 * Create BufFile and perform the common initialization.
114 makeBufFileCommon(int nfiles)
116 BufFile *file = (BufFile *) palloc(sizeof(BufFile));
118 file->numFiles = nfiles;
119 file->offsets = (off_t *) palloc0(sizeof(off_t) * nfiles);
120 file->isInterXact = false;
122 file->resowner = CurrentResourceOwner;
124 file->curOffset = 0L;
132 * Create a BufFile given the first underlying physical file.
133 * NOTE: caller must set isInterXact if appropriate.
136 makeBufFile(File firstfile)
138 BufFile *file = makeBufFileCommon(1);
140 file->files = (File *) palloc(sizeof(File));
141 file->files[0] = firstfile;
142 file->readOnly = false;
143 file->fileset = NULL;
150 * Add another component temp file.
153 extendBufFile(BufFile *file)
156 ResourceOwner oldowner;
158 /* Be sure to associate the file with the BufFile's resource owner */
159 oldowner = CurrentResourceOwner;
160 CurrentResourceOwner = file->resowner;
162 if (file->fileset == NULL)
163 pfile = OpenTemporaryFile(file->isInterXact);
165 pfile = MakeNewSharedSegment(file, file->numFiles);
169 CurrentResourceOwner = oldowner;
171 file->files = (File *) repalloc(file->files,
172 (file->numFiles + 1) * sizeof(File));
173 file->offsets = (off_t *) repalloc(file->offsets,
174 (file->numFiles + 1) * sizeof(off_t));
175 file->files[file->numFiles] = pfile;
176 file->offsets[file->numFiles] = 0L;
181 * Create a BufFile for a new temporary file (which will expand to become
182 * multiple temporary files if more than MAX_PHYSICAL_FILESIZE bytes are
185 * If interXact is true, the temp file will not be automatically deleted
186 * at end of transaction.
188 * Note: if interXact is true, the caller had better be calling us in a
189 * memory context, and with a resource owner, that will survive across
190 * transaction boundaries.
193 BufFileCreateTemp(bool interXact)
198 pfile = OpenTemporaryFile(interXact);
201 file = makeBufFile(pfile);
202 file->isInterXact = interXact;
208 * Build the name for a given segment of a given BufFile.
211 SharedSegmentName(char *name, const char *buffile_name, int segment)
213 snprintf(name, MAXPGPATH, "%s.%d", buffile_name, segment);
217 * Create a new segment file backing a shared BufFile.
220 MakeNewSharedSegment(BufFile *buffile, int segment)
222 char name[MAXPGPATH];
226 * It is possible that there are files left over from before a crash
227 * restart with the same name. In order for BufFileOpenShared() not to
228 * get confused about how many segments there are, we'll unlink the next
229 * segment number if it already exists.
231 SharedSegmentName(name, buffile->name, segment + 1);
232 SharedFileSetDelete(buffile->fileset, name, true);
234 /* Create the new segment. */
235 SharedSegmentName(name, buffile->name, segment);
236 file = SharedFileSetCreate(buffile->fileset, name);
238 /* SharedFileSetCreate would've errored out */
245 * Create a BufFile that can be discovered and opened read-only by other
246 * backends that are attached to the same SharedFileSet using the same name.
248 * The naming scheme for shared BufFiles is left up to the calling code. The
249 * name will appear as part of one or more filenames on disk, and might
250 * provide clues to administrators about which subsystem is generating
251 * temporary file data. Since each SharedFileSet object is backed by one or
252 * more uniquely named temporary directory, names don't conflict with
253 * unrelated SharedFileSet objects.
256 BufFileCreateShared(SharedFileSet *fileset, const char *name)
260 file = makeBufFileCommon(1);
261 file->fileset = fileset;
262 file->name = pstrdup(name);
263 file->files = (File *) palloc(sizeof(File));
264 file->files[0] = MakeNewSharedSegment(file, 0);
265 file->readOnly = false;
271 * Open a file that was previously created in another backend (or this one)
272 * with BufFileCreateShared in the same SharedFileSet using the same name.
273 * The backend that created the file must have called BufFileClose() or
274 * BufFileExportShared() to make sure that it is ready to be opened by other
275 * backends and render it read-only.
278 BufFileOpenShared(SharedFileSet *fileset, const char *name)
281 char segment_name[MAXPGPATH];
286 files = palloc(sizeof(File) * capacity);
289 * We don't know how many segments there are, so we'll probe the
290 * filesystem to find out.
294 /* See if we need to expand our file segment array. */
295 if (nfiles + 1 > capacity)
298 files = repalloc(files, sizeof(File) * capacity);
300 /* Try to load a segment. */
301 SharedSegmentName(segment_name, name, nfiles);
302 files[nfiles] = SharedFileSetOpen(fileset, segment_name);
303 if (files[nfiles] <= 0)
307 CHECK_FOR_INTERRUPTS();
311 * If we didn't find any files at all, then no BufFile exists with this
316 (errcode_for_file_access(),
317 errmsg("could not open BufFile \"%s\"", name)));
319 file = makeBufFileCommon(nfiles);
321 file->readOnly = true; /* Can't write to files opened this way */
322 file->fileset = fileset;
323 file->name = pstrdup(name);
329 * Delete a BufFile that was created by BufFileCreateShared in the given
330 * SharedFileSet using the given name.
332 * It is not necessary to delete files explicitly with this function. It is
333 * provided only as a way to delete files proactively, rather than waiting for
334 * the SharedFileSet to be cleaned up.
336 * Only one backend should attempt to delete a given name, and should know
337 * that it exists and has been exported or closed.
340 BufFileDeleteShared(SharedFileSet *fileset, const char *name)
342 char segment_name[MAXPGPATH];
347 * We don't know how many segments the file has. We'll keep deleting
348 * until we run out. If we don't manage to find even an initial segment,
353 SharedSegmentName(segment_name, name, segment);
354 if (!SharedFileSetDelete(fileset, segment_name, true))
359 CHECK_FOR_INTERRUPTS();
363 elog(ERROR, "could not delete unknown shared BufFile \"%s\"", name);
367 * BufFileExportShared --- flush and make read-only, in preparation for sharing.
370 BufFileExportShared(BufFile *file)
372 /* Must be a file belonging to a SharedFileSet. */
373 Assert(file->fileset != NULL);
375 /* It's probably a bug if someone calls this twice. */
376 Assert(!file->readOnly);
379 file->readOnly = true;
385 * Like fclose(), this also implicitly FileCloses the underlying File.
388 BufFileClose(BufFile *file)
392 /* flush any unwritten data */
394 /* close and delete the underlying file(s) */
395 for (i = 0; i < file->numFiles; i++)
396 FileClose(file->files[i]);
397 /* release the buffer space */
399 pfree(file->offsets);
406 * Load some data into buffer, if possible, starting from curOffset.
407 * At call, must have dirty = false, pos and nbytes = 0.
408 * On exit, nbytes is number of bytes loaded.
411 BufFileLoadBuffer(BufFile *file)
416 * Advance to next component file if necessary and possible.
418 if (file->curOffset >= MAX_PHYSICAL_FILESIZE &&
419 file->curFile + 1 < file->numFiles)
422 file->curOffset = 0L;
426 * May need to reposition physical file.
428 thisfile = file->files[file->curFile];
429 if (file->curOffset != file->offsets[file->curFile])
431 if (FileSeek(thisfile, file->curOffset, SEEK_SET) != file->curOffset)
432 return; /* seek failed, read nothing */
433 file->offsets[file->curFile] = file->curOffset;
437 * Read whatever we can get, up to a full bufferload.
439 file->nbytes = FileRead(thisfile,
441 sizeof(file->buffer),
442 WAIT_EVENT_BUFFILE_READ);
443 if (file->nbytes < 0)
445 file->offsets[file->curFile] += file->nbytes;
446 /* we choose not to advance curOffset here */
448 if (file->nbytes > 0)
449 pgBufferUsage.temp_blks_read++;
455 * Dump buffer contents starting at curOffset.
456 * At call, should have dirty = true, nbytes > 0.
457 * On exit, dirty is cleared if successful write, and curOffset is advanced.
460 BufFileDumpBuffer(BufFile *file)
467 * Unlike BufFileLoadBuffer, we must dump the whole buffer even if it
468 * crosses a component-file boundary; so we need a loop.
470 while (wpos < file->nbytes)
475 * Advance to next component file if necessary and possible.
477 if (file->curOffset >= MAX_PHYSICAL_FILESIZE)
479 while (file->curFile + 1 >= file->numFiles)
482 file->curOffset = 0L;
486 * Determine how much we need to write into this file.
488 bytestowrite = file->nbytes - wpos;
489 availbytes = MAX_PHYSICAL_FILESIZE - file->curOffset;
491 if ((off_t) bytestowrite > availbytes)
492 bytestowrite = (int) availbytes;
495 * May need to reposition physical file.
497 thisfile = file->files[file->curFile];
498 if (file->curOffset != file->offsets[file->curFile])
500 if (FileSeek(thisfile, file->curOffset, SEEK_SET) != file->curOffset)
501 return; /* seek failed, give up */
502 file->offsets[file->curFile] = file->curOffset;
504 bytestowrite = FileWrite(thisfile,
505 file->buffer.data + wpos,
507 WAIT_EVENT_BUFFILE_WRITE);
508 if (bytestowrite <= 0)
509 return; /* failed to write */
510 file->offsets[file->curFile] += bytestowrite;
511 file->curOffset += bytestowrite;
512 wpos += bytestowrite;
514 pgBufferUsage.temp_blks_written++;
519 * At this point, curOffset has been advanced to the end of the buffer,
520 * ie, its original value + nbytes. We need to make it point to the
521 * logical file position, ie, original value + pos, in case that is less
522 * (as could happen due to a small backwards seek in a dirty buffer!)
524 file->curOffset -= (file->nbytes - file->pos);
525 if (file->curOffset < 0) /* handle possible segment crossing */
528 Assert(file->curFile >= 0);
529 file->curOffset += MAX_PHYSICAL_FILESIZE;
533 * Now we can set the buffer empty without changing the logical position
542 * Like fread() except we assume 1-byte element size.
545 BufFileRead(BufFile *file, void *ptr, size_t size)
552 if (BufFileFlush(file) != 0)
553 return 0; /* could not flush... */
554 Assert(!file->dirty);
559 if (file->pos >= file->nbytes)
561 /* Try to load more data into buffer. */
562 file->curOffset += file->pos;
565 BufFileLoadBuffer(file);
566 if (file->nbytes <= 0)
567 break; /* no more data available */
570 nthistime = file->nbytes - file->pos;
571 if (nthistime > size)
573 Assert(nthistime > 0);
575 memcpy(ptr, file->buffer.data + file->pos, nthistime);
577 file->pos += nthistime;
578 ptr = (void *) ((char *) ptr + nthistime);
589 * Like fwrite() except we assume 1-byte element size.
592 BufFileWrite(BufFile *file, void *ptr, size_t size)
597 Assert(!file->readOnly);
601 if (file->pos >= BLCKSZ)
603 /* Buffer full, dump it out */
606 BufFileDumpBuffer(file);
608 break; /* I/O error */
612 /* Hmm, went directly from reading to writing? */
613 file->curOffset += file->pos;
619 nthistime = BLCKSZ - file->pos;
620 if (nthistime > size)
622 Assert(nthistime > 0);
624 memcpy(file->buffer.data + file->pos, ptr, nthistime);
627 file->pos += nthistime;
628 if (file->nbytes < file->pos)
629 file->nbytes = file->pos;
630 ptr = (void *) ((char *) ptr + nthistime);
632 nwritten += nthistime;
644 BufFileFlush(BufFile *file)
648 BufFileDumpBuffer(file);
659 * Like fseek(), except that target position needs two values in order to
660 * work when logical filesize exceeds maximum value representable by off_t.
661 * We do not support relative seeks across more than that, however.
663 * Result is 0 if OK, EOF if not. Logical position is not moved if an
664 * impossible seek is attempted.
667 BufFileSeek(BufFile *file, int fileno, off_t offset, int whence)
683 * Relative seek considers only the signed offset, ignoring
684 * fileno. Note that large offsets (> 1 gig) risk overflow in this
685 * add, unless we have 64-bit off_t.
687 newFile = file->curFile;
688 newOffset = (file->curOffset + file->pos) + offset;
692 /* could be implemented, not needed currently */
696 elog(ERROR, "invalid whence: %d", whence);
699 while (newOffset < 0)
703 newOffset += MAX_PHYSICAL_FILESIZE;
705 if (newFile == file->curFile &&
706 newOffset >= file->curOffset &&
707 newOffset <= file->curOffset + file->nbytes)
710 * Seek is to a point within existing buffer; we can just adjust
711 * pos-within-buffer, without flushing buffer. Note this is OK
712 * whether reading or writing, but buffer remains dirty if we were
715 file->pos = (int) (newOffset - file->curOffset);
718 /* Otherwise, must reposition buffer, so flush any dirty data */
719 if (BufFileFlush(file) != 0)
723 * At this point and no sooner, check for seek past last segment. The
724 * above flush could have created a new segment, so checking sooner would
725 * not work (at least not with this code).
728 /* convert seek to "start of next seg" to "end of last seg" */
729 if (newFile == file->numFiles && newOffset == 0)
732 newOffset = MAX_PHYSICAL_FILESIZE;
734 while (newOffset > MAX_PHYSICAL_FILESIZE)
736 if (++newFile >= file->numFiles)
738 newOffset -= MAX_PHYSICAL_FILESIZE;
740 if (newFile >= file->numFiles)
743 file->curFile = newFile;
744 file->curOffset = newOffset;
751 BufFileTell(BufFile *file, int *fileno, off_t *offset)
753 *fileno = file->curFile;
754 *offset = file->curOffset + file->pos;
758 * BufFileSeekBlock --- block-oriented seek
760 * Performs absolute seek to the start of the n'th BLCKSZ-sized block of
761 * the file. Note that users of this interface will fail if their files
762 * exceed BLCKSZ * LONG_MAX bytes, but that is quite a lot; we don't work
763 * with tables bigger than that, either...
765 * Result is 0 if OK, EOF if not. Logical position is not moved if an
766 * impossible seek is attempted.
769 BufFileSeekBlock(BufFile *file, long blknum)
771 return BufFileSeek(file,
772 (int) (blknum / BUFFILE_SEG_SIZE),
773 (off_t) (blknum % BUFFILE_SEG_SIZE) * BLCKSZ,
779 * BufFileTellBlock --- block-oriented tell
781 * Any fractional part of a block in the current seek position is ignored.
784 BufFileTellBlock(BufFile *file)
788 blknum = (file->curOffset + file->pos) / BLCKSZ;
789 blknum += file->curFile * BUFFILE_SEG_SIZE;
796 * Return the current file size.
798 * Counts any holes left behind by BufFileAppend as part of the size.
799 * Returns -1 on error.
802 BufFileSize(BufFile *file)
806 /* Get the size of the last physical file by seeking to end. */
807 lastFileSize = FileSeek(file->files[file->numFiles - 1], 0, SEEK_END);
808 if (lastFileSize < 0)
810 file->offsets[file->numFiles - 1] = lastFileSize;
812 return ((file->numFiles - 1) * (off_t) MAX_PHYSICAL_FILESIZE) +
817 * Append the contents of source file (managed within shared fileset) to
818 * end of target file (managed within same shared fileset).
820 * Note that operation subsumes ownership of underlying resources from
821 * "source". Caller should never call BufFileClose against source having
822 * called here first. Resource owners for source and target must match,
825 * This operation works by manipulating lists of segment files, so the
826 * file content is always appended at a MAX_PHYSICAL_FILESIZE-aligned
827 * boundary, typically creating empty holes before the boundary. These
828 * areas do not contain any interesting data, and cannot be read from by
831 * Returns the block number within target where the contents of source
832 * begins. Caller should apply this as an offset when working off block
833 * positions that are in terms of the original BufFile space.
836 BufFileAppend(BufFile *target, BufFile *source)
838 long startBlock = target->numFiles * BUFFILE_SEG_SIZE;
839 int newNumFiles = target->numFiles + source->numFiles;
842 Assert(target->fileset != NULL);
843 Assert(source->readOnly);
844 Assert(!source->dirty);
845 Assert(source->fileset != NULL);
847 if (target->resowner != source->resowner)
848 elog(ERROR, "could not append BufFile with non-matching resource owner");
850 target->files = (File *)
851 repalloc(target->files, sizeof(File) * newNumFiles);
852 target->offsets = (off_t *)
853 repalloc(target->offsets, sizeof(off_t) * newNumFiles);
854 for (i = target->numFiles; i < newNumFiles; i++)
856 target->files[i] = source->files[i - target->numFiles];
857 target->offsets[i] = source->offsets[i - target->numFiles];
859 target->numFiles = newNumFiles;