1 /*-------------------------------------------------------------------------
4 * Management of large buffered files, primarily temporary files.
6 * Portions Copyright (c) 1996-2017, 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 transaction end. If the underlying
24 * virtual File is made with OpenTemporaryFile, then 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.
34 *-------------------------------------------------------------------------
39 #include "executor/instrument.h"
41 #include "storage/fd.h"
42 #include "storage/buffile.h"
43 #include "storage/buf_internals.h"
44 #include "utils/resowner.h"
47 * We break BufFiles into gigabyte-sized segments, regardless of RELSEG_SIZE.
48 * The reason is that we'd like large temporary BufFiles to be spread across
49 * multiple tablespaces when available.
51 #define MAX_PHYSICAL_FILESIZE 0x40000000
52 #define BUFFILE_SEG_SIZE (MAX_PHYSICAL_FILESIZE / BLCKSZ)
55 * This data structure represents a buffered file that consists of one or
56 * more physical files (each accessed through a virtual file descriptor
61 int numFiles; /* number of physical files in set */
62 /* all files except the last have length exactly MAX_PHYSICAL_FILESIZE */
63 File *files; /* palloc'd array with numFiles entries */
64 off_t *offsets; /* palloc'd array with numFiles entries */
67 * offsets[i] is the current seek position of files[i]. We use this to
68 * avoid making redundant FileSeek calls.
71 bool isInterXact; /* keep open over transactions? */
72 bool dirty; /* does buffer need to be written? */
75 * resowner is the ResourceOwner to use for underlying temp files. (We
76 * don't need to remember the memory context we're using explicitly,
77 * because after creation we only repalloc our arrays larger.)
79 ResourceOwner resowner;
82 * "current pos" is position of start of buffer within the logical file.
83 * Position as seen by user of BufFile is (curFile, curOffset + pos).
85 int curFile; /* file index (0..n) part of current pos */
86 off_t curOffset; /* offset part of current pos */
87 int pos; /* next read/write position in buffer */
88 int nbytes; /* total # of valid bytes in buffer */
92 static BufFile *makeBufFile(File firstfile);
93 static void extendBufFile(BufFile *file);
94 static void BufFileLoadBuffer(BufFile *file);
95 static void BufFileDumpBuffer(BufFile *file);
96 static int BufFileFlush(BufFile *file);
100 * Create a BufFile given the first underlying physical file.
101 * NOTE: caller must set isInterXact if appropriate.
104 makeBufFile(File firstfile)
106 BufFile *file = (BufFile *) palloc(sizeof(BufFile));
109 file->files = (File *) palloc(sizeof(File));
110 file->files[0] = firstfile;
111 file->offsets = (off_t *) palloc(sizeof(off_t));
112 file->offsets[0] = 0L;
113 file->isInterXact = false;
115 file->resowner = CurrentResourceOwner;
117 file->curOffset = 0L;
125 * Add another component temp file.
128 extendBufFile(BufFile *file)
131 ResourceOwner oldowner;
133 /* Be sure to associate the file with the BufFile's resource owner */
134 oldowner = CurrentResourceOwner;
135 CurrentResourceOwner = file->resowner;
137 pfile = OpenTemporaryFile(file->isInterXact);
140 CurrentResourceOwner = oldowner;
142 file->files = (File *) repalloc(file->files,
143 (file->numFiles + 1) * sizeof(File));
144 file->offsets = (off_t *) repalloc(file->offsets,
145 (file->numFiles + 1) * sizeof(off_t));
146 file->files[file->numFiles] = pfile;
147 file->offsets[file->numFiles] = 0L;
152 * Create a BufFile for a new temporary file (which will expand to become
153 * multiple temporary files if more than MAX_PHYSICAL_FILESIZE bytes are
156 * If interXact is true, the temp file will not be automatically deleted
157 * at end of transaction.
159 * Note: if interXact is true, the caller had better be calling us in a
160 * memory context, and with a resource owner, that will survive across
161 * transaction boundaries.
164 BufFileCreateTemp(bool interXact)
169 pfile = OpenTemporaryFile(interXact);
172 file = makeBufFile(pfile);
173 file->isInterXact = interXact;
180 * Create a BufFile and attach it to an already-opened virtual File.
182 * This is comparable to fdopen() in stdio. This is the only way at present
183 * to attach a BufFile to a non-temporary file. Note that BufFiles created
184 * in this way CANNOT be expanded into multiple files.
187 BufFileCreate(File file)
189 return makeBufFile(file);
196 * Like fclose(), this also implicitly FileCloses the underlying File.
199 BufFileClose(BufFile *file)
203 /* flush any unwritten data */
205 /* close the underlying file(s) (with delete if it's a temp file) */
206 for (i = 0; i < file->numFiles; i++)
207 FileClose(file->files[i]);
208 /* release the buffer space */
210 pfree(file->offsets);
217 * Load some data into buffer, if possible, starting from curOffset.
218 * At call, must have dirty = false, pos and nbytes = 0.
219 * On exit, nbytes is number of bytes loaded.
222 BufFileLoadBuffer(BufFile *file)
227 * Advance to next component file if necessary and possible.
229 * This path can only be taken if there is more than one component, so it
230 * won't interfere with reading a non-temp file that is over
231 * MAX_PHYSICAL_FILESIZE.
233 if (file->curOffset >= MAX_PHYSICAL_FILESIZE &&
234 file->curFile + 1 < file->numFiles)
237 file->curOffset = 0L;
241 * May need to reposition physical file.
243 thisfile = file->files[file->curFile];
244 if (file->curOffset != file->offsets[file->curFile])
246 if (FileSeek(thisfile, file->curOffset, SEEK_SET) != file->curOffset)
247 return; /* seek failed, read nothing */
248 file->offsets[file->curFile] = file->curOffset;
252 * Read whatever we can get, up to a full bufferload.
254 file->nbytes = FileRead(thisfile,
256 sizeof(file->buffer),
257 WAIT_EVENT_BUFFILE_READ);
258 if (file->nbytes < 0)
260 file->offsets[file->curFile] += file->nbytes;
261 /* we choose not to advance curOffset here */
263 if (file->nbytes > 0)
264 pgBufferUsage.temp_blks_read++;
270 * Dump buffer contents starting at curOffset.
271 * At call, should have dirty = true, nbytes > 0.
272 * On exit, dirty is cleared if successful write, and curOffset is advanced.
275 BufFileDumpBuffer(BufFile *file)
282 * Unlike BufFileLoadBuffer, we must dump the whole buffer even if it
283 * crosses a component-file boundary; so we need a loop.
285 while (wpos < file->nbytes)
290 * Advance to next component file if necessary and possible.
292 if (file->curOffset >= MAX_PHYSICAL_FILESIZE)
294 while (file->curFile + 1 >= file->numFiles)
297 file->curOffset = 0L;
301 * Enforce per-file size limit only for temp files, else just try to
302 * write as much as asked...
304 bytestowrite = file->nbytes - wpos;
305 availbytes = MAX_PHYSICAL_FILESIZE - file->curOffset;
307 if ((off_t) bytestowrite > availbytes)
308 bytestowrite = (int) availbytes;
311 * May need to reposition physical file.
313 thisfile = file->files[file->curFile];
314 if (file->curOffset != file->offsets[file->curFile])
316 if (FileSeek(thisfile, file->curOffset, SEEK_SET) != file->curOffset)
317 return; /* seek failed, give up */
318 file->offsets[file->curFile] = file->curOffset;
320 bytestowrite = FileWrite(thisfile,
323 WAIT_EVENT_BUFFILE_WRITE);
324 if (bytestowrite <= 0)
325 return; /* failed to write */
326 file->offsets[file->curFile] += bytestowrite;
327 file->curOffset += bytestowrite;
328 wpos += bytestowrite;
330 pgBufferUsage.temp_blks_written++;
335 * At this point, curOffset has been advanced to the end of the buffer,
336 * ie, its original value + nbytes. We need to make it point to the
337 * logical file position, ie, original value + pos, in case that is less
338 * (as could happen due to a small backwards seek in a dirty buffer!)
340 file->curOffset -= (file->nbytes - file->pos);
341 if (file->curOffset < 0) /* handle possible segment crossing */
344 Assert(file->curFile >= 0);
345 file->curOffset += MAX_PHYSICAL_FILESIZE;
349 * Now we can set the buffer empty without changing the logical position
358 * Like fread() except we assume 1-byte element size.
361 BufFileRead(BufFile *file, void *ptr, size_t size)
368 if (BufFileFlush(file) != 0)
369 return 0; /* could not flush... */
370 Assert(!file->dirty);
375 if (file->pos >= file->nbytes)
377 /* Try to load more data into buffer. */
378 file->curOffset += file->pos;
381 BufFileLoadBuffer(file);
382 if (file->nbytes <= 0)
383 break; /* no more data available */
386 nthistime = file->nbytes - file->pos;
387 if (nthistime > size)
389 Assert(nthistime > 0);
391 memcpy(ptr, file->buffer + file->pos, nthistime);
393 file->pos += nthistime;
394 ptr = (void *) ((char *) ptr + nthistime);
405 * Like fwrite() except we assume 1-byte element size.
408 BufFileWrite(BufFile *file, void *ptr, size_t size)
415 if (file->pos >= BLCKSZ)
417 /* Buffer full, dump it out */
420 BufFileDumpBuffer(file);
422 break; /* I/O error */
426 /* Hmm, went directly from reading to writing? */
427 file->curOffset += file->pos;
433 nthistime = BLCKSZ - file->pos;
434 if (nthistime > size)
436 Assert(nthistime > 0);
438 memcpy(file->buffer + file->pos, ptr, nthistime);
441 file->pos += nthistime;
442 if (file->nbytes < file->pos)
443 file->nbytes = file->pos;
444 ptr = (void *) ((char *) ptr + nthistime);
446 nwritten += nthistime;
458 BufFileFlush(BufFile *file)
462 BufFileDumpBuffer(file);
473 * Like fseek(), except that target position needs two values in order to
474 * work when logical filesize exceeds maximum value representable by long.
475 * We do not support relative seeks across more than LONG_MAX, however.
477 * Result is 0 if OK, EOF if not. Logical position is not moved if an
478 * impossible seek is attempted.
481 BufFileSeek(BufFile *file, int fileno, off_t offset, int whence)
497 * Relative seek considers only the signed offset, ignoring
498 * fileno. Note that large offsets (> 1 gig) risk overflow in this
499 * add, unless we have 64-bit off_t.
501 newFile = file->curFile;
502 newOffset = (file->curOffset + file->pos) + offset;
506 /* could be implemented, not needed currently */
510 elog(ERROR, "invalid whence: %d", whence);
513 while (newOffset < 0)
517 newOffset += MAX_PHYSICAL_FILESIZE;
519 if (newFile == file->curFile &&
520 newOffset >= file->curOffset &&
521 newOffset <= file->curOffset + file->nbytes)
524 * Seek is to a point within existing buffer; we can just adjust
525 * pos-within-buffer, without flushing buffer. Note this is OK
526 * whether reading or writing, but buffer remains dirty if we were
529 file->pos = (int) (newOffset - file->curOffset);
532 /* Otherwise, must reposition buffer, so flush any dirty data */
533 if (BufFileFlush(file) != 0)
537 * At this point and no sooner, check for seek past last segment. The
538 * above flush could have created a new segment, so checking sooner would
539 * not work (at least not with this code).
542 /* convert seek to "start of next seg" to "end of last seg" */
543 if (newFile == file->numFiles && newOffset == 0)
546 newOffset = MAX_PHYSICAL_FILESIZE;
548 while (newOffset > MAX_PHYSICAL_FILESIZE)
550 if (++newFile >= file->numFiles)
552 newOffset -= MAX_PHYSICAL_FILESIZE;
554 if (newFile >= file->numFiles)
557 file->curFile = newFile;
558 file->curOffset = newOffset;
565 BufFileTell(BufFile *file, int *fileno, off_t *offset)
567 *fileno = file->curFile;
568 *offset = file->curOffset + file->pos;
572 * BufFileSeekBlock --- block-oriented seek
574 * Performs absolute seek to the start of the n'th BLCKSZ-sized block of
575 * the file. Note that users of this interface will fail if their files
576 * exceed BLCKSZ * LONG_MAX bytes, but that is quite a lot; we don't work
577 * with tables bigger than that, either...
579 * Result is 0 if OK, EOF if not. Logical position is not moved if an
580 * impossible seek is attempted.
583 BufFileSeekBlock(BufFile *file, long blknum)
585 return BufFileSeek(file,
586 (int) (blknum / BUFFILE_SEG_SIZE),
587 (off_t) (blknum % BUFFILE_SEG_SIZE) * BLCKSZ,
593 * BufFileTellBlock --- block-oriented tell
595 * Any fractional part of a block in the current seek position is ignored.
598 BufFileTellBlock(BufFile *file)
602 blknum = (file->curOffset + file->pos) / BLCKSZ;
603 blknum += file->curFile * BUFFILE_SEG_SIZE;