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