]> granicus.if.org Git - postgresql/blob - src/backend/storage/file/buffile.c
b527d38b05b0c4ebe51d93ee712aba0313cc9d04
[postgresql] / src / backend / storage / file / buffile.c
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            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         char            buffer[BLCKSZ];
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 int      BufFileFlush(BufFile *file);
97
98
99 /*
100  * Create a BufFile given the first underlying physical file.
101  * NOTE: caller must set isInterXact if appropriate.
102  */
103 static BufFile *
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->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
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         pfile = OpenTemporaryFile(file->isInterXact);
138         Assert(pfile >= 0);
139
140         CurrentResourceOwner = oldowner;
141
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;
148         file->numFiles++;
149 }
150
151 /*
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
154  * written to it).
155  *
156  * If interXact is true, the temp file will not be automatically deleted
157  * at end of transaction.
158  *
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.
162  */
163 BufFile *
164 BufFileCreateTemp(bool interXact)
165 {
166         BufFile    *file;
167         File            pfile;
168
169         pfile = OpenTemporaryFile(interXact);
170         Assert(pfile >= 0);
171
172         file = makeBufFile(pfile);
173         file->isInterXact = interXact;
174
175         return file;
176 }
177
178 #ifdef NOT_USED
179 /*
180  * Create a BufFile and attach it to an already-opened virtual File.
181  *
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.
185  */
186 BufFile *
187 BufFileCreate(File file)
188 {
189         return makeBufFile(file);
190 }
191 #endif
192
193 /*
194  * Close a BufFile
195  *
196  * Like fclose(), this also implicitly FileCloses the underlying File.
197  */
198 void
199 BufFileClose(BufFile *file)
200 {
201         int                     i;
202
203         /* flush any unwritten data */
204         BufFileFlush(file);
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 */
209         pfree(file->files);
210         pfree(file->offsets);
211         pfree(file);
212 }
213
214 /*
215  * BufFileLoadBuffer
216  *
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.
220  */
221 static void
222 BufFileLoadBuffer(BufFile *file)
223 {
224         File            thisfile;
225
226         /*
227          * Advance to next component file if necessary and possible.
228          *
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.
232          */
233         if (file->curOffset >= MAX_PHYSICAL_FILESIZE &&
234                 file->curFile + 1 < file->numFiles)
235         {
236                 file->curFile++;
237                 file->curOffset = 0L;
238         }
239
240         /*
241          * May need to reposition physical file.
242          */
243         thisfile = file->files[file->curFile];
244         if (file->curOffset != file->offsets[file->curFile])
245         {
246                 if (FileSeek(thisfile, file->curOffset, SEEK_SET) != file->curOffset)
247                         return;                         /* seek failed, read nothing */
248                 file->offsets[file->curFile] = file->curOffset;
249         }
250
251         /*
252          * Read whatever we can get, up to a full bufferload.
253          */
254         file->nbytes = FileRead(thisfile,
255                                                         file->buffer,
256                                                         sizeof(file->buffer),
257                                                         WAIT_EVENT_BUFFILE_READ);
258         if (file->nbytes < 0)
259                 file->nbytes = 0;
260         file->offsets[file->curFile] += file->nbytes;
261         /* we choose not to advance curOffset here */
262
263         if (file->nbytes > 0)
264                 pgBufferUsage.temp_blks_read++;
265 }
266
267 /*
268  * BufFileDumpBuffer
269  *
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.
273  */
274 static void
275 BufFileDumpBuffer(BufFile *file)
276 {
277         int                     wpos = 0;
278         int                     bytestowrite;
279         File            thisfile;
280
281         /*
282          * Unlike BufFileLoadBuffer, we must dump the whole buffer even if it
283          * crosses a component-file boundary; so we need a loop.
284          */
285         while (wpos < file->nbytes)
286         {
287                 off_t           availbytes;
288
289                 /*
290                  * Advance to next component file if necessary and possible.
291                  */
292                 if (file->curOffset >= MAX_PHYSICAL_FILESIZE)
293                 {
294                         while (file->curFile + 1 >= file->numFiles)
295                                 extendBufFile(file);
296                         file->curFile++;
297                         file->curOffset = 0L;
298                 }
299
300                 /*
301                  * Enforce per-file size limit only for temp files, else just try to
302                  * write as much as asked...
303                  */
304                 bytestowrite = file->nbytes - wpos;
305                 availbytes = MAX_PHYSICAL_FILESIZE - file->curOffset;
306
307                 if ((off_t) bytestowrite > availbytes)
308                         bytestowrite = (int) availbytes;
309
310                 /*
311                  * May need to reposition physical file.
312                  */
313                 thisfile = file->files[file->curFile];
314                 if (file->curOffset != file->offsets[file->curFile])
315                 {
316                         if (FileSeek(thisfile, file->curOffset, SEEK_SET) != file->curOffset)
317                                 return;                 /* seek failed, give up */
318                         file->offsets[file->curFile] = file->curOffset;
319                 }
320                 bytestowrite = FileWrite(thisfile,
321                                                                  file->buffer + wpos,
322                                                                  bytestowrite,
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;
329
330                 pgBufferUsage.temp_blks_written++;
331         }
332         file->dirty = false;
333
334         /*
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!)
339          */
340         file->curOffset -= (file->nbytes - file->pos);
341         if (file->curOffset < 0)        /* handle possible segment crossing */
342         {
343                 file->curFile--;
344                 Assert(file->curFile >= 0);
345                 file->curOffset += MAX_PHYSICAL_FILESIZE;
346         }
347
348         /*
349          * Now we can set the buffer empty without changing the logical position
350          */
351         file->pos = 0;
352         file->nbytes = 0;
353 }
354
355 /*
356  * BufFileRead
357  *
358  * Like fread() except we assume 1-byte element size.
359  */
360 size_t
361 BufFileRead(BufFile *file, void *ptr, size_t size)
362 {
363         size_t          nread = 0;
364         size_t          nthistime;
365
366         if (file->dirty)
367         {
368                 if (BufFileFlush(file) != 0)
369                         return 0;                       /* could not flush... */
370                 Assert(!file->dirty);
371         }
372
373         while (size > 0)
374         {
375                 if (file->pos >= file->nbytes)
376                 {
377                         /* Try to load more data into buffer. */
378                         file->curOffset += file->pos;
379                         file->pos = 0;
380                         file->nbytes = 0;
381                         BufFileLoadBuffer(file);
382                         if (file->nbytes <= 0)
383                                 break;                  /* no more data available */
384                 }
385
386                 nthistime = file->nbytes - file->pos;
387                 if (nthistime > size)
388                         nthistime = size;
389                 Assert(nthistime > 0);
390
391                 memcpy(ptr, file->buffer + file->pos, nthistime);
392
393                 file->pos += nthistime;
394                 ptr = (void *) ((char *) ptr + nthistime);
395                 size -= nthistime;
396                 nread += nthistime;
397         }
398
399         return nread;
400 }
401
402 /*
403  * BufFileWrite
404  *
405  * Like fwrite() except we assume 1-byte element size.
406  */
407 size_t
408 BufFileWrite(BufFile *file, void *ptr, size_t size)
409 {
410         size_t          nwritten = 0;
411         size_t          nthistime;
412
413         while (size > 0)
414         {
415                 if (file->pos >= BLCKSZ)
416                 {
417                         /* Buffer full, dump it out */
418                         if (file->dirty)
419                         {
420                                 BufFileDumpBuffer(file);
421                                 if (file->dirty)
422                                         break;          /* I/O error */
423                         }
424                         else
425                         {
426                                 /* Hmm, went directly from reading to writing? */
427                                 file->curOffset += file->pos;
428                                 file->pos = 0;
429                                 file->nbytes = 0;
430                         }
431                 }
432
433                 nthistime = BLCKSZ - file->pos;
434                 if (nthistime > size)
435                         nthistime = size;
436                 Assert(nthistime > 0);
437
438                 memcpy(file->buffer + file->pos, ptr, nthistime);
439
440                 file->dirty = true;
441                 file->pos += nthistime;
442                 if (file->nbytes < file->pos)
443                         file->nbytes = file->pos;
444                 ptr = (void *) ((char *) ptr + nthistime);
445                 size -= nthistime;
446                 nwritten += nthistime;
447         }
448
449         return nwritten;
450 }
451
452 /*
453  * BufFileFlush
454  *
455  * Like fflush()
456  */
457 static int
458 BufFileFlush(BufFile *file)
459 {
460         if (file->dirty)
461         {
462                 BufFileDumpBuffer(file);
463                 if (file->dirty)
464                         return EOF;
465         }
466
467         return 0;
468 }
469
470 /*
471  * BufFileSeek
472  *
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.
476  *
477  * Result is 0 if OK, EOF if not.  Logical position is not moved if an
478  * impossible seek is attempted.
479  */
480 int
481 BufFileSeek(BufFile *file, int fileno, off_t offset, int whence)
482 {
483         int                     newFile;
484         off_t           newOffset;
485
486         switch (whence)
487         {
488                 case SEEK_SET:
489                         if (fileno < 0)
490                                 return EOF;
491                         newFile = fileno;
492                         newOffset = offset;
493                         break;
494                 case SEEK_CUR:
495
496                         /*
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.
500                          */
501                         newFile = file->curFile;
502                         newOffset = (file->curOffset + file->pos) + offset;
503                         break;
504 #ifdef NOT_USED
505                 case SEEK_END:
506                         /* could be implemented, not needed currently */
507                         break;
508 #endif
509                 default:
510                         elog(ERROR, "invalid whence: %d", whence);
511                         return EOF;
512         }
513         while (newOffset < 0)
514         {
515                 if (--newFile < 0)
516                         return EOF;
517                 newOffset += MAX_PHYSICAL_FILESIZE;
518         }
519         if (newFile == file->curFile &&
520                 newOffset >= file->curOffset &&
521                 newOffset <= file->curOffset + file->nbytes)
522         {
523                 /*
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
527                  * writing.
528                  */
529                 file->pos = (int) (newOffset - file->curOffset);
530                 return 0;
531         }
532         /* Otherwise, must reposition buffer, so flush any dirty data */
533         if (BufFileFlush(file) != 0)
534                 return EOF;
535
536         /*
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).
540          */
541
542         /* convert seek to "start of next seg" to "end of last seg" */
543         if (newFile == file->numFiles && newOffset == 0)
544         {
545                 newFile--;
546                 newOffset = MAX_PHYSICAL_FILESIZE;
547         }
548         while (newOffset > MAX_PHYSICAL_FILESIZE)
549         {
550                 if (++newFile >= file->numFiles)
551                         return EOF;
552                 newOffset -= MAX_PHYSICAL_FILESIZE;
553         }
554         if (newFile >= file->numFiles)
555                 return EOF;
556         /* Seek is OK! */
557         file->curFile = newFile;
558         file->curOffset = newOffset;
559         file->pos = 0;
560         file->nbytes = 0;
561         return 0;
562 }
563
564 void
565 BufFileTell(BufFile *file, int *fileno, off_t *offset)
566 {
567         *fileno = file->curFile;
568         *offset = file->curOffset + file->pos;
569 }
570
571 /*
572  * BufFileSeekBlock --- block-oriented seek
573  *
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...
578  *
579  * Result is 0 if OK, EOF if not.  Logical position is not moved if an
580  * impossible seek is attempted.
581  */
582 int
583 BufFileSeekBlock(BufFile *file, long blknum)
584 {
585         return BufFileSeek(file,
586                                            (int) (blknum / BUFFILE_SEG_SIZE),
587                                            (off_t) (blknum % BUFFILE_SEG_SIZE) * BLCKSZ,
588                                            SEEK_SET);
589 }
590
591 #ifdef NOT_USED
592 /*
593  * BufFileTellBlock --- block-oriented tell
594  *
595  * Any fractional part of a block in the current seek position is ignored.
596  */
597 long
598 BufFileTellBlock(BufFile *file)
599 {
600         long            blknum;
601
602         blknum = (file->curOffset + file->pos) / BLCKSZ;
603         blknum += file->curFile * BUFFILE_SEG_SIZE;
604         return blknum;
605 }
606
607 #endif