1 /*-------------------------------------------------------------------------
2 *
3 * buffile.c
4 * Management of large buffered files, primarily temporary files.
5 *
6 * Portions Copyright (c) 1996-2016, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
8 *
9 * IDENTIFICATION
10 * src/backend/storage/file/buffile.c
11 *
12 * NOTES:
13 *
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.
21 *
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.
30 *
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 *-------------------------------------------------------------------------
35 */
36
37 #include "postgres.h"
38
39 #include "executor/instrument.h"
40 #include "storage/fd.h"
41 #include "storage/buffile.h"
42 #include "storage/buf_internals.h"
43 #include "utils/resowner.h"
44
45 /*
46 * We break BufFiles into gigabyte-sized segments, regardless of RELSEG_SIZE.
47 * The reason is that we'd like large temporary BufFiles to be spread across
48 * multiple tablespaces when available.
49 */
50 #define MAX_PHYSICAL_FILESIZE 0x40000000
51 #define BUFFILE_SEG_SIZE (MAX_PHYSICAL_FILESIZE / BLCKSZ)
52
53 /*
54 * This data structure represents a buffered file that consists of one or
55 * more physical files (each accessed through a virtual file descriptor
56 * managed by fd.c).
57 */
58 struct BufFile
59 {
60 int numFiles; /* number of physical files in set */
61 /* all files except the last have length exactly MAX_PHYSICAL_FILESIZE */
62 File *files; /* palloc'd array with numFiles entries */
63 off_t *offsets; /* palloc'd array with numFiles entries */
64
65 /*
66 * offsets[i] is the current seek position of files[i]. We use this to
67 * avoid making redundant FileSeek calls.
68 */
69
70 bool isTemp; /* can only add files if this is TRUE */
71 bool isInterXact; /* keep open over transactions? */
72 bool dirty; /* does buffer need to be written? */
73
74 /*
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.)
78 */
79 ResourceOwner resowner;
80
81 /*
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).
84 */
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 */
89 PGAlignedBlock buffer;
90 };
91
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 void BufFileFlush(BufFile *file);
97
98 /*
99 * Create a BufFile given the first underlying physical file.
100 * NOTE: caller must set isTemp and isInterXact if appropriate.
101 */
102 static BufFile *
makeBufFile(File firstfile)103 makeBufFile(File firstfile)
104 {
105 BufFile *file = (BufFile *) palloc(sizeof(BufFile));
106
107 file->numFiles = 1;
108 file->files = (File *) palloc(sizeof(File));
109 file->files[0] = firstfile;
110 file->offsets = (off_t *) palloc(sizeof(off_t));
111 file->offsets[0] = 0L;
112 file->isTemp = false;
113 file->isInterXact = false;
114 file->dirty = false;
115 file->resowner = CurrentResourceOwner;
116 file->curFile = 0;
117 file->curOffset = 0L;
118 file->pos = 0;
119 file->nbytes = 0;
120
121 return file;
122 }
123
124 /*
125 * Add another component temp file.
126 */
127 static void
extendBufFile(BufFile * file)128 extendBufFile(BufFile *file)
129 {
130 File pfile;
131 ResourceOwner oldowner;
132
133 /* Be sure to associate the file with the BufFile's resource owner */
134 oldowner = CurrentResourceOwner;
135 CurrentResourceOwner = file->resowner;
136
137 Assert(file->isTemp);
138 pfile = OpenTemporaryFile(file->isInterXact);
139 Assert(pfile >= 0);
140
141 CurrentResourceOwner = oldowner;
142
143 file->files = (File *) repalloc(file->files,
144 (file->numFiles + 1) * sizeof(File));
145 file->offsets = (off_t *) repalloc(file->offsets,
146 (file->numFiles + 1) * sizeof(off_t));
147 file->files[file->numFiles] = pfile;
148 file->offsets[file->numFiles] = 0L;
149 file->numFiles++;
150 }
151
152 /*
153 * Create a BufFile for a new temporary file (which will expand to become
154 * multiple temporary files if more than MAX_PHYSICAL_FILESIZE bytes are
155 * written to it).
156 *
157 * If interXact is true, the temp file will not be automatically deleted
158 * at end of transaction.
159 *
160 * Note: if interXact is true, the caller had better be calling us in a
161 * memory context, and with a resource owner, that will survive across
162 * transaction boundaries.
163 */
164 BufFile *
BufFileCreateTemp(bool interXact)165 BufFileCreateTemp(bool interXact)
166 {
167 BufFile *file;
168 File pfile;
169
170 pfile = OpenTemporaryFile(interXact);
171 Assert(pfile >= 0);
172
173 file = makeBufFile(pfile);
174 file->isTemp = true;
175 file->isInterXact = interXact;
176
177 return file;
178 }
179
180 #ifdef NOT_USED
181 /*
182 * Create a BufFile and attach it to an already-opened virtual File.
183 *
184 * This is comparable to fdopen() in stdio. This is the only way at present
185 * to attach a BufFile to a non-temporary file. Note that BufFiles created
186 * in this way CANNOT be expanded into multiple files.
187 */
188 BufFile *
BufFileCreate(File file)189 BufFileCreate(File file)
190 {
191 return makeBufFile(file);
192 }
193 #endif
194
195 /*
196 * Close a BufFile
197 *
198 * Like fclose(), this also implicitly FileCloses the underlying File.
199 */
200 void
BufFileClose(BufFile * file)201 BufFileClose(BufFile *file)
202 {
203 int i;
204
205 /* flush any unwritten data */
206 BufFileFlush(file);
207 /* close the underlying file(s) (with delete if it's a temp file) */
208 for (i = 0; i < file->numFiles; i++)
209 FileClose(file->files[i]);
210 /* release the buffer space */
211 pfree(file->files);
212 pfree(file->offsets);
213 pfree(file);
214 }
215
216 /*
217 * BufFileLoadBuffer
218 *
219 * Load some data into buffer, if possible, starting from curOffset.
220 * At call, must have dirty = false, pos and nbytes = 0.
221 * On exit, nbytes is number of bytes loaded.
222 */
223 static void
BufFileLoadBuffer(BufFile * file)224 BufFileLoadBuffer(BufFile *file)
225 {
226 File thisfile;
227
228 /*
229 * Advance to next component file if necessary and possible.
230 *
231 * This path can only be taken if there is more than one component, so it
232 * won't interfere with reading a non-temp file that is over
233 * MAX_PHYSICAL_FILESIZE.
234 */
235 if (file->curOffset >= MAX_PHYSICAL_FILESIZE &&
236 file->curFile + 1 < file->numFiles)
237 {
238 file->curFile++;
239 file->curOffset = 0L;
240 }
241
242 /*
243 * May need to reposition physical file.
244 */
245 thisfile = file->files[file->curFile];
246 if (file->curOffset != file->offsets[file->curFile])
247 {
248 if (FileSeek(thisfile, file->curOffset, SEEK_SET) != file->curOffset)
249 ereport(ERROR,
250 (errcode_for_file_access(),
251 errmsg("could not seek in file \"%s\": %m",
252 FilePathName(thisfile))));
253 file->offsets[file->curFile] = file->curOffset;
254 }
255
256 /*
257 * Read whatever we can get, up to a full bufferload.
258 */
259 file->nbytes = FileRead(thisfile, file->buffer.data, sizeof(file->buffer));
260 if (file->nbytes < 0)
261 {
262 file->nbytes = 0;
263 ereport(ERROR,
264 (errcode_for_file_access(),
265 errmsg("could not read file \"%s\": %m",
266 FilePathName(thisfile))));
267 }
268
269 file->offsets[file->curFile] += file->nbytes;
270 /* we choose not to advance curOffset here */
271
272 pgBufferUsage.temp_blks_read++;
273 }
274
275 /*
276 * BufFileDumpBuffer
277 *
278 * Dump buffer contents starting at curOffset.
279 * At call, should have dirty = true, nbytes > 0.
280 * On exit, dirty is cleared if successful write, and curOffset is advanced.
281 */
282 static void
BufFileDumpBuffer(BufFile * file)283 BufFileDumpBuffer(BufFile *file)
284 {
285 int wpos = 0;
286 int bytestowrite;
287 File thisfile;
288
289 /*
290 * Unlike BufFileLoadBuffer, we must dump the whole buffer even if it
291 * crosses a component-file boundary; so we need a loop.
292 */
293 while (wpos < file->nbytes)
294 {
295 /*
296 * Advance to next component file if necessary and possible.
297 */
298 if (file->curOffset >= MAX_PHYSICAL_FILESIZE && file->isTemp)
299 {
300 while (file->curFile + 1 >= file->numFiles)
301 extendBufFile(file);
302 file->curFile++;
303 file->curOffset = 0L;
304 }
305
306 /*
307 * Enforce per-file size limit only for temp files, else just try to
308 * write as much as asked...
309 */
310 bytestowrite = file->nbytes - wpos;
311 if (file->isTemp)
312 {
313 off_t availbytes = MAX_PHYSICAL_FILESIZE - file->curOffset;
314
315 if ((off_t) bytestowrite > availbytes)
316 bytestowrite = (int) availbytes;
317 }
318
319 /*
320 * May need to reposition physical file.
321 */
322 thisfile = file->files[file->curFile];
323 if (file->curOffset != file->offsets[file->curFile])
324 {
325 if (FileSeek(thisfile, file->curOffset, SEEK_SET) != file->curOffset)
326 ereport(ERROR,
327 (errcode_for_file_access(),
328 errmsg("could not seek in file \"%s\": %m",
329 FilePathName(thisfile))));
330 file->offsets[file->curFile] = file->curOffset;
331 }
332 bytestowrite = FileWrite(thisfile, file->buffer.data + wpos, bytestowrite);
333 if (bytestowrite <= 0)
334 ereport(ERROR,
335 (errcode_for_file_access(),
336 errmsg("could not write to file \"%s\": %m",
337 FilePathName(thisfile))));
338
339 file->offsets[file->curFile] += bytestowrite;
340 file->curOffset += bytestowrite;
341 wpos += bytestowrite;
342
343 pgBufferUsage.temp_blks_written++;
344 }
345 file->dirty = false;
346
347 /*
348 * At this point, curOffset has been advanced to the end of the buffer,
349 * ie, its original value + nbytes. We need to make it point to the
350 * logical file position, ie, original value + pos, in case that is less
351 * (as could happen due to a small backwards seek in a dirty buffer!)
352 */
353 file->curOffset -= (file->nbytes - file->pos);
354 if (file->curOffset < 0) /* handle possible segment crossing */
355 {
356 file->curFile--;
357 Assert(file->curFile >= 0);
358 file->curOffset += MAX_PHYSICAL_FILESIZE;
359 }
360
361 /*
362 * Now we can set the buffer empty without changing the logical position
363 */
364 file->pos = 0;
365 file->nbytes = 0;
366 }
367
368 /*
369 * BufFileRead
370 *
371 * Like fread() except we assume 1-byte element size and report I/O errors via
372 * ereport().
373 */
374 size_t
BufFileRead(BufFile * file,void * ptr,size_t size)375 BufFileRead(BufFile *file, void *ptr, size_t size)
376 {
377 size_t nread = 0;
378 size_t nthistime;
379
380 BufFileFlush(file);
381
382 while (size > 0)
383 {
384 if (file->pos >= file->nbytes)
385 {
386 /* Try to load more data into buffer. */
387 file->curOffset += file->pos;
388 file->pos = 0;
389 file->nbytes = 0;
390 BufFileLoadBuffer(file);
391 if (file->nbytes <= 0)
392 break; /* no more data available */
393 }
394
395 nthistime = file->nbytes - file->pos;
396 if (nthistime > size)
397 nthistime = size;
398 Assert(nthistime > 0);
399
400 memcpy(ptr, file->buffer.data + file->pos, nthistime);
401
402 file->pos += nthistime;
403 ptr = (void *) ((char *) ptr + nthistime);
404 size -= nthistime;
405 nread += nthistime;
406 }
407
408 return nread;
409 }
410
411 /*
412 * BufFileWrite
413 *
414 * Like fwrite() except we assume 1-byte element size and report errors via
415 * ereport().
416 */
417 size_t
BufFileWrite(BufFile * file,void * ptr,size_t size)418 BufFileWrite(BufFile *file, void *ptr, size_t size)
419 {
420 size_t nwritten = 0;
421 size_t nthistime;
422
423 while (size > 0)
424 {
425 if (file->pos >= BLCKSZ)
426 {
427 /* Buffer full, dump it out */
428 if (file->dirty)
429 BufFileDumpBuffer(file);
430 else
431 {
432 /* Hmm, went directly from reading to writing? */
433 file->curOffset += file->pos;
434 file->pos = 0;
435 file->nbytes = 0;
436 }
437 }
438
439 nthistime = BLCKSZ - file->pos;
440 if (nthistime > size)
441 nthistime = size;
442 Assert(nthistime > 0);
443
444 memcpy(file->buffer.data + file->pos, ptr, nthistime);
445
446 file->dirty = true;
447 file->pos += nthistime;
448 if (file->nbytes < file->pos)
449 file->nbytes = file->pos;
450 ptr = (void *) ((char *) ptr + nthistime);
451 size -= nthistime;
452 nwritten += nthistime;
453 }
454
455 return nwritten;
456 }
457
458 /*
459 * BufFileFlush
460 *
461 * Like fflush(), except that I/O errors are reported with ereport().
462 */
463 static void
BufFileFlush(BufFile * file)464 BufFileFlush(BufFile *file)
465 {
466 if (file->dirty)
467 BufFileDumpBuffer(file);
468
469 Assert(!file->dirty);
470 }
471
472 /*
473 * BufFileSeek
474 *
475 * Like fseek(), except that target position needs two values in order to
476 * work when logical filesize exceeds maximum value representable by long.
477 * We do not support relative seeks across more than LONG_MAX, however.
478 * I/O errors are reported by ereport().
479 *
480 * Result is 0 if OK, EOF if not. Logical position is not moved if an
481 * impossible seek is attempted.
482 */
483 int
BufFileSeek(BufFile * file,int fileno,off_t offset,int whence)484 BufFileSeek(BufFile *file, int fileno, off_t offset, int whence)
485 {
486 int newFile;
487 off_t newOffset;
488
489 switch (whence)
490 {
491 case SEEK_SET:
492 if (fileno < 0)
493 return EOF;
494 newFile = fileno;
495 newOffset = offset;
496 break;
497 case SEEK_CUR:
498
499 /*
500 * Relative seek considers only the signed offset, ignoring
501 * fileno. Note that large offsets (> 1 gig) risk overflow in this
502 * add, unless we have 64-bit off_t.
503 */
504 newFile = file->curFile;
505 newOffset = (file->curOffset + file->pos) + offset;
506 break;
507 #ifdef NOT_USED
508 case SEEK_END:
509 /* could be implemented, not needed currently */
510 break;
511 #endif
512 default:
513 elog(ERROR, "invalid whence: %d", whence);
514 return EOF;
515 }
516 while (newOffset < 0)
517 {
518 if (--newFile < 0)
519 return EOF;
520 newOffset += MAX_PHYSICAL_FILESIZE;
521 }
522 if (newFile == file->curFile &&
523 newOffset >= file->curOffset &&
524 newOffset <= file->curOffset + file->nbytes)
525 {
526 /*
527 * Seek is to a point within existing buffer; we can just adjust
528 * pos-within-buffer, without flushing buffer. Note this is OK
529 * whether reading or writing, but buffer remains dirty if we were
530 * writing.
531 */
532 file->pos = (int) (newOffset - file->curOffset);
533 return 0;
534 }
535 /* Otherwise, must reposition buffer, so flush any dirty data */
536 BufFileFlush(file);
537
538 /*
539 * At this point and no sooner, check for seek past last segment. The
540 * above flush could have created a new segment, so checking sooner would
541 * not work (at least not with this code).
542 */
543 if (file->isTemp)
544 {
545 /* convert seek to "start of next seg" to "end of last seg" */
546 if (newFile == file->numFiles && newOffset == 0)
547 {
548 newFile--;
549 newOffset = MAX_PHYSICAL_FILESIZE;
550 }
551 while (newOffset > MAX_PHYSICAL_FILESIZE)
552 {
553 if (++newFile >= file->numFiles)
554 return EOF;
555 newOffset -= MAX_PHYSICAL_FILESIZE;
556 }
557 }
558 if (newFile >= file->numFiles)
559 return EOF;
560 /* Seek is OK! */
561 file->curFile = newFile;
562 file->curOffset = newOffset;
563 file->pos = 0;
564 file->nbytes = 0;
565 return 0;
566 }
567
568 void
BufFileTell(BufFile * file,int * fileno,off_t * offset)569 BufFileTell(BufFile *file, int *fileno, off_t *offset)
570 {
571 *fileno = file->curFile;
572 *offset = file->curOffset + file->pos;
573 }
574
575 /*
576 * BufFileSeekBlock --- block-oriented seek
577 *
578 * Performs absolute seek to the start of the n'th BLCKSZ-sized block of
579 * the file. Note that users of this interface will fail if their files
580 * exceed BLCKSZ * LONG_MAX bytes, but that is quite a lot; we don't work
581 * with tables bigger than that, either...
582 *
583 * Result is 0 if OK, EOF if not. Logical position is not moved if an
584 * impossible seek is attempted.
585 */
586 int
BufFileSeekBlock(BufFile * file,long blknum)587 BufFileSeekBlock(BufFile *file, long blknum)
588 {
589 return BufFileSeek(file,
590 (int) (blknum / BUFFILE_SEG_SIZE),
591 (off_t) (blknum % BUFFILE_SEG_SIZE) * BLCKSZ,
592 SEEK_SET);
593 }
594
595 #ifdef NOT_USED
596 /*
597 * BufFileTellBlock --- block-oriented tell
598 *
599 * Any fractional part of a block in the current seek position is ignored.
600 */
601 long
BufFileTellBlock(BufFile * file)602 BufFileTellBlock(BufFile *file)
603 {
604 long blknum;
605
606 blknum = (file->curOffset + file->pos) / BLCKSZ;
607 blknum += file->curFile * BUFFILE_SEG_SIZE;
608 return blknum;
609 }
610
611 #endif
612