1 /*-------------------------------------------------------------------------
4 * Management of large buffered files, primarily temporary files.
6 * Portions Copyright (c) 1996-2009, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
10 * $PostgreSQL: pgsql/src/backend/storage/file/buffile.c,v 1.33 2009/01/01 17:23:47 momjian Exp $
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). To avoid confusion, the caller should take care that
27 * all calls for a single BufFile are made in the same palloc context.
29 * BufFile also supports temporary files that exceed the OS file size limit
30 * (by opening multiple fd.c temporary files). This is an essential feature
31 * for sorts and hashjoins on large amounts of data.
32 *-------------------------------------------------------------------------
37 #include "storage/fd.h"
38 #include "storage/buffile.h"
39 #include "storage/buf_internals.h"
42 * We break BufFiles into gigabyte-sized segments, regardless of RELSEG_SIZE.
43 * The reason is that we'd like large temporary BufFiles to be spread across
44 * multiple tablespaces when available.
46 #define MAX_PHYSICAL_FILESIZE 0x40000000
47 #define BUFFILE_SEG_SIZE (MAX_PHYSICAL_FILESIZE / BLCKSZ)
50 * This data structure represents a buffered file that consists of one or
51 * more physical files (each accessed through a virtual file descriptor
56 int numFiles; /* number of physical files in set */
57 /* all files except the last have length exactly MAX_PHYSICAL_FILESIZE */
58 File *files; /* palloc'd array with numFiles entries */
59 off_t *offsets; /* palloc'd array with numFiles entries */
62 * offsets[i] is the current seek position of files[i]. We use this to
63 * avoid making redundant FileSeek calls.
66 bool isTemp; /* can only add files if this is TRUE */
67 bool isInterXact; /* keep open over transactions? */
68 bool dirty; /* does buffer need to be written? */
71 * "current pos" is position of start of buffer within the logical file.
72 * Position as seen by user of BufFile is (curFile, curOffset + pos).
74 int curFile; /* file index (0..n) part of current pos */
75 off_t curOffset; /* offset part of current pos */
76 int pos; /* next read/write position in buffer */
77 int nbytes; /* total # of valid bytes in buffer */
81 static BufFile *makeBufFile(File firstfile);
82 static void extendBufFile(BufFile *file);
83 static void BufFileLoadBuffer(BufFile *file);
84 static void BufFileDumpBuffer(BufFile *file);
85 static int BufFileFlush(BufFile *file);
89 * Create a BufFile given the first underlying physical file.
90 * NOTE: caller must set isTemp and isInterXact if appropriate.
93 makeBufFile(File firstfile)
95 BufFile *file = (BufFile *) palloc(sizeof(BufFile));
98 file->files = (File *) palloc(sizeof(File));
99 file->files[0] = firstfile;
100 file->offsets = (off_t *) palloc(sizeof(off_t));
101 file->offsets[0] = 0L;
102 file->isTemp = false;
103 file->isInterXact = false;
106 file->curOffset = 0L;
114 * Add another component temp file.
117 extendBufFile(BufFile *file)
121 Assert(file->isTemp);
122 pfile = OpenTemporaryFile(file->isInterXact);
125 file->files = (File *) repalloc(file->files,
126 (file->numFiles + 1) * sizeof(File));
127 file->offsets = (off_t *) repalloc(file->offsets,
128 (file->numFiles + 1) * sizeof(off_t));
129 file->files[file->numFiles] = pfile;
130 file->offsets[file->numFiles] = 0L;
135 * Create a BufFile for a new temporary file (which will expand to become
136 * multiple temporary files if more than MAX_PHYSICAL_FILESIZE bytes are
139 * If interXact is true, the temp file will not be automatically deleted
140 * at end of transaction.
142 * Note: if interXact is true, the caller had better be calling us in a
143 * memory context that will survive across transaction boundaries.
146 BufFileCreateTemp(bool interXact)
151 pfile = OpenTemporaryFile(interXact);
154 file = makeBufFile(pfile);
156 file->isInterXact = interXact;
163 * Create a BufFile and attach it to an already-opened virtual File.
165 * This is comparable to fdopen() in stdio. This is the only way at present
166 * to attach a BufFile to a non-temporary file. Note that BufFiles created
167 * in this way CANNOT be expanded into multiple files.
170 BufFileCreate(File file)
172 return makeBufFile(file);
179 * Like fclose(), this also implicitly FileCloses the underlying File.
182 BufFileClose(BufFile *file)
186 /* flush any unwritten data */
188 /* close the underlying file(s) (with delete if it's a temp file) */
189 for (i = 0; i < file->numFiles; i++)
190 FileClose(file->files[i]);
191 /* release the buffer space */
193 pfree(file->offsets);
200 * Load some data into buffer, if possible, starting from curOffset.
201 * At call, must have dirty = false, pos and nbytes = 0.
202 * On exit, nbytes is number of bytes loaded.
205 BufFileLoadBuffer(BufFile *file)
210 * Advance to next component file if necessary and possible.
212 * This path can only be taken if there is more than one component, so it
213 * won't interfere with reading a non-temp file that is over
214 * MAX_PHYSICAL_FILESIZE.
216 if (file->curOffset >= MAX_PHYSICAL_FILESIZE &&
217 file->curFile + 1 < file->numFiles)
220 file->curOffset = 0L;
224 * May need to reposition physical file.
226 thisfile = file->files[file->curFile];
227 if (file->curOffset != file->offsets[file->curFile])
229 if (FileSeek(thisfile, file->curOffset, SEEK_SET) != file->curOffset)
230 return; /* seek failed, read nothing */
231 file->offsets[file->curFile] = file->curOffset;
235 * Read whatever we can get, up to a full bufferload.
237 file->nbytes = FileRead(thisfile, file->buffer, sizeof(file->buffer));
238 if (file->nbytes < 0)
240 file->offsets[file->curFile] += file->nbytes;
241 /* we choose not to advance curOffset here */
249 * Dump buffer contents starting at curOffset.
250 * At call, should have dirty = true, nbytes > 0.
251 * On exit, dirty is cleared if successful write, and curOffset is advanced.
254 BufFileDumpBuffer(BufFile *file)
261 * Unlike BufFileLoadBuffer, we must dump the whole buffer even if it
262 * crosses a component-file boundary; so we need a loop.
264 while (wpos < file->nbytes)
267 * Advance to next component file if necessary and possible.
269 if (file->curOffset >= MAX_PHYSICAL_FILESIZE && file->isTemp)
271 while (file->curFile + 1 >= file->numFiles)
274 file->curOffset = 0L;
278 * Enforce per-file size limit only for temp files, else just try to
279 * write as much as asked...
281 bytestowrite = file->nbytes - wpos;
284 off_t availbytes = MAX_PHYSICAL_FILESIZE - file->curOffset;
286 if ((off_t) bytestowrite > availbytes)
287 bytestowrite = (int) availbytes;
291 * May need to reposition physical file.
293 thisfile = file->files[file->curFile];
294 if (file->curOffset != file->offsets[file->curFile])
296 if (FileSeek(thisfile, file->curOffset, SEEK_SET) != file->curOffset)
297 return; /* seek failed, give up */
298 file->offsets[file->curFile] = file->curOffset;
300 bytestowrite = FileWrite(thisfile, file->buffer + wpos, bytestowrite);
301 if (bytestowrite <= 0)
302 return; /* failed to write */
303 file->offsets[file->curFile] += bytestowrite;
304 file->curOffset += bytestowrite;
305 wpos += bytestowrite;
312 * At this point, curOffset has been advanced to the end of the buffer,
313 * ie, its original value + nbytes. We need to make it point to the
314 * logical file position, ie, original value + pos, in case that is less
315 * (as could happen due to a small backwards seek in a dirty buffer!)
317 file->curOffset -= (file->nbytes - file->pos);
318 if (file->curOffset < 0) /* handle possible segment crossing */
321 Assert(file->curFile >= 0);
322 file->curOffset += MAX_PHYSICAL_FILESIZE;
326 * Now we can set the buffer empty without changing the logical position
335 * Like fread() except we assume 1-byte element size.
338 BufFileRead(BufFile *file, void *ptr, size_t size)
345 if (BufFileFlush(file) != 0)
346 return 0; /* could not flush... */
347 Assert(!file->dirty);
352 if (file->pos >= file->nbytes)
354 /* Try to load more data into buffer. */
355 file->curOffset += file->pos;
358 BufFileLoadBuffer(file);
359 if (file->nbytes <= 0)
360 break; /* no more data available */
363 nthistime = file->nbytes - file->pos;
364 if (nthistime > size)
366 Assert(nthistime > 0);
368 memcpy(ptr, file->buffer + file->pos, nthistime);
370 file->pos += nthistime;
371 ptr = (void *) ((char *) ptr + nthistime);
382 * Like fwrite() except we assume 1-byte element size.
385 BufFileWrite(BufFile *file, void *ptr, size_t size)
392 if (file->pos >= BLCKSZ)
394 /* Buffer full, dump it out */
397 BufFileDumpBuffer(file);
399 break; /* I/O error */
403 /* Hmm, went directly from reading to writing? */
404 file->curOffset += file->pos;
410 nthistime = BLCKSZ - file->pos;
411 if (nthistime > size)
413 Assert(nthistime > 0);
415 memcpy(file->buffer + file->pos, ptr, nthistime);
418 file->pos += nthistime;
419 if (file->nbytes < file->pos)
420 file->nbytes = file->pos;
421 ptr = (void *) ((char *) ptr + nthistime);
423 nwritten += nthistime;
435 BufFileFlush(BufFile *file)
439 BufFileDumpBuffer(file);
450 * Like fseek(), except that target position needs two values in order to
451 * work when logical filesize exceeds maximum value representable by long.
452 * We do not support relative seeks across more than LONG_MAX, however.
454 * Result is 0 if OK, EOF if not. Logical position is not moved if an
455 * impossible seek is attempted.
458 BufFileSeek(BufFile *file, int fileno, off_t offset, int whence)
474 * Relative seek considers only the signed offset, ignoring
475 * fileno. Note that large offsets (> 1 gig) risk overflow in this
476 * add, unless we have 64-bit off_t.
478 newFile = file->curFile;
479 newOffset = (file->curOffset + file->pos) + offset;
483 /* could be implemented, not needed currently */
487 elog(ERROR, "invalid whence: %d", whence);
490 while (newOffset < 0)
494 newOffset += MAX_PHYSICAL_FILESIZE;
496 if (newFile == file->curFile &&
497 newOffset >= file->curOffset &&
498 newOffset <= file->curOffset + file->nbytes)
501 * Seek is to a point within existing buffer; we can just adjust
502 * pos-within-buffer, without flushing buffer. Note this is OK
503 * whether reading or writing, but buffer remains dirty if we were
506 file->pos = (int) (newOffset - file->curOffset);
509 /* Otherwise, must reposition buffer, so flush any dirty data */
510 if (BufFileFlush(file) != 0)
514 * At this point and no sooner, check for seek past last segment. The
515 * above flush could have created a new segment, so checking sooner would
516 * not work (at least not with this code).
520 /* convert seek to "start of next seg" to "end of last seg" */
521 if (newFile == file->numFiles && newOffset == 0)
524 newOffset = MAX_PHYSICAL_FILESIZE;
526 while (newOffset > MAX_PHYSICAL_FILESIZE)
528 if (++newFile >= file->numFiles)
530 newOffset -= MAX_PHYSICAL_FILESIZE;
533 if (newFile >= file->numFiles)
536 file->curFile = newFile;
537 file->curOffset = newOffset;
544 BufFileTell(BufFile *file, int *fileno, off_t *offset)
546 *fileno = file->curFile;
547 *offset = file->curOffset + file->pos;
551 * BufFileSeekBlock --- block-oriented seek
553 * Performs absolute seek to the start of the n'th BLCKSZ-sized block of
554 * the file. Note that users of this interface will fail if their files
555 * exceed BLCKSZ * LONG_MAX bytes, but that is quite a lot; we don't work
556 * with tables bigger than that, either...
558 * Result is 0 if OK, EOF if not. Logical position is not moved if an
559 * impossible seek is attempted.
562 BufFileSeekBlock(BufFile *file, long blknum)
564 return BufFileSeek(file,
565 (int) (blknum / BUFFILE_SEG_SIZE),
566 (off_t) (blknum % BUFFILE_SEG_SIZE) * BLCKSZ,
572 * BufFileTellBlock --- block-oriented tell
574 * Any fractional part of a block in the current seek position is ignored.
577 BufFileTellBlock(BufFile *file)
581 blknum = (file->curOffset + file->pos) / BLCKSZ;
582 blknum += file->curFile * BUFFILE_SEG_SIZE;