]> granicus.if.org Git - postgresql/blob - src/backend/storage/file/buffile.c
efbede76297269947ceeee3ac03b122d9e1e4641
[postgresql] / src / backend / storage / file / buffile.c
1 /*-------------------------------------------------------------------------
2  *
3  * buffile.c
4  *        Management of large buffered temporary files.
5  *
6  * Portions Copyright (c) 1996-2018, 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 made read-only and shared with
36  * other backends, as infrastructure for parallel execution.  Such files need
37  * to be created as a member of a SharedFileSet that all participants are
38  * attached to.
39  *-------------------------------------------------------------------------
40  */
41
42 #include "postgres.h"
43
44 #include "executor/instrument.h"
45 #include "miscadmin.h"
46 #include "pgstat.h"
47 #include "storage/fd.h"
48 #include "storage/buffile.h"
49 #include "storage/buf_internals.h"
50 #include "utils/resowner.h"
51
52 /*
53  * We break BufFiles into gigabyte-sized segments, regardless of RELSEG_SIZE.
54  * The reason is that we'd like large BufFiles to be spread across multiple
55  * tablespaces when available.
56  */
57 #define MAX_PHYSICAL_FILESIZE   0x40000000
58 #define BUFFILE_SEG_SIZE                (MAX_PHYSICAL_FILESIZE / BLCKSZ)
59
60 /*
61  * This data structure represents a buffered file that consists of one or
62  * more physical files (each accessed through a virtual file descriptor
63  * managed by fd.c).
64  */
65 struct BufFile
66 {
67         int                     numFiles;               /* number of physical files in set */
68         /* all files except the last have length exactly MAX_PHYSICAL_FILESIZE */
69         File       *files;                      /* palloc'd array with numFiles entries */
70         off_t      *offsets;            /* palloc'd array with numFiles entries */
71
72         /*
73          * offsets[i] is the current seek position of files[i].  We use this to
74          * avoid making redundant FileSeek calls.
75          */
76
77         bool            isInterXact;    /* keep open over transactions? */
78         bool            dirty;                  /* does buffer need to be written? */
79         bool            readOnly;               /* has the file been set to read only? */
80
81         SharedFileSet *fileset;         /* space for segment files if shared */
82         const char *name;                       /* name of this BufFile if shared */
83
84         /*
85          * resowner is the ResourceOwner to use for underlying temp files.  (We
86          * don't need to remember the memory context we're using explicitly,
87          * because after creation we only repalloc our arrays larger.)
88          */
89         ResourceOwner resowner;
90
91         /*
92          * "current pos" is position of start of buffer within the logical file.
93          * Position as seen by user of BufFile is (curFile, curOffset + pos).
94          */
95         int                     curFile;                /* file index (0..n) part of current pos */
96         off_t           curOffset;              /* offset part of current pos */
97         int                     pos;                    /* next read/write position in buffer */
98         int                     nbytes;                 /* total # of valid bytes in buffer */
99         char            buffer[BLCKSZ];
100 };
101
102 static BufFile *makeBufFileCommon(int nfiles);
103 static BufFile *makeBufFile(File firstfile);
104 static void extendBufFile(BufFile *file);
105 static void BufFileLoadBuffer(BufFile *file);
106 static void BufFileDumpBuffer(BufFile *file);
107 static int      BufFileFlush(BufFile *file);
108 static File MakeNewSharedSegment(BufFile *file, int segment);
109
110 /*
111  * Create BufFile and perform the common initialization.
112  */
113 static BufFile *
114 makeBufFileCommon(int nfiles)
115 {
116         BufFile    *file = (BufFile *) palloc(sizeof(BufFile));
117
118         file->numFiles = nfiles;
119         file->offsets = (off_t *) palloc0(sizeof(off_t) * nfiles);
120         file->isInterXact = false;
121         file->dirty = false;
122         file->resowner = CurrentResourceOwner;
123         file->curFile = 0;
124         file->curOffset = 0L;
125         file->pos = 0;
126         file->nbytes = 0;
127
128         return file;
129 }
130
131 /*
132  * Create a BufFile given the first underlying physical file.
133  * NOTE: caller must set isInterXact if appropriate.
134  */
135 static BufFile *
136 makeBufFile(File firstfile)
137 {
138         BufFile    *file = makeBufFileCommon(1);
139
140         file->files = (File *) palloc(sizeof(File));
141         file->files[0] = firstfile;
142         file->readOnly = false;
143         file->fileset = NULL;
144         file->name = NULL;
145
146         return file;
147 }
148
149 /*
150  * Add another component temp file.
151  */
152 static void
153 extendBufFile(BufFile *file)
154 {
155         File            pfile;
156         ResourceOwner oldowner;
157
158         /* Be sure to associate the file with the BufFile's resource owner */
159         oldowner = CurrentResourceOwner;
160         CurrentResourceOwner = file->resowner;
161
162         if (file->fileset == NULL)
163                 pfile = OpenTemporaryFile(file->isInterXact);
164         else
165                 pfile = MakeNewSharedSegment(file, file->numFiles);
166
167         Assert(pfile >= 0);
168
169         CurrentResourceOwner = oldowner;
170
171         file->files = (File *) repalloc(file->files,
172                                                                         (file->numFiles + 1) * sizeof(File));
173         file->offsets = (off_t *) repalloc(file->offsets,
174                                                                            (file->numFiles + 1) * sizeof(off_t));
175         file->files[file->numFiles] = pfile;
176         file->offsets[file->numFiles] = 0L;
177         file->numFiles++;
178 }
179
180 /*
181  * Create a BufFile for a new temporary file (which will expand to become
182  * multiple temporary files if more than MAX_PHYSICAL_FILESIZE bytes are
183  * written to it).
184  *
185  * If interXact is true, the temp file will not be automatically deleted
186  * at end of transaction.
187  *
188  * Note: if interXact is true, the caller had better be calling us in a
189  * memory context, and with a resource owner, that will survive across
190  * transaction boundaries.
191  */
192 BufFile *
193 BufFileCreateTemp(bool interXact)
194 {
195         BufFile    *file;
196         File            pfile;
197
198         pfile = OpenTemporaryFile(interXact);
199         Assert(pfile >= 0);
200
201         file = makeBufFile(pfile);
202         file->isInterXact = interXact;
203
204         return file;
205 }
206
207 /*
208  * Build the name for a given segment of a given BufFile.
209  */
210 static void
211 SharedSegmentName(char *name, const char *buffile_name, int segment)
212 {
213         snprintf(name, MAXPGPATH, "%s.%d", buffile_name, segment);
214 }
215
216 /*
217  * Create a new segment file backing a shared BufFile.
218  */
219 static File
220 MakeNewSharedSegment(BufFile *buffile, int segment)
221 {
222         char            name[MAXPGPATH];
223         File            file;
224
225         /*
226          * It is possible that there are files left over from before a crash
227          * restart with the same name.  In order for BufFileOpenShared() not to
228          * get confused about how many segments there are, we'll unlink the next
229          * segment number if it already exists.
230          */
231         SharedSegmentName(name, buffile->name, segment + 1);
232         SharedFileSetDelete(buffile->fileset, name, true);
233
234         /* Create the new segment. */
235         SharedSegmentName(name, buffile->name, segment);
236         file = SharedFileSetCreate(buffile->fileset, name);
237
238         /* SharedFileSetCreate would've errored out */
239         Assert(file > 0);
240
241         return file;
242 }
243
244 /*
245  * Create a BufFile that can be discovered and opened read-only by other
246  * backends that are attached to the same SharedFileSet using the same name.
247  *
248  * The naming scheme for shared BufFiles is left up to the calling code.  The
249  * name will appear as part of one or more filenames on disk, and might
250  * provide clues to administrators about which subsystem is generating
251  * temporary file data.  Since each SharedFileSet object is backed by one or
252  * more uniquely named temporary directory, names don't conflict with
253  * unrelated SharedFileSet objects.
254  */
255 BufFile *
256 BufFileCreateShared(SharedFileSet *fileset, const char *name)
257 {
258         BufFile    *file;
259
260         file = makeBufFileCommon(1);
261         file->fileset = fileset;
262         file->name = pstrdup(name);
263         file->files = (File *) palloc(sizeof(File));
264         file->files[0] = MakeNewSharedSegment(file, 0);
265         file->readOnly = false;
266
267         return file;
268 }
269
270 /*
271  * Open a file that was previously created in another backend (or this one)
272  * with BufFileCreateShared in the same SharedFileSet using the same name.
273  * The backend that created the file must have called BufFileClose() or
274  * BufFileExportShared() to make sure that it is ready to be opened by other
275  * backends and render it read-only.
276  */
277 BufFile *
278 BufFileOpenShared(SharedFileSet *fileset, const char *name)
279 {
280         BufFile    *file;
281         char            segment_name[MAXPGPATH];
282         Size            capacity = 16;
283         File       *files;
284         int                     nfiles = 0;
285
286         files = palloc(sizeof(File) * capacity);
287
288         /*
289          * We don't know how many segments there are, so we'll probe the
290          * filesystem to find out.
291          */
292         for (;;)
293         {
294                 /* See if we need to expand our file segment array. */
295                 if (nfiles + 1 > capacity)
296                 {
297                         capacity *= 2;
298                         files = repalloc(files, sizeof(File) * capacity);
299                 }
300                 /* Try to load a segment. */
301                 SharedSegmentName(segment_name, name, nfiles);
302                 files[nfiles] = SharedFileSetOpen(fileset, segment_name);
303                 if (files[nfiles] <= 0)
304                         break;
305                 ++nfiles;
306
307                 CHECK_FOR_INTERRUPTS();
308         }
309
310         /*
311          * If we didn't find any files at all, then no BufFile exists with this
312          * name.
313          */
314         if (nfiles == 0)
315                 ereport(ERROR,
316                                 (errcode_for_file_access(),
317                                  errmsg("could not open BufFile \"%s\"", name)));
318
319         file = makeBufFileCommon(nfiles);
320         file->files = files;
321         file->readOnly = true;          /* Can't write to files opened this way */
322         file->fileset = fileset;
323         file->name = pstrdup(name);
324
325         return file;
326 }
327
328 /*
329  * Delete a BufFile that was created by BufFileCreateShared in the given
330  * SharedFileSet using the given name.
331  *
332  * It is not necessary to delete files explicitly with this function.  It is
333  * provided only as a way to delete files proactively, rather than waiting for
334  * the SharedFileSet to be cleaned up.
335  *
336  * Only one backend should attempt to delete a given name, and should know
337  * that it exists and has been exported or closed.
338  */
339 void
340 BufFileDeleteShared(SharedFileSet *fileset, const char *name)
341 {
342         char            segment_name[MAXPGPATH];
343         int                     segment = 0;
344         bool            found = false;
345
346         /*
347          * We don't know how many segments the file has.  We'll keep deleting
348          * until we run out.  If we don't manage to find even an initial segment,
349          * raise an error.
350          */
351         for (;;)
352         {
353                 SharedSegmentName(segment_name, name, segment);
354                 if (!SharedFileSetDelete(fileset, segment_name, true))
355                         break;
356                 found = true;
357                 ++segment;
358
359                 CHECK_FOR_INTERRUPTS();
360         }
361
362         if (!found)
363                 elog(ERROR, "could not delete unknown shared BufFile \"%s\"", name);
364 }
365
366 /*
367  * BufFileExportShared --- flush and make read-only, in preparation for sharing.
368  */
369 void
370 BufFileExportShared(BufFile *file)
371 {
372         /* Must be a file belonging to a SharedFileSet. */
373         Assert(file->fileset != NULL);
374
375         /* It's probably a bug if someone calls this twice. */
376         Assert(!file->readOnly);
377
378         BufFileFlush(file);
379         file->readOnly = true;
380 }
381
382 /*
383  * Close a BufFile
384  *
385  * Like fclose(), this also implicitly FileCloses the underlying File.
386  */
387 void
388 BufFileClose(BufFile *file)
389 {
390         int                     i;
391
392         /* flush any unwritten data */
393         BufFileFlush(file);
394         /* close and delete the underlying file(s) */
395         for (i = 0; i < file->numFiles; i++)
396                 FileClose(file->files[i]);
397         /* release the buffer space */
398         pfree(file->files);
399         pfree(file->offsets);
400         pfree(file);
401 }
402
403 /*
404  * BufFileLoadBuffer
405  *
406  * Load some data into buffer, if possible, starting from curOffset.
407  * At call, must have dirty = false, pos and nbytes = 0.
408  * On exit, nbytes is number of bytes loaded.
409  */
410 static void
411 BufFileLoadBuffer(BufFile *file)
412 {
413         File            thisfile;
414
415         /*
416          * Advance to next component file if necessary and possible.
417          */
418         if (file->curOffset >= MAX_PHYSICAL_FILESIZE &&
419                 file->curFile + 1 < file->numFiles)
420         {
421                 file->curFile++;
422                 file->curOffset = 0L;
423         }
424
425         /*
426          * May need to reposition physical file.
427          */
428         thisfile = file->files[file->curFile];
429         if (file->curOffset != file->offsets[file->curFile])
430         {
431                 if (FileSeek(thisfile, file->curOffset, SEEK_SET) != file->curOffset)
432                         return;                         /* seek failed, read nothing */
433                 file->offsets[file->curFile] = file->curOffset;
434         }
435
436         /*
437          * Read whatever we can get, up to a full bufferload.
438          */
439         file->nbytes = FileRead(thisfile,
440                                                         file->buffer,
441                                                         sizeof(file->buffer),
442                                                         WAIT_EVENT_BUFFILE_READ);
443         if (file->nbytes < 0)
444                 file->nbytes = 0;
445         file->offsets[file->curFile] += file->nbytes;
446         /* we choose not to advance curOffset here */
447
448         if (file->nbytes > 0)
449                 pgBufferUsage.temp_blks_read++;
450 }
451
452 /*
453  * BufFileDumpBuffer
454  *
455  * Dump buffer contents starting at curOffset.
456  * At call, should have dirty = true, nbytes > 0.
457  * On exit, dirty is cleared if successful write, and curOffset is advanced.
458  */
459 static void
460 BufFileDumpBuffer(BufFile *file)
461 {
462         int                     wpos = 0;
463         int                     bytestowrite;
464         File            thisfile;
465
466         /*
467          * Unlike BufFileLoadBuffer, we must dump the whole buffer even if it
468          * crosses a component-file boundary; so we need a loop.
469          */
470         while (wpos < file->nbytes)
471         {
472                 off_t           availbytes;
473
474                 /*
475                  * Advance to next component file if necessary and possible.
476                  */
477                 if (file->curOffset >= MAX_PHYSICAL_FILESIZE)
478                 {
479                         while (file->curFile + 1 >= file->numFiles)
480                                 extendBufFile(file);
481                         file->curFile++;
482                         file->curOffset = 0L;
483                 }
484
485                 /*
486                  * Determine how much we need to write into this file.
487                  */
488                 bytestowrite = file->nbytes - wpos;
489                 availbytes = MAX_PHYSICAL_FILESIZE - file->curOffset;
490
491                 if ((off_t) bytestowrite > availbytes)
492                         bytestowrite = (int) availbytes;
493
494                 /*
495                  * May need to reposition physical file.
496                  */
497                 thisfile = file->files[file->curFile];
498                 if (file->curOffset != file->offsets[file->curFile])
499                 {
500                         if (FileSeek(thisfile, file->curOffset, SEEK_SET) != file->curOffset)
501                                 return;                 /* seek failed, give up */
502                         file->offsets[file->curFile] = file->curOffset;
503                 }
504                 bytestowrite = FileWrite(thisfile,
505                                                                  file->buffer + wpos,
506                                                                  bytestowrite,
507                                                                  WAIT_EVENT_BUFFILE_WRITE);
508                 if (bytestowrite <= 0)
509                         return;                         /* failed to write */
510                 file->offsets[file->curFile] += bytestowrite;
511                 file->curOffset += bytestowrite;
512                 wpos += bytestowrite;
513
514                 pgBufferUsage.temp_blks_written++;
515         }
516         file->dirty = false;
517
518         /*
519          * At this point, curOffset has been advanced to the end of the buffer,
520          * ie, its original value + nbytes.  We need to make it point to the
521          * logical file position, ie, original value + pos, in case that is less
522          * (as could happen due to a small backwards seek in a dirty buffer!)
523          */
524         file->curOffset -= (file->nbytes - file->pos);
525         if (file->curOffset < 0)        /* handle possible segment crossing */
526         {
527                 file->curFile--;
528                 Assert(file->curFile >= 0);
529                 file->curOffset += MAX_PHYSICAL_FILESIZE;
530         }
531
532         /*
533          * Now we can set the buffer empty without changing the logical position
534          */
535         file->pos = 0;
536         file->nbytes = 0;
537 }
538
539 /*
540  * BufFileRead
541  *
542  * Like fread() except we assume 1-byte element size.
543  */
544 size_t
545 BufFileRead(BufFile *file, void *ptr, size_t size)
546 {
547         size_t          nread = 0;
548         size_t          nthistime;
549
550         if (file->dirty)
551         {
552                 if (BufFileFlush(file) != 0)
553                         return 0;                       /* could not flush... */
554                 Assert(!file->dirty);
555         }
556
557         while (size > 0)
558         {
559                 if (file->pos >= file->nbytes)
560                 {
561                         /* Try to load more data into buffer. */
562                         file->curOffset += file->pos;
563                         file->pos = 0;
564                         file->nbytes = 0;
565                         BufFileLoadBuffer(file);
566                         if (file->nbytes <= 0)
567                                 break;                  /* no more data available */
568                 }
569
570                 nthistime = file->nbytes - file->pos;
571                 if (nthistime > size)
572                         nthistime = size;
573                 Assert(nthistime > 0);
574
575                 memcpy(ptr, file->buffer + file->pos, nthistime);
576
577                 file->pos += nthistime;
578                 ptr = (void *) ((char *) ptr + nthistime);
579                 size -= nthistime;
580                 nread += nthistime;
581         }
582
583         return nread;
584 }
585
586 /*
587  * BufFileWrite
588  *
589  * Like fwrite() except we assume 1-byte element size.
590  */
591 size_t
592 BufFileWrite(BufFile *file, void *ptr, size_t size)
593 {
594         size_t          nwritten = 0;
595         size_t          nthistime;
596
597         Assert(!file->readOnly);
598
599         while (size > 0)
600         {
601                 if (file->pos >= BLCKSZ)
602                 {
603                         /* Buffer full, dump it out */
604                         if (file->dirty)
605                         {
606                                 BufFileDumpBuffer(file);
607                                 if (file->dirty)
608                                         break;          /* I/O error */
609                         }
610                         else
611                         {
612                                 /* Hmm, went directly from reading to writing? */
613                                 file->curOffset += file->pos;
614                                 file->pos = 0;
615                                 file->nbytes = 0;
616                         }
617                 }
618
619                 nthistime = BLCKSZ - file->pos;
620                 if (nthistime > size)
621                         nthistime = size;
622                 Assert(nthistime > 0);
623
624                 memcpy(file->buffer + file->pos, ptr, nthistime);
625
626                 file->dirty = true;
627                 file->pos += nthistime;
628                 if (file->nbytes < file->pos)
629                         file->nbytes = file->pos;
630                 ptr = (void *) ((char *) ptr + nthistime);
631                 size -= nthistime;
632                 nwritten += nthistime;
633         }
634
635         return nwritten;
636 }
637
638 /*
639  * BufFileFlush
640  *
641  * Like fflush()
642  */
643 static int
644 BufFileFlush(BufFile *file)
645 {
646         if (file->dirty)
647         {
648                 BufFileDumpBuffer(file);
649                 if (file->dirty)
650                         return EOF;
651         }
652
653         return 0;
654 }
655
656 /*
657  * BufFileSeek
658  *
659  * Like fseek(), except that target position needs two values in order to
660  * work when logical filesize exceeds maximum value representable by off_t.
661  * We do not support relative seeks across more than that, however.
662  *
663  * Result is 0 if OK, EOF if not.  Logical position is not moved if an
664  * impossible seek is attempted.
665  */
666 int
667 BufFileSeek(BufFile *file, int fileno, off_t offset, int whence)
668 {
669         int                     newFile;
670         off_t           newOffset;
671
672         switch (whence)
673         {
674                 case SEEK_SET:
675                         if (fileno < 0)
676                                 return EOF;
677                         newFile = fileno;
678                         newOffset = offset;
679                         break;
680                 case SEEK_CUR:
681
682                         /*
683                          * Relative seek considers only the signed offset, ignoring
684                          * fileno. Note that large offsets (> 1 gig) risk overflow in this
685                          * add, unless we have 64-bit off_t.
686                          */
687                         newFile = file->curFile;
688                         newOffset = (file->curOffset + file->pos) + offset;
689                         break;
690 #ifdef NOT_USED
691                 case SEEK_END:
692                         /* could be implemented, not needed currently */
693                         break;
694 #endif
695                 default:
696                         elog(ERROR, "invalid whence: %d", whence);
697                         return EOF;
698         }
699         while (newOffset < 0)
700         {
701                 if (--newFile < 0)
702                         return EOF;
703                 newOffset += MAX_PHYSICAL_FILESIZE;
704         }
705         if (newFile == file->curFile &&
706                 newOffset >= file->curOffset &&
707                 newOffset <= file->curOffset + file->nbytes)
708         {
709                 /*
710                  * Seek is to a point within existing buffer; we can just adjust
711                  * pos-within-buffer, without flushing buffer.  Note this is OK
712                  * whether reading or writing, but buffer remains dirty if we were
713                  * writing.
714                  */
715                 file->pos = (int) (newOffset - file->curOffset);
716                 return 0;
717         }
718         /* Otherwise, must reposition buffer, so flush any dirty data */
719         if (BufFileFlush(file) != 0)
720                 return EOF;
721
722         /*
723          * At this point and no sooner, check for seek past last segment. The
724          * above flush could have created a new segment, so checking sooner would
725          * not work (at least not with this code).
726          */
727
728         /* convert seek to "start of next seg" to "end of last seg" */
729         if (newFile == file->numFiles && newOffset == 0)
730         {
731                 newFile--;
732                 newOffset = MAX_PHYSICAL_FILESIZE;
733         }
734         while (newOffset > MAX_PHYSICAL_FILESIZE)
735         {
736                 if (++newFile >= file->numFiles)
737                         return EOF;
738                 newOffset -= MAX_PHYSICAL_FILESIZE;
739         }
740         if (newFile >= file->numFiles)
741                 return EOF;
742         /* Seek is OK! */
743         file->curFile = newFile;
744         file->curOffset = newOffset;
745         file->pos = 0;
746         file->nbytes = 0;
747         return 0;
748 }
749
750 void
751 BufFileTell(BufFile *file, int *fileno, off_t *offset)
752 {
753         *fileno = file->curFile;
754         *offset = file->curOffset + file->pos;
755 }
756
757 /*
758  * BufFileSeekBlock --- block-oriented seek
759  *
760  * Performs absolute seek to the start of the n'th BLCKSZ-sized block of
761  * the file.  Note that users of this interface will fail if their files
762  * exceed BLCKSZ * LONG_MAX bytes, but that is quite a lot; we don't work
763  * with tables bigger than that, either...
764  *
765  * Result is 0 if OK, EOF if not.  Logical position is not moved if an
766  * impossible seek is attempted.
767  */
768 int
769 BufFileSeekBlock(BufFile *file, long blknum)
770 {
771         return BufFileSeek(file,
772                                            (int) (blknum / BUFFILE_SEG_SIZE),
773                                            (off_t) (blknum % BUFFILE_SEG_SIZE) * BLCKSZ,
774                                            SEEK_SET);
775 }
776
777 #ifdef NOT_USED
778 /*
779  * BufFileTellBlock --- block-oriented tell
780  *
781  * Any fractional part of a block in the current seek position is ignored.
782  */
783 long
784 BufFileTellBlock(BufFile *file)
785 {
786         long            blknum;
787
788         blknum = (file->curOffset + file->pos) / BLCKSZ;
789         blknum += file->curFile * BUFFILE_SEG_SIZE;
790         return blknum;
791 }
792
793 #endif
794
795 /*
796  * Return the current file size.
797  *
798  * Counts any holes left behind by BufFileAppend as part of the size.
799  * Returns -1 on error.
800  */
801 off_t
802 BufFileSize(BufFile *file)
803 {
804         off_t           lastFileSize;
805
806         /* Get the size of the last physical file by seeking to end. */
807         lastFileSize = FileSeek(file->files[file->numFiles - 1], 0, SEEK_END);
808         if (lastFileSize < 0)
809                 return -1;
810         file->offsets[file->numFiles - 1] = lastFileSize;
811
812         return ((file->numFiles - 1) * (off_t) MAX_PHYSICAL_FILESIZE) +
813                 lastFileSize;
814 }
815
816 /*
817  * Append the contents of source file (managed within shared fileset) to
818  * end of target file (managed within same shared fileset).
819  *
820  * Note that operation subsumes ownership of underlying resources from
821  * "source".  Caller should never call BufFileClose against source having
822  * called here first.  Resource owners for source and target must match,
823  * too.
824  *
825  * This operation works by manipulating lists of segment files, so the
826  * file content is always appended at a MAX_PHYSICAL_FILESIZE-aligned
827  * boundary, typically creating empty holes before the boundary.  These
828  * areas do not contain any interesting data, and cannot be read from by
829  * caller.
830  *
831  * Returns the block number within target where the contents of source
832  * begins.  Caller should apply this as an offset when working off block
833  * positions that are in terms of the original BufFile space.
834  */
835 long
836 BufFileAppend(BufFile *target, BufFile *source)
837 {
838         long            startBlock = target->numFiles * BUFFILE_SEG_SIZE;
839         int                     newNumFiles = target->numFiles + source->numFiles;
840         int                     i;
841
842         Assert(target->fileset != NULL);
843         Assert(source->readOnly);
844         Assert(!source->dirty);
845         Assert(source->fileset != NULL);
846
847         if (target->resowner != source->resowner)
848                 elog(ERROR, "could not append BufFile with non-matching resource owner");
849
850         target->files = (File *)
851                 repalloc(target->files, sizeof(File) * newNumFiles);
852         target->offsets = (off_t *)
853                 repalloc(target->offsets, sizeof(off_t) * newNumFiles);
854         for (i = target->numFiles; i < newNumFiles; i++)
855         {
856                 target->files[i] = source->files[i - target->numFiles];
857                 target->offsets[i] = source->offsets[i - target->numFiles];
858         }
859         target->numFiles = newNumFiles;
860
861         return startBlock;
862 }