PostgreSQL Source Code  git master
buffile.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * buffile.c
4  * Management of large buffered temporary files.
5  *
6  * Portions Copyright (c) 1996-2023, 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 query/transaction end. Since the underlying
24  * virtual Files are made with OpenTemporaryFile, 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  * BufFile supports temporary files that can be shared with other backends, as
36  * infrastructure for parallel execution. Such files need to be created as a
37  * member of a SharedFileSet that all participants are attached to.
38  *
39  * BufFile also supports temporary files that can be used by the single backend
40  * when the corresponding files need to be survived across the transaction and
41  * need to be opened and closed multiple times. Such files need to be created
42  * as a member of a FileSet.
43  *-------------------------------------------------------------------------
44  */
45 
46 #include "postgres.h"
47 
48 #include "commands/tablespace.h"
49 #include "executor/instrument.h"
50 #include "miscadmin.h"
51 #include "pgstat.h"
52 #include "storage/buf_internals.h"
53 #include "storage/buffile.h"
54 #include "storage/fd.h"
55 #include "utils/resowner.h"
56 
57 /*
58  * We break BufFiles into gigabyte-sized segments, regardless of RELSEG_SIZE.
59  * The reason is that we'd like large BufFiles to be spread across multiple
60  * tablespaces when available.
61  */
62 #define MAX_PHYSICAL_FILESIZE 0x40000000
63 #define BUFFILE_SEG_SIZE (MAX_PHYSICAL_FILESIZE / BLCKSZ)
64 
65 /*
66  * This data structure represents a buffered file that consists of one or
67  * more physical files (each accessed through a virtual file descriptor
68  * managed by fd.c).
69  */
70 struct BufFile
71 {
72  int numFiles; /* number of physical files in set */
73  /* all files except the last have length exactly MAX_PHYSICAL_FILESIZE */
74  File *files; /* palloc'd array with numFiles entries */
75 
76  bool isInterXact; /* keep open over transactions? */
77  bool dirty; /* does buffer need to be written? */
78  bool readOnly; /* has the file been set to read only? */
79 
80  FileSet *fileset; /* space for fileset based segment files */
81  const char *name; /* name of fileset based BufFile */
82 
83  /*
84  * resowner is the ResourceOwner to use for underlying temp files. (We
85  * don't need to remember the memory context we're using explicitly,
86  * because after creation we only repalloc our arrays larger.)
87  */
89 
90  /*
91  * "current pos" is position of start of buffer within the logical file.
92  * Position as seen by user of BufFile is (curFile, curOffset + pos).
93  */
94  int curFile; /* file index (0..n) part of current pos */
95  off_t curOffset; /* offset part of current pos */
96  int pos; /* next read/write position in buffer */
97  int nbytes; /* total # of valid bytes in buffer */
99 };
100 
101 static BufFile *makeBufFileCommon(int nfiles);
102 static BufFile *makeBufFile(File firstfile);
103 static void extendBufFile(BufFile *file);
104 static void BufFileLoadBuffer(BufFile *file);
105 static void BufFileDumpBuffer(BufFile *file);
106 static void BufFileFlush(BufFile *file);
107 static File MakeNewFileSetSegment(BufFile *buffile, int segment);
108 
109 /*
110  * Create BufFile and perform the common initialization.
111  */
112 static BufFile *
113 makeBufFileCommon(int nfiles)
114 {
115  BufFile *file = (BufFile *) palloc(sizeof(BufFile));
116 
117  file->numFiles = nfiles;
118  file->isInterXact = false;
119  file->dirty = false;
121  file->curFile = 0;
122  file->curOffset = 0L;
123  file->pos = 0;
124  file->nbytes = 0;
125 
126  return file;
127 }
128 
129 /*
130  * Create a BufFile given the first underlying physical file.
131  * NOTE: caller must set isInterXact if appropriate.
132  */
133 static BufFile *
134 makeBufFile(File firstfile)
135 {
136  BufFile *file = makeBufFileCommon(1);
137 
138  file->files = (File *) palloc(sizeof(File));
139  file->files[0] = firstfile;
140  file->readOnly = false;
141  file->fileset = NULL;
142  file->name = NULL;
143 
144  return file;
145 }
146 
147 /*
148  * Add another component temp file.
149  */
150 static void
152 {
153  File pfile;
154  ResourceOwner oldowner;
155 
156  /* Be sure to associate the file with the BufFile's resource owner */
157  oldowner = CurrentResourceOwner;
159 
160  if (file->fileset == NULL)
161  pfile = OpenTemporaryFile(file->isInterXact);
162  else
163  pfile = MakeNewFileSetSegment(file, file->numFiles);
164 
165  Assert(pfile >= 0);
166 
167  CurrentResourceOwner = oldowner;
168 
169  file->files = (File *) repalloc(file->files,
170  (file->numFiles + 1) * sizeof(File));
171  file->files[file->numFiles] = pfile;
172  file->numFiles++;
173 }
174 
175 /*
176  * Create a BufFile for a new temporary file (which will expand to become
177  * multiple temporary files if more than MAX_PHYSICAL_FILESIZE bytes are
178  * written to it).
179  *
180  * If interXact is true, the temp file will not be automatically deleted
181  * at end of transaction.
182  *
183  * Note: if interXact is true, the caller had better be calling us in a
184  * memory context, and with a resource owner, that will survive across
185  * transaction boundaries.
186  */
187 BufFile *
188 BufFileCreateTemp(bool interXact)
189 {
190  BufFile *file;
191  File pfile;
192 
193  /*
194  * Ensure that temp tablespaces are set up for OpenTemporaryFile to use.
195  * Possibly the caller will have done this already, but it seems useful to
196  * double-check here. Failure to do this at all would result in the temp
197  * files always getting placed in the default tablespace, which is a
198  * pretty hard-to-detect bug. Callers may prefer to do it earlier if they
199  * want to be sure that any required catalog access is done in some other
200  * resource context.
201  */
203 
204  pfile = OpenTemporaryFile(interXact);
205  Assert(pfile >= 0);
206 
207  file = makeBufFile(pfile);
208  file->isInterXact = interXact;
209 
210  return file;
211 }
212 
213 /*
214  * Build the name for a given segment of a given BufFile.
215  */
216 static void
217 FileSetSegmentName(char *name, const char *buffile_name, int segment)
218 {
219  snprintf(name, MAXPGPATH, "%s.%d", buffile_name, segment);
220 }
221 
222 /*
223  * Create a new segment file backing a fileset based BufFile.
224  */
225 static File
226 MakeNewFileSetSegment(BufFile *buffile, int segment)
227 {
228  char name[MAXPGPATH];
229  File file;
230 
231  /*
232  * It is possible that there are files left over from before a crash
233  * restart with the same name. In order for BufFileOpenFileSet() not to
234  * get confused about how many segments there are, we'll unlink the next
235  * segment number if it already exists.
236  */
237  FileSetSegmentName(name, buffile->name, segment + 1);
238  FileSetDelete(buffile->fileset, name, true);
239 
240  /* Create the new segment. */
241  FileSetSegmentName(name, buffile->name, segment);
242  file = FileSetCreate(buffile->fileset, name);
243 
244  /* FileSetCreate would've errored out */
245  Assert(file > 0);
246 
247  return file;
248 }
249 
250 /*
251  * Create a BufFile that can be discovered and opened read-only by other
252  * backends that are attached to the same SharedFileSet using the same name.
253  *
254  * The naming scheme for fileset based BufFiles is left up to the calling code.
255  * The name will appear as part of one or more filenames on disk, and might
256  * provide clues to administrators about which subsystem is generating
257  * temporary file data. Since each SharedFileSet object is backed by one or
258  * more uniquely named temporary directory, names don't conflict with
259  * unrelated SharedFileSet objects.
260  */
261 BufFile *
262 BufFileCreateFileSet(FileSet *fileset, const char *name)
263 {
264  BufFile *file;
265 
266  file = makeBufFileCommon(1);
267  file->fileset = fileset;
268  file->name = pstrdup(name);
269  file->files = (File *) palloc(sizeof(File));
270  file->files[0] = MakeNewFileSetSegment(file, 0);
271  file->readOnly = false;
272 
273  return file;
274 }
275 
276 /*
277  * Open a file that was previously created in another backend (or this one)
278  * with BufFileCreateFileSet in the same FileSet using the same name.
279  * The backend that created the file must have called BufFileClose() or
280  * BufFileExportFileSet() to make sure that it is ready to be opened by other
281  * backends and render it read-only. If missing_ok is true, which indicates
282  * that missing files can be safely ignored, then return NULL if the BufFile
283  * with the given name is not found, otherwise, throw an error.
284  */
285 BufFile *
286 BufFileOpenFileSet(FileSet *fileset, const char *name, int mode,
287  bool missing_ok)
288 {
289  BufFile *file;
290  char segment_name[MAXPGPATH];
291  Size capacity = 16;
292  File *files;
293  int nfiles = 0;
294 
295  files = palloc(sizeof(File) * capacity);
296 
297  /*
298  * We don't know how many segments there are, so we'll probe the
299  * filesystem to find out.
300  */
301  for (;;)
302  {
303  /* See if we need to expand our file segment array. */
304  if (nfiles + 1 > capacity)
305  {
306  capacity *= 2;
307  files = repalloc(files, sizeof(File) * capacity);
308  }
309  /* Try to load a segment. */
310  FileSetSegmentName(segment_name, name, nfiles);
311  files[nfiles] = FileSetOpen(fileset, segment_name, mode);
312  if (files[nfiles] <= 0)
313  break;
314  ++nfiles;
315 
317  }
318 
319  /*
320  * If we didn't find any files at all, then no BufFile exists with this
321  * name.
322  */
323  if (nfiles == 0)
324  {
325  /* free the memory */
326  pfree(files);
327 
328  if (missing_ok)
329  return NULL;
330 
331  ereport(ERROR,
333  errmsg("could not open temporary file \"%s\" from BufFile \"%s\": %m",
334  segment_name, name)));
335  }
336 
337  file = makeBufFileCommon(nfiles);
338  file->files = files;
339  file->readOnly = (mode == O_RDONLY);
340  file->fileset = fileset;
341  file->name = pstrdup(name);
342 
343  return file;
344 }
345 
346 /*
347  * Delete a BufFile that was created by BufFileCreateFileSet in the given
348  * FileSet using the given name.
349  *
350  * It is not necessary to delete files explicitly with this function. It is
351  * provided only as a way to delete files proactively, rather than waiting for
352  * the FileSet to be cleaned up.
353  *
354  * Only one backend should attempt to delete a given name, and should know
355  * that it exists and has been exported or closed otherwise missing_ok should
356  * be passed true.
357  */
358 void
359 BufFileDeleteFileSet(FileSet *fileset, const char *name, bool missing_ok)
360 {
361  char segment_name[MAXPGPATH];
362  int segment = 0;
363  bool found = false;
364 
365  /*
366  * We don't know how many segments the file has. We'll keep deleting
367  * until we run out. If we don't manage to find even an initial segment,
368  * raise an error.
369  */
370  for (;;)
371  {
372  FileSetSegmentName(segment_name, name, segment);
373  if (!FileSetDelete(fileset, segment_name, true))
374  break;
375  found = true;
376  ++segment;
377 
379  }
380 
381  if (!found && !missing_ok)
382  elog(ERROR, "could not delete unknown BufFile \"%s\"", name);
383 }
384 
385 /*
386  * BufFileExportFileSet --- flush and make read-only, in preparation for sharing.
387  */
388 void
390 {
391  /* Must be a file belonging to a FileSet. */
392  Assert(file->fileset != NULL);
393 
394  /* It's probably a bug if someone calls this twice. */
395  Assert(!file->readOnly);
396 
397  BufFileFlush(file);
398  file->readOnly = true;
399 }
400 
401 /*
402  * Close a BufFile
403  *
404  * Like fclose(), this also implicitly FileCloses the underlying File.
405  */
406 void
408 {
409  int i;
410 
411  /* flush any unwritten data */
412  BufFileFlush(file);
413  /* close and delete the underlying file(s) */
414  for (i = 0; i < file->numFiles; i++)
415  FileClose(file->files[i]);
416  /* release the buffer space */
417  pfree(file->files);
418  pfree(file);
419 }
420 
421 /*
422  * BufFileLoadBuffer
423  *
424  * Load some data into buffer, if possible, starting from curOffset.
425  * At call, must have dirty = false, pos and nbytes = 0.
426  * On exit, nbytes is number of bytes loaded.
427  */
428 static void
430 {
431  File thisfile;
432  instr_time io_start;
433  instr_time io_time;
434 
435  /*
436  * Advance to next component file if necessary and possible.
437  */
438  if (file->curOffset >= MAX_PHYSICAL_FILESIZE &&
439  file->curFile + 1 < file->numFiles)
440  {
441  file->curFile++;
442  file->curOffset = 0L;
443  }
444 
445  thisfile = file->files[file->curFile];
446 
447  if (track_io_timing)
448  INSTR_TIME_SET_CURRENT(io_start);
449  else
450  INSTR_TIME_SET_ZERO(io_start);
451 
452  /*
453  * Read whatever we can get, up to a full bufferload.
454  */
455  file->nbytes = FileRead(thisfile,
456  file->buffer.data,
457  sizeof(file->buffer),
458  file->curOffset,
460  if (file->nbytes < 0)
461  {
462  file->nbytes = 0;
463  ereport(ERROR,
465  errmsg("could not read file \"%s\": %m",
466  FilePathName(thisfile))));
467  }
468 
469  if (track_io_timing)
470  {
471  INSTR_TIME_SET_CURRENT(io_time);
472  INSTR_TIME_SUBTRACT(io_time, io_start);
474  }
475 
476  /* we choose not to advance curOffset here */
477 
478  if (file->nbytes > 0)
480 }
481 
482 /*
483  * BufFileDumpBuffer
484  *
485  * Dump buffer contents starting at curOffset.
486  * At call, should have dirty = true, nbytes > 0.
487  * On exit, dirty is cleared if successful write, and curOffset is advanced.
488  */
489 static void
491 {
492  int wpos = 0;
493  int bytestowrite;
494  File thisfile;
495 
496  /*
497  * Unlike BufFileLoadBuffer, we must dump the whole buffer even if it
498  * crosses a component-file boundary; so we need a loop.
499  */
500  while (wpos < file->nbytes)
501  {
502  off_t availbytes;
503  instr_time io_start;
504  instr_time io_time;
505 
506  /*
507  * Advance to next component file if necessary and possible.
508  */
509  if (file->curOffset >= MAX_PHYSICAL_FILESIZE)
510  {
511  while (file->curFile + 1 >= file->numFiles)
512  extendBufFile(file);
513  file->curFile++;
514  file->curOffset = 0L;
515  }
516 
517  /*
518  * Determine how much we need to write into this file.
519  */
520  bytestowrite = file->nbytes - wpos;
521  availbytes = MAX_PHYSICAL_FILESIZE - file->curOffset;
522 
523  if ((off_t) bytestowrite > availbytes)
524  bytestowrite = (int) availbytes;
525 
526  thisfile = file->files[file->curFile];
527 
528  if (track_io_timing)
529  INSTR_TIME_SET_CURRENT(io_start);
530  else
531  INSTR_TIME_SET_ZERO(io_start);
532 
533  bytestowrite = FileWrite(thisfile,
534  file->buffer.data + wpos,
535  bytestowrite,
536  file->curOffset,
538  if (bytestowrite <= 0)
539  ereport(ERROR,
541  errmsg("could not write to file \"%s\": %m",
542  FilePathName(thisfile))));
543 
544  if (track_io_timing)
545  {
546  INSTR_TIME_SET_CURRENT(io_time);
547  INSTR_TIME_SUBTRACT(io_time, io_start);
549  }
550 
551  file->curOffset += bytestowrite;
552  wpos += bytestowrite;
553 
555  }
556  file->dirty = false;
557 
558  /*
559  * At this point, curOffset has been advanced to the end of the buffer,
560  * ie, its original value + nbytes. We need to make it point to the
561  * logical file position, ie, original value + pos, in case that is less
562  * (as could happen due to a small backwards seek in a dirty buffer!)
563  */
564  file->curOffset -= (file->nbytes - file->pos);
565  if (file->curOffset < 0) /* handle possible segment crossing */
566  {
567  file->curFile--;
568  Assert(file->curFile >= 0);
570  }
571 
572  /*
573  * Now we can set the buffer empty without changing the logical position
574  */
575  file->pos = 0;
576  file->nbytes = 0;
577 }
578 
579 /*
580  * BufFileRead variants
581  *
582  * Like fread() except we assume 1-byte element size and report I/O errors via
583  * ereport().
584  *
585  * If 'exact' is true, then an error is also raised if the number of bytes
586  * read is not exactly 'size' (no short reads). If 'exact' and 'eofOK' are
587  * true, then reading zero bytes is ok.
588  */
589 static size_t
590 BufFileReadCommon(BufFile *file, void *ptr, size_t size, bool exact, bool eofOK)
591 {
592  size_t start_size = size;
593  size_t nread = 0;
594  size_t nthistime;
595 
596  BufFileFlush(file);
597 
598  while (size > 0)
599  {
600  if (file->pos >= file->nbytes)
601  {
602  /* Try to load more data into buffer. */
603  file->curOffset += file->pos;
604  file->pos = 0;
605  file->nbytes = 0;
606  BufFileLoadBuffer(file);
607  if (file->nbytes <= 0)
608  break; /* no more data available */
609  }
610 
611  nthistime = file->nbytes - file->pos;
612  if (nthistime > size)
613  nthistime = size;
614  Assert(nthistime > 0);
615 
616  memcpy(ptr, file->buffer.data + file->pos, nthistime);
617 
618  file->pos += nthistime;
619  ptr = (char *) ptr + nthistime;
620  size -= nthistime;
621  nread += nthistime;
622  }
623 
624  if (exact &&
625  (nread != start_size && !(nread == 0 && eofOK)))
626  ereport(ERROR,
628  file->name ?
629  errmsg("could not read from file set \"%s\": read only %zu of %zu bytes",
630  file->name, nread, start_size) :
631  errmsg("could not read from temporary file: read only %zu of %zu bytes",
632  nread, start_size));
633 
634  return nread;
635 }
636 
637 /*
638  * Legacy interface where the caller needs to check for end of file or short
639  * reads.
640  */
641 size_t
642 BufFileRead(BufFile *file, void *ptr, size_t size)
643 {
644  return BufFileReadCommon(file, ptr, size, false, false);
645 }
646 
647 /*
648  * Require read of exactly the specified size.
649  */
650 void
651 BufFileReadExact(BufFile *file, void *ptr, size_t size)
652 {
653  BufFileReadCommon(file, ptr, size, true, false);
654 }
655 
656 /*
657  * Require read of exactly the specified size, but optionally allow end of
658  * file (in which case 0 is returned).
659  */
660 size_t
661 BufFileReadMaybeEOF(BufFile *file, void *ptr, size_t size, bool eofOK)
662 {
663  return BufFileReadCommon(file, ptr, size, true, eofOK);
664 }
665 
666 /*
667  * BufFileWrite
668  *
669  * Like fwrite() except we assume 1-byte element size and report errors via
670  * ereport().
671  */
672 void
673 BufFileWrite(BufFile *file, const void *ptr, size_t size)
674 {
675  size_t nthistime;
676 
677  Assert(!file->readOnly);
678 
679  while (size > 0)
680  {
681  if (file->pos >= BLCKSZ)
682  {
683  /* Buffer full, dump it out */
684  if (file->dirty)
685  BufFileDumpBuffer(file);
686  else
687  {
688  /* Hmm, went directly from reading to writing? */
689  file->curOffset += file->pos;
690  file->pos = 0;
691  file->nbytes = 0;
692  }
693  }
694 
695  nthistime = BLCKSZ - file->pos;
696  if (nthistime > size)
697  nthistime = size;
698  Assert(nthistime > 0);
699 
700  memcpy(file->buffer.data + file->pos, ptr, nthistime);
701 
702  file->dirty = true;
703  file->pos += nthistime;
704  if (file->nbytes < file->pos)
705  file->nbytes = file->pos;
706  ptr = (const char *) ptr + nthistime;
707  size -= nthistime;
708  }
709 }
710 
711 /*
712  * BufFileFlush
713  *
714  * Like fflush(), except that I/O errors are reported with ereport().
715  */
716 static void
718 {
719  if (file->dirty)
720  BufFileDumpBuffer(file);
721 
722  Assert(!file->dirty);
723 }
724 
725 /*
726  * BufFileSeek
727  *
728  * Like fseek(), except that target position needs two values in order to
729  * work when logical filesize exceeds maximum value representable by off_t.
730  * We do not support relative seeks across more than that, however.
731  * I/O errors are reported by ereport().
732  *
733  * Result is 0 if OK, EOF if not. Logical position is not moved if an
734  * impossible seek is attempted.
735  */
736 int
737 BufFileSeek(BufFile *file, int fileno, off_t offset, int whence)
738 {
739  int newFile;
740  off_t newOffset;
741 
742  switch (whence)
743  {
744  case SEEK_SET:
745  if (fileno < 0)
746  return EOF;
747  newFile = fileno;
748  newOffset = offset;
749  break;
750  case SEEK_CUR:
751 
752  /*
753  * Relative seek considers only the signed offset, ignoring
754  * fileno. Note that large offsets (> 1 GB) risk overflow in this
755  * add, unless we have 64-bit off_t.
756  */
757  newFile = file->curFile;
758  newOffset = (file->curOffset + file->pos) + offset;
759  break;
760  case SEEK_END:
761 
762  /*
763  * The file size of the last file gives us the end offset of that
764  * file.
765  */
766  newFile = file->numFiles - 1;
767  newOffset = FileSize(file->files[file->numFiles - 1]);
768  if (newOffset < 0)
769  ereport(ERROR,
771  errmsg("could not determine size of temporary file \"%s\" from BufFile \"%s\": %m",
772  FilePathName(file->files[file->numFiles - 1]),
773  file->name)));
774  break;
775  default:
776  elog(ERROR, "invalid whence: %d", whence);
777  return EOF;
778  }
779  while (newOffset < 0)
780  {
781  if (--newFile < 0)
782  return EOF;
783  newOffset += MAX_PHYSICAL_FILESIZE;
784  }
785  if (newFile == file->curFile &&
786  newOffset >= file->curOffset &&
787  newOffset <= file->curOffset + file->nbytes)
788  {
789  /*
790  * Seek is to a point within existing buffer; we can just adjust
791  * pos-within-buffer, without flushing buffer. Note this is OK
792  * whether reading or writing, but buffer remains dirty if we were
793  * writing.
794  */
795  file->pos = (int) (newOffset - file->curOffset);
796  return 0;
797  }
798  /* Otherwise, must reposition buffer, so flush any dirty data */
799  BufFileFlush(file);
800 
801  /*
802  * At this point and no sooner, check for seek past last segment. The
803  * above flush could have created a new segment, so checking sooner would
804  * not work (at least not with this code).
805  */
806 
807  /* convert seek to "start of next seg" to "end of last seg" */
808  if (newFile == file->numFiles && newOffset == 0)
809  {
810  newFile--;
811  newOffset = MAX_PHYSICAL_FILESIZE;
812  }
813  while (newOffset > MAX_PHYSICAL_FILESIZE)
814  {
815  if (++newFile >= file->numFiles)
816  return EOF;
817  newOffset -= MAX_PHYSICAL_FILESIZE;
818  }
819  if (newFile >= file->numFiles)
820  return EOF;
821  /* Seek is OK! */
822  file->curFile = newFile;
823  file->curOffset = newOffset;
824  file->pos = 0;
825  file->nbytes = 0;
826  return 0;
827 }
828 
829 void
830 BufFileTell(BufFile *file, int *fileno, off_t *offset)
831 {
832  *fileno = file->curFile;
833  *offset = file->curOffset + file->pos;
834 }
835 
836 /*
837  * BufFileSeekBlock --- block-oriented seek
838  *
839  * Performs absolute seek to the start of the n'th BLCKSZ-sized block of
840  * the file. Note that users of this interface will fail if their files
841  * exceed BLCKSZ * LONG_MAX bytes, but that is quite a lot; we don't work
842  * with tables bigger than that, either...
843  *
844  * Result is 0 if OK, EOF if not. Logical position is not moved if an
845  * impossible seek is attempted.
846  */
847 int
848 BufFileSeekBlock(BufFile *file, long blknum)
849 {
850  return BufFileSeek(file,
851  (int) (blknum / BUFFILE_SEG_SIZE),
852  (off_t) (blknum % BUFFILE_SEG_SIZE) * BLCKSZ,
853  SEEK_SET);
854 }
855 
856 #ifdef NOT_USED
857 /*
858  * BufFileTellBlock --- block-oriented tell
859  *
860  * Any fractional part of a block in the current seek position is ignored.
861  */
862 long
863 BufFileTellBlock(BufFile *file)
864 {
865  long blknum;
866 
867  blknum = (file->curOffset + file->pos) / BLCKSZ;
868  blknum += file->curFile * BUFFILE_SEG_SIZE;
869  return blknum;
870 }
871 
872 #endif
873 
874 /*
875  * Return the current fileset based BufFile size.
876  *
877  * Counts any holes left behind by BufFileAppend as part of the size.
878  * ereport()s on failure.
879  */
880 int64
882 {
883  int64 lastFileSize;
884 
885  Assert(file->fileset != NULL);
886 
887  /* Get the size of the last physical file. */
888  lastFileSize = FileSize(file->files[file->numFiles - 1]);
889  if (lastFileSize < 0)
890  ereport(ERROR,
892  errmsg("could not determine size of temporary file \"%s\" from BufFile \"%s\": %m",
893  FilePathName(file->files[file->numFiles - 1]),
894  file->name)));
895 
896  return ((file->numFiles - 1) * (int64) MAX_PHYSICAL_FILESIZE) +
897  lastFileSize;
898 }
899 
900 /*
901  * Append the contents of source file (managed within fileset) to
902  * end of target file (managed within same fileset).
903  *
904  * Note that operation subsumes ownership of underlying resources from
905  * "source". Caller should never call BufFileClose against source having
906  * called here first. Resource owners for source and target must match,
907  * too.
908  *
909  * This operation works by manipulating lists of segment files, so the
910  * file content is always appended at a MAX_PHYSICAL_FILESIZE-aligned
911  * boundary, typically creating empty holes before the boundary. These
912  * areas do not contain any interesting data, and cannot be read from by
913  * caller.
914  *
915  * Returns the block number within target where the contents of source
916  * begins. Caller should apply this as an offset when working off block
917  * positions that are in terms of the original BufFile space.
918  */
919 long
921 {
922  long startBlock = target->numFiles * BUFFILE_SEG_SIZE;
923  int newNumFiles = target->numFiles + source->numFiles;
924  int i;
925 
926  Assert(target->fileset != NULL);
927  Assert(source->readOnly);
928  Assert(!source->dirty);
929  Assert(source->fileset != NULL);
930 
931  if (target->resowner != source->resowner)
932  elog(ERROR, "could not append BufFile with non-matching resource owner");
933 
934  target->files = (File *)
935  repalloc(target->files, sizeof(File) * newNumFiles);
936  for (i = target->numFiles; i < newNumFiles; i++)
937  target->files[i] = source->files[i - target->numFiles];
938  target->numFiles = newNumFiles;
939 
940  return startBlock;
941 }
942 
943 /*
944  * Truncate a BufFile created by BufFileCreateFileSet up to the given fileno
945  * and the offset.
946  */
947 void
948 BufFileTruncateFileSet(BufFile *file, int fileno, off_t offset)
949 {
950  int numFiles = file->numFiles;
951  int newFile = fileno;
952  off_t newOffset = file->curOffset;
953  char segment_name[MAXPGPATH];
954  int i;
955 
956  /*
957  * Loop over all the files up to the given fileno and remove the files
958  * that are greater than the fileno and truncate the given file up to the
959  * offset. Note that we also remove the given fileno if the offset is 0
960  * provided it is not the first file in which we truncate it.
961  */
962  for (i = file->numFiles - 1; i >= fileno; i--)
963  {
964  if ((i != fileno || offset == 0) && i != 0)
965  {
966  FileSetSegmentName(segment_name, file->name, i);
967  FileClose(file->files[i]);
968  if (!FileSetDelete(file->fileset, segment_name, true))
969  ereport(ERROR,
971  errmsg("could not delete fileset \"%s\": %m",
972  segment_name)));
973  numFiles--;
974  newOffset = MAX_PHYSICAL_FILESIZE;
975 
976  /*
977  * This is required to indicate that we have deleted the given
978  * fileno.
979  */
980  if (i == fileno)
981  newFile--;
982  }
983  else
984  {
985  if (FileTruncate(file->files[i], offset,
987  ereport(ERROR,
989  errmsg("could not truncate file \"%s\": %m",
990  FilePathName(file->files[i]))));
991  newOffset = offset;
992  }
993  }
994 
995  file->numFiles = numFiles;
996 
997  /*
998  * If the truncate point is within existing buffer then we can just adjust
999  * pos within buffer.
1000  */
1001  if (newFile == file->curFile &&
1002  newOffset >= file->curOffset &&
1003  newOffset <= file->curOffset + file->nbytes)
1004  {
1005  /* No need to reset the current pos if the new pos is greater. */
1006  if (newOffset <= file->curOffset + file->pos)
1007  file->pos = (int) (newOffset - file->curOffset);
1008 
1009  /* Adjust the nbytes for the current buffer. */
1010  file->nbytes = (int) (newOffset - file->curOffset);
1011  }
1012  else if (newFile == file->curFile &&
1013  newOffset < file->curOffset)
1014  {
1015  /*
1016  * The truncate point is within the existing file but prior to the
1017  * current position, so we can forget the current buffer and reset the
1018  * current position.
1019  */
1020  file->curOffset = newOffset;
1021  file->pos = 0;
1022  file->nbytes = 0;
1023  }
1024  else if (newFile < file->curFile)
1025  {
1026  /*
1027  * The truncate point is prior to the current file, so need to reset
1028  * the current position accordingly.
1029  */
1030  file->curFile = newFile;
1031  file->curOffset = newOffset;
1032  file->pos = 0;
1033  file->nbytes = 0;
1034  }
1035  /* Nothing to do, if the truncate point is beyond current file. */
1036 }
void PrepareTempTablespaces(void)
Definition: tablespace.c:1337
void BufFileExportFileSet(BufFile *file)
Definition: buffile.c:389
size_t BufFileRead(BufFile *file, void *ptr, size_t size)
Definition: buffile.c:642
void BufFileReadExact(BufFile *file, void *ptr, size_t size)
Definition: buffile.c:651
static void FileSetSegmentName(char *name, const char *buffile_name, int segment)
Definition: buffile.c:217
long BufFileAppend(BufFile *target, BufFile *source)
Definition: buffile.c:920
BufFile * BufFileOpenFileSet(FileSet *fileset, const char *name, int mode, bool missing_ok)
Definition: buffile.c:286
int BufFileSeekBlock(BufFile *file, long blknum)
Definition: buffile.c:848
static BufFile * makeBufFileCommon(int nfiles)
Definition: buffile.c:113
#define BUFFILE_SEG_SIZE
Definition: buffile.c:63
static void BufFileLoadBuffer(BufFile *file)
Definition: buffile.c:429
static File MakeNewFileSetSegment(BufFile *buffile, int segment)
Definition: buffile.c:226
void BufFileTell(BufFile *file, int *fileno, off_t *offset)
Definition: buffile.c:830
BufFile * BufFileCreateTemp(bool interXact)
Definition: buffile.c:188
static void extendBufFile(BufFile *file)
Definition: buffile.c:151
#define MAX_PHYSICAL_FILESIZE
Definition: buffile.c:62
static void BufFileFlush(BufFile *file)
Definition: buffile.c:717
void BufFileWrite(BufFile *file, const void *ptr, size_t size)
Definition: buffile.c:673
size_t BufFileReadMaybeEOF(BufFile *file, void *ptr, size_t size, bool eofOK)
Definition: buffile.c:661
void BufFileTruncateFileSet(BufFile *file, int fileno, off_t offset)
Definition: buffile.c:948
int BufFileSeek(BufFile *file, int fileno, off_t offset, int whence)
Definition: buffile.c:737
int64 BufFileSize(BufFile *file)
Definition: buffile.c:881
BufFile * BufFileCreateFileSet(FileSet *fileset, const char *name)
Definition: buffile.c:262
static BufFile * makeBufFile(File firstfile)
Definition: buffile.c:134
static size_t BufFileReadCommon(BufFile *file, void *ptr, size_t size, bool exact, bool eofOK)
Definition: buffile.c:590
void BufFileClose(BufFile *file)
Definition: buffile.c:407
void BufFileDeleteFileSet(FileSet *fileset, const char *name, bool missing_ok)
Definition: buffile.c:359
static void BufFileDumpBuffer(BufFile *file)
Definition: buffile.c:490
bool track_io_timing
Definition: bufmgr.c:137
size_t Size
Definition: c.h:589
int errcode_for_file_access(void)
Definition: elog.c:881
int errmsg(const char *fmt,...)
Definition: elog.c:1069
#define ERROR
Definition: elog.h:39
#define ereport(elevel,...)
Definition: elog.h:149
const char * name
Definition: encode.c:571
void FileClose(File file)
Definition: fd.c:1884
int FileWrite(File file, const void *buffer, size_t amount, off_t offset, uint32 wait_event_info)
Definition: fd.c:2091
int FileRead(File file, void *buffer, size_t amount, off_t offset, uint32 wait_event_info)
Definition: fd.c:2035
File OpenTemporaryFile(bool interXact)
Definition: fd.c:1630
char * FilePathName(File file)
Definition: fd.c:2262
off_t FileSize(File file)
Definition: fd.c:2210
int FileTruncate(File file, off_t offset, uint32 wait_event_info)
Definition: fd.c:2227
int File
Definition: fd.h:54
File FileSetOpen(FileSet *fileset, const char *name, int mode)
Definition: fileset.c:121
bool FileSetDelete(FileSet *fileset, const char *name, bool error_on_failure)
Definition: fileset.c:138
File FileSetCreate(FileSet *fileset, const char *name)
Definition: fileset.c:94
#define INSTR_TIME_SET_CURRENT(t)
Definition: instr_time.h:122
#define INSTR_TIME_ADD(x, y)
Definition: instr_time.h:178
#define INSTR_TIME_SUBTRACT(x, y)
Definition: instr_time.h:181
#define INSTR_TIME_SET_ZERO(t)
Definition: instr_time.h:172
BufferUsage pgBufferUsage
Definition: instrument.c:20
int i
Definition: isn.c:73
Assert(fmt[strlen(fmt) - 1] !='\n')
char * pstrdup(const char *in)
Definition: mcxt.c:1624
void pfree(void *pointer)
Definition: mcxt.c:1436
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:1456
void * palloc(Size size)
Definition: mcxt.c:1210
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:121
static PgChecksumMode mode
Definition: pg_checksums.c:65
#define MAXPGPATH
static rewind_source * source
Definition: pg_rewind.c:87
#define snprintf
Definition: port.h:238
ResourceOwner CurrentResourceOwner
Definition: resowner.c:146
int nbytes
Definition: buffile.c:97
PGAlignedBlock buffer
Definition: buffile.c:98
int numFiles
Definition: buffile.c:72
bool dirty
Definition: buffile.c:77
FileSet * fileset
Definition: buffile.c:80
File * files
Definition: buffile.c:74
ResourceOwner resowner
Definition: buffile.c:88
bool isInterXact
Definition: buffile.c:76
bool readOnly
Definition: buffile.c:78
int pos
Definition: buffile.c:96
int curFile
Definition: buffile.c:94
off_t curOffset
Definition: buffile.c:95
const char * name
Definition: buffile.c:81
instr_time temp_blk_write_time
Definition: instrument.h:39
instr_time temp_blk_read_time
Definition: instrument.h:38
int64 temp_blks_read
Definition: instrument.h:34
int64 temp_blks_written
Definition: instrument.h:35
#define wpos(wep)
Definition: tsrank.c:26
char data[BLCKSZ]
Definition: c.h:1130
@ WAIT_EVENT_BUFFILE_WRITE
Definition: wait_event.h:168
@ WAIT_EVENT_BUFFILE_TRUNCATE
Definition: wait_event.h:169
@ WAIT_EVENT_BUFFILE_READ
Definition: wait_event.h:167