PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
buffile.c
Go to the documentation of this file.
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 "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  */
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 isTemp and 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->isTemp = false;
114  file->isInterXact = false;
115  file->dirty = false;
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
130 {
131  File pfile;
132  ResourceOwner oldowner;
133 
134  /* Be sure to associate the file with the BufFile's resource owner */
135  oldowner = CurrentResourceOwner;
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 *
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 *
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
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
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  return; /* seek failed, read nothing */
251  file->offsets[file->curFile] = file->curOffset;
252  }
253 
254  /*
255  * Read whatever we can get, up to a full bufferload.
256  */
257  file->nbytes = FileRead(thisfile, file->buffer, sizeof(file->buffer));
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 
264 }
265 
266 /*
267  * BufFileDumpBuffer
268  *
269  * Dump buffer contents starting at curOffset.
270  * At call, should have dirty = true, nbytes > 0.
271  * On exit, dirty is cleared if successful write, and curOffset is advanced.
272  */
273 static void
275 {
276  int wpos = 0;
277  int bytestowrite;
278  File thisfile;
279 
280  /*
281  * Unlike BufFileLoadBuffer, we must dump the whole buffer even if it
282  * crosses a component-file boundary; so we need a loop.
283  */
284  while (wpos < file->nbytes)
285  {
286  /*
287  * Advance to next component file if necessary and possible.
288  */
289  if (file->curOffset >= MAX_PHYSICAL_FILESIZE && file->isTemp)
290  {
291  while (file->curFile + 1 >= file->numFiles)
292  extendBufFile(file);
293  file->curFile++;
294  file->curOffset = 0L;
295  }
296 
297  /*
298  * Enforce per-file size limit only for temp files, else just try to
299  * write as much as asked...
300  */
301  bytestowrite = file->nbytes - wpos;
302  if (file->isTemp)
303  {
304  off_t availbytes = MAX_PHYSICAL_FILESIZE - file->curOffset;
305 
306  if ((off_t) bytestowrite > availbytes)
307  bytestowrite = (int) availbytes;
308  }
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, file->buffer + wpos, bytestowrite);
321  if (bytestowrite <= 0)
322  return; /* failed to write */
323  file->offsets[file->curFile] += bytestowrite;
324  file->curOffset += bytestowrite;
325  wpos += bytestowrite;
326 
328  }
329  file->dirty = false;
330 
331  /*
332  * At this point, curOffset has been advanced to the end of the buffer,
333  * ie, its original value + nbytes. We need to make it point to the
334  * logical file position, ie, original value + pos, in case that is less
335  * (as could happen due to a small backwards seek in a dirty buffer!)
336  */
337  file->curOffset -= (file->nbytes - file->pos);
338  if (file->curOffset < 0) /* handle possible segment crossing */
339  {
340  file->curFile--;
341  Assert(file->curFile >= 0);
343  }
344 
345  /*
346  * Now we can set the buffer empty without changing the logical position
347  */
348  file->pos = 0;
349  file->nbytes = 0;
350 }
351 
352 /*
353  * BufFileRead
354  *
355  * Like fread() except we assume 1-byte element size.
356  */
357 size_t
358 BufFileRead(BufFile *file, void *ptr, size_t size)
359 {
360  size_t nread = 0;
361  size_t nthistime;
362 
363  if (file->dirty)
364  {
365  if (BufFileFlush(file) != 0)
366  return 0; /* could not flush... */
367  Assert(!file->dirty);
368  }
369 
370  while (size > 0)
371  {
372  if (file->pos >= file->nbytes)
373  {
374  /* Try to load more data into buffer. */
375  file->curOffset += file->pos;
376  file->pos = 0;
377  file->nbytes = 0;
378  BufFileLoadBuffer(file);
379  if (file->nbytes <= 0)
380  break; /* no more data available */
381  }
382 
383  nthistime = file->nbytes - file->pos;
384  if (nthistime > size)
385  nthistime = size;
386  Assert(nthistime > 0);
387 
388  memcpy(ptr, file->buffer + file->pos, nthistime);
389 
390  file->pos += nthistime;
391  ptr = (void *) ((char *) ptr + nthistime);
392  size -= nthistime;
393  nread += nthistime;
394  }
395 
396  return nread;
397 }
398 
399 /*
400  * BufFileWrite
401  *
402  * Like fwrite() except we assume 1-byte element size.
403  */
404 size_t
405 BufFileWrite(BufFile *file, void *ptr, size_t size)
406 {
407  size_t nwritten = 0;
408  size_t nthistime;
409 
410  while (size > 0)
411  {
412  if (file->pos >= BLCKSZ)
413  {
414  /* Buffer full, dump it out */
415  if (file->dirty)
416  {
417  BufFileDumpBuffer(file);
418  if (file->dirty)
419  break; /* I/O error */
420  }
421  else
422  {
423  /* Hmm, went directly from reading to writing? */
424  file->curOffset += file->pos;
425  file->pos = 0;
426  file->nbytes = 0;
427  }
428  }
429 
430  nthistime = BLCKSZ - file->pos;
431  if (nthistime > size)
432  nthistime = size;
433  Assert(nthistime > 0);
434 
435  memcpy(file->buffer + file->pos, ptr, nthistime);
436 
437  file->dirty = true;
438  file->pos += nthistime;
439  if (file->nbytes < file->pos)
440  file->nbytes = file->pos;
441  ptr = (void *) ((char *) ptr + nthistime);
442  size -= nthistime;
443  nwritten += nthistime;
444  }
445 
446  return nwritten;
447 }
448 
449 /*
450  * BufFileFlush
451  *
452  * Like fflush()
453  */
454 static int
456 {
457  if (file->dirty)
458  {
459  BufFileDumpBuffer(file);
460  if (file->dirty)
461  return EOF;
462  }
463 
464  return 0;
465 }
466 
467 /*
468  * BufFileSeek
469  *
470  * Like fseek(), except that target position needs two values in order to
471  * work when logical filesize exceeds maximum value representable by long.
472  * We do not support relative seeks across more than LONG_MAX, however.
473  *
474  * Result is 0 if OK, EOF if not. Logical position is not moved if an
475  * impossible seek is attempted.
476  */
477 int
478 BufFileSeek(BufFile *file, int fileno, off_t offset, int whence)
479 {
480  int newFile;
481  off_t newOffset;
482 
483  switch (whence)
484  {
485  case SEEK_SET:
486  if (fileno < 0)
487  return EOF;
488  newFile = fileno;
489  newOffset = offset;
490  break;
491  case SEEK_CUR:
492 
493  /*
494  * Relative seek considers only the signed offset, ignoring
495  * fileno. Note that large offsets (> 1 gig) risk overflow in this
496  * add, unless we have 64-bit off_t.
497  */
498  newFile = file->curFile;
499  newOffset = (file->curOffset + file->pos) + offset;
500  break;
501 #ifdef NOT_USED
502  case SEEK_END:
503  /* could be implemented, not needed currently */
504  break;
505 #endif
506  default:
507  elog(ERROR, "invalid whence: %d", whence);
508  return EOF;
509  }
510  while (newOffset < 0)
511  {
512  if (--newFile < 0)
513  return EOF;
514  newOffset += MAX_PHYSICAL_FILESIZE;
515  }
516  if (newFile == file->curFile &&
517  newOffset >= file->curOffset &&
518  newOffset <= file->curOffset + file->nbytes)
519  {
520  /*
521  * Seek is to a point within existing buffer; we can just adjust
522  * pos-within-buffer, without flushing buffer. Note this is OK
523  * whether reading or writing, but buffer remains dirty if we were
524  * writing.
525  */
526  file->pos = (int) (newOffset - file->curOffset);
527  return 0;
528  }
529  /* Otherwise, must reposition buffer, so flush any dirty data */
530  if (BufFileFlush(file) != 0)
531  return EOF;
532 
533  /*
534  * At this point and no sooner, check for seek past last segment. The
535  * above flush could have created a new segment, so checking sooner would
536  * not work (at least not with this code).
537  */
538  if (file->isTemp)
539  {
540  /* convert seek to "start of next seg" to "end of last seg" */
541  if (newFile == file->numFiles && newOffset == 0)
542  {
543  newFile--;
544  newOffset = MAX_PHYSICAL_FILESIZE;
545  }
546  while (newOffset > MAX_PHYSICAL_FILESIZE)
547  {
548  if (++newFile >= file->numFiles)
549  return EOF;
550  newOffset -= MAX_PHYSICAL_FILESIZE;
551  }
552  }
553  if (newFile >= file->numFiles)
554  return EOF;
555  /* Seek is OK! */
556  file->curFile = newFile;
557  file->curOffset = newOffset;
558  file->pos = 0;
559  file->nbytes = 0;
560  return 0;
561 }
562 
563 void
564 BufFileTell(BufFile *file, int *fileno, off_t *offset)
565 {
566  *fileno = file->curFile;
567  *offset = file->curOffset + file->pos;
568 }
569 
570 /*
571  * BufFileSeekBlock --- block-oriented seek
572  *
573  * Performs absolute seek to the start of the n'th BLCKSZ-sized block of
574  * the file. Note that users of this interface will fail if their files
575  * exceed BLCKSZ * LONG_MAX bytes, but that is quite a lot; we don't work
576  * with tables bigger than that, either...
577  *
578  * Result is 0 if OK, EOF if not. Logical position is not moved if an
579  * impossible seek is attempted.
580  */
581 int
582 BufFileSeekBlock(BufFile *file, long blknum)
583 {
584  return BufFileSeek(file,
585  (int) (blknum / BUFFILE_SEG_SIZE),
586  (off_t) (blknum % BUFFILE_SEG_SIZE) * BLCKSZ,
587  SEEK_SET);
588 }
589 
590 #ifdef NOT_USED
591 /*
592  * BufFileTellBlock --- block-oriented tell
593  *
594  * Any fractional part of a block in the current seek position is ignored.
595  */
596 long
597 BufFileTellBlock(BufFile *file)
598 {
599  long blknum;
600 
601  blknum = (file->curOffset + file->pos) / BLCKSZ;
602  blknum += file->curFile * BUFFILE_SEG_SIZE;
603  return blknum;
604 }
605 
606 #endif
int FileWrite(File file, char *buffer, int amount)
Definition: fd.c:1666
off_t * offsets
Definition: buffile.c:63
int nbytes
Definition: buffile.c:88
int BufFileSeek(BufFile *file, int fileno, off_t offset, int whence)
Definition: buffile.c:478
static int BufFileFlush(BufFile *file)
Definition: buffile.c:455
ResourceOwner CurrentResourceOwner
Definition: resowner.c:138
#define MAX_PHYSICAL_FILESIZE
Definition: buffile.c:50
#define BUFFILE_SEG_SIZE
Definition: buffile.c:51
bool isTemp
Definition: buffile.c:70
long temp_blks_written
Definition: instrument.h:30
static void extendBufFile(BufFile *file)
Definition: buffile.c:129
int numFiles
Definition: buffile.c:60
ResourceOwner resowner
Definition: buffile.c:79
void BufFileClose(BufFile *file)
Definition: buffile.c:202
void pfree(void *pointer)
Definition: mcxt.c:992
#define ERROR
Definition: elog.h:43
BufFile * BufFileCreateTemp(bool interXact)
Definition: buffile.c:166
bool isInterXact
Definition: buffile.c:71
static BufFile * makeBufFile(File firstfile)
Definition: buffile.c:104
static void BufFileDumpBuffer(BufFile *file)
Definition: buffile.c:274
long temp_blks_read
Definition: instrument.h:29
File * files
Definition: buffile.c:62
#define wpos(wep)
Definition: tsrank.c:27
off_t curOffset
Definition: buffile.c:86
int BufFileSeekBlock(BufFile *file, long blknum)
Definition: buffile.c:582
int curFile
Definition: buffile.c:85
void BufFileTell(BufFile *file, int *fileno, off_t *offset)
Definition: buffile.c:564
void FileClose(File file)
Definition: fd.c:1456
#define Assert(condition)
Definition: c.h:671
File OpenTemporaryFile(bool interXact)
Definition: fd.c:1334
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:1021
bool dirty
Definition: buffile.c:72
char buffer[BLCKSZ]
Definition: buffile.c:89
void * palloc(Size size)
Definition: mcxt.c:891
int i
size_t BufFileRead(BufFile *file, void *ptr, size_t size)
Definition: buffile.c:358
size_t BufFileWrite(BufFile *file, void *ptr, size_t size)
Definition: buffile.c:405
static void BufFileLoadBuffer(BufFile *file)
Definition: buffile.c:225
#define elog
Definition: elog.h:219
off_t FileSeek(File file, off_t offset, int whence)
Definition: fd.c:1802
int File
Definition: fd.h:51
BufferUsage pgBufferUsage
Definition: instrument.c:20
int FileRead(File file, char *buffer, int amount)
Definition: fd.c:1604
int pos
Definition: buffile.c:87