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