buffile.c 14.5 KB
Newer Older
1 2 3 4 5
/*-------------------------------------------------------------------------
 *
 * buffile.c
 *	  Management of large buffered files, primarily temporary files.
 *
6
 * Portions Copyright (c) 1996-2008, PostgreSQL Global Development Group
Bruce Momjian's avatar
Add:  
Bruce Momjian committed
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.31 2008/05/02 01:08:27 tgl Exp $
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
 *
 * NOTES:
 *
 * BufFiles provide a very incomplete emulation of stdio atop virtual Files
 * (as managed by fd.c).  Currently, we only support the buffered-I/O
 * aspect of stdio: a read or write of the low-level File occurs only
 * when the buffer is filled or emptied.  This is an even bigger win
 * for virtual Files than for ordinary kernel files, since reducing the
 * frequency with which a virtual File is touched reduces "thrashing"
 * of opening/closing file descriptors.
 *
 * Note that BufFile structs are allocated with palloc(), and therefore
 * will go away automatically at transaction end.  If the underlying
 * virtual File is made with OpenTemporaryFile, then all resources for
 * 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 28 29
 * all calls for a single BufFile are made in the same palloc context.
 *
 * 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 36
 *-------------------------------------------------------------------------
 */

#include "postgres.h"

Bruce Momjian's avatar
Bruce Momjian committed
37
#include "storage/fd.h"
38 39 40
#include "storage/buffile.h"

/*
41 42 43
 * We break BufFiles into gigabyte-sized segments, regardless of RELSEG_SIZE.
 * The reason is that we'd like large temporary BufFiles to be spread across
 * multiple tablespaces when available.
44
 */
45 46
#define MAX_PHYSICAL_FILESIZE	0x40000000
#define BUFFILE_SEG_SIZE		(MAX_PHYSICAL_FILESIZE / BLCKSZ)
47 48

/*
49 50 51
 * This data structure represents a buffered file that consists of one or
 * more physical files (each accessed through a virtual file descriptor
 * managed by fd.c).
52
 */
53
struct BufFile
54 55 56 57
{
	int			numFiles;		/* number of physical files in set */
	/* all files except the last have length exactly MAX_PHYSICAL_FILESIZE */
	File	   *files;			/* palloc'd array with numFiles entries */
58
	off_t	   *offsets;		/* palloc'd array with numFiles entries */
59 60

	/*
61 62
	 * offsets[i] is the current seek position of files[i].  We use this to
	 * avoid making redundant FileSeek calls.
63 64
	 */

65
	bool		isTemp;			/* can only add files if this is TRUE */
66
	bool		isInterXact;	/* keep open over transactions? */
67
	bool		dirty;			/* does buffer need to be written? */
68

69
	/*
70 71
	 * "current pos" is position of start of buffer within the logical file.
	 * Position as seen by user of BufFile is (curFile, curOffset + pos).
72 73
	 */
	int			curFile;		/* file index (0..n) part of current pos */
74
	off_t		curOffset;		/* offset part of current pos */
75 76 77 78 79
	int			pos;			/* next read/write position in buffer */
	int			nbytes;			/* total # of valid bytes in buffer */
	char		buffer[BLCKSZ];
};

80 81
static BufFile *makeBufFile(File firstfile);
static void extendBufFile(BufFile *file);
82 83 84 85 86 87
static void BufFileLoadBuffer(BufFile *file);
static void BufFileDumpBuffer(BufFile *file);
static int	BufFileFlush(BufFile *file);


/*
88
 * Create a BufFile given the first underlying physical file.
89
 * NOTE: caller must set isTemp and isInterXact if appropriate.
90
 */
91 92
static BufFile *
makeBufFile(File firstfile)
93
{
94
	BufFile    *file = (BufFile *) palloc(sizeof(BufFile));
95 96 97 98

	file->numFiles = 1;
	file->files = (File *) palloc(sizeof(File));
	file->files[0] = firstfile;
99
	file->offsets = (off_t *) palloc(sizeof(off_t));
100
	file->offsets[0] = 0L;
101
	file->isTemp = false;
102
	file->isInterXact = false;
103 104 105 106 107
	file->dirty = false;
	file->curFile = 0;
	file->curOffset = 0L;
	file->pos = 0;
	file->nbytes = 0;
108 109 110 111 112 113 114 115

	return file;
}

/*
 * Add another component temp file.
 */
static void
116
extendBufFile(BufFile *file)
117 118 119 120
{
	File		pfile;

	Assert(file->isTemp);
121
	pfile = OpenTemporaryFile(file->isInterXact);
122 123 124
	Assert(pfile >= 0);

	file->files = (File *) repalloc(file->files,
125
									(file->numFiles + 1) * sizeof(File));
126 127
	file->offsets = (off_t *) repalloc(file->offsets,
									  (file->numFiles + 1) * sizeof(off_t));
128 129 130 131 132 133 134 135 136
	file->files[file->numFiles] = pfile;
	file->offsets[file->numFiles] = 0L;
	file->numFiles++;
}

/*
 * Create a BufFile for a new temporary file (which will expand to become
 * multiple temporary files if more than MAX_PHYSICAL_FILESIZE bytes are
 * written to it).
137
 *
138
 * If interXact is true, the temp file will not be automatically deleted
139
 * at end of transaction.
140
 *
141 142
 * Note: if interXact is true, the caller had better be calling us in a
 * memory context that will survive across transaction boundaries.
143
 */
144
BufFile *
145
BufFileCreateTemp(bool interXact)
146
{
147
	BufFile    *file;
148 149
	File		pfile;

150
	pfile = OpenTemporaryFile(interXact);
151 152
	Assert(pfile >= 0);

153 154
	file = makeBufFile(pfile);
	file->isTemp = true;
155
	file->isInterXact = interXact;
156

157
	return file;
158 159
}

160
#ifdef NOT_USED
161 162 163 164 165 166 167
/*
 * Create a BufFile and attach it to an already-opened virtual File.
 *
 * This is comparable to fdopen() in stdio.  This is the only way at present
 * to attach a BufFile to a non-temporary file.  Note that BufFiles created
 * in this way CANNOT be expanded into multiple files.
 */
168
BufFile *
169 170
BufFileCreate(File file)
{
171
	return makeBufFile(file);
172
}
173
#endif
174 175 176 177 178 179 180 181 182

/*
 * Close a BufFile
 *
 * Like fclose(), this also implicitly FileCloses the underlying File.
 */
void
BufFileClose(BufFile *file)
{
183
	int			i;
184

185 186
	/* flush any unwritten data */
	BufFileFlush(file);
187 188 189
	/* close the underlying file(s) (with delete if it's a temp file) */
	for (i = 0; i < file->numFiles; i++)
		FileClose(file->files[i]);
190
	/* release the buffer space */
191 192
	pfree(file->files);
	pfree(file->offsets);
193 194 195
	pfree(file);
}

196 197
/*
 * BufFileLoadBuffer
198 199 200 201 202 203 204 205
 *
 * Load some data into buffer, if possible, starting from curOffset.
 * At call, must have dirty = false, pos and nbytes = 0.
 * On exit, nbytes is number of bytes loaded.
 */
static void
BufFileLoadBuffer(BufFile *file)
{
206
	File		thisfile;
207 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
	 * won't interfere with reading a non-temp file that is over
213 214 215
	 * MAX_PHYSICAL_FILESIZE.
	 */
	if (file->curOffset >= MAX_PHYSICAL_FILESIZE &&
216
		file->curFile + 1 < file->numFiles)
217 218 219 220
	{
		file->curFile++;
		file->curOffset = 0L;
	}
221

222
	/*
223
	 * May need to reposition physical file.
224
	 */
225 226
	thisfile = file->files[file->curFile];
	if (file->curOffset != file->offsets[file->curFile])
227 228 229
	{
		if (FileSeek(thisfile, file->curOffset, SEEK_SET) != file->curOffset)
			return;				/* seek failed, read nothing */
230
		file->offsets[file->curFile] = file->curOffset;
231
	}
232

233 234 235
	/*
	 * Read whatever we can get, up to a full bufferload.
	 */
236 237 238
	file->nbytes = FileRead(thisfile, file->buffer, sizeof(file->buffer));
	if (file->nbytes < 0)
		file->nbytes = 0;
239
	file->offsets[file->curFile] += file->nbytes;
240 241 242
	/* we choose not to advance curOffset here */
}

243 244
/*
 * BufFileDumpBuffer
245 246 247 248 249 250 251 252 253 254 255 256 257
 *
 * Dump buffer contents starting at curOffset.
 * At call, should have dirty = true, nbytes > 0.
 * On exit, dirty is cleared if successful write, and curOffset is advanced.
 */
static void
BufFileDumpBuffer(BufFile *file)
{
	int			wpos = 0;
	int			bytestowrite;
	File		thisfile;

	/*
258 259
	 * Unlike BufFileLoadBuffer, we must dump the whole buffer even if it
	 * crosses a component-file boundary; so we need a loop.
260 261 262 263 264 265
	 */
	while (wpos < file->nbytes)
	{
		/*
		 * Advance to next component file if necessary and possible.
		 */
266
		if (file->curOffset >= MAX_PHYSICAL_FILESIZE && file->isTemp)
267
		{
268
			while (file->curFile + 1 >= file->numFiles)
269
				extendBufFile(file);
270 271 272
			file->curFile++;
			file->curOffset = 0L;
		}
273

274
		/*
275 276
		 * Enforce per-file size limit only for temp files, else just try to
		 * write as much as asked...
277 278
		 */
		bytestowrite = file->nbytes - wpos;
279
		if (file->isTemp)
280
		{
281
			off_t		availbytes = MAX_PHYSICAL_FILESIZE - file->curOffset;
282

283
			if ((off_t) bytestowrite > availbytes)
284 285
				bytestowrite = (int) availbytes;
		}
286

287
		/*
288
		 * May need to reposition physical file.
289
		 */
290 291
		thisfile = file->files[file->curFile];
		if (file->curOffset != file->offsets[file->curFile])
292 293 294
		{
			if (FileSeek(thisfile, file->curOffset, SEEK_SET) != file->curOffset)
				return;			/* seek failed, give up */
295
			file->offsets[file->curFile] = file->curOffset;
296
		}
297
		bytestowrite = FileWrite(thisfile, file->buffer + wpos, bytestowrite);
298 299
		if (bytestowrite <= 0)
			return;				/* failed to write */
300
		file->offsets[file->curFile] += bytestowrite;
301 302 303 304
		file->curOffset += bytestowrite;
		wpos += bytestowrite;
	}
	file->dirty = false;
305

306
	/*
307 308 309 310
	 * At this point, curOffset has been advanced to the end of the buffer,
	 * ie, its original value + nbytes.  We need to make it point to the
	 * logical file position, ie, original value + pos, in case that is less
	 * (as could happen due to a small backwards seek in a dirty buffer!)
311 312 313 314 315 316 317 318
	 */
	file->curOffset -= (file->nbytes - file->pos);
	if (file->curOffset < 0)	/* handle possible segment crossing */
	{
		file->curFile--;
		Assert(file->curFile >= 0);
		file->curOffset += MAX_PHYSICAL_FILESIZE;
	}
319 320

	/*
321
	 * Now we can set the buffer empty without changing the logical position
322
	 */
323 324 325 326
	file->pos = 0;
	file->nbytes = 0;
}

327 328
/*
 * BufFileRead
329 330 331 332 333 334 335 336 337 338 339 340 341
 *
 * Like fread() except we assume 1-byte element size.
 */
size_t
BufFileRead(BufFile *file, void *ptr, size_t size)
{
	size_t		nread = 0;
	size_t		nthistime;

	if (file->dirty)
	{
		if (BufFileFlush(file) != 0)
			return 0;			/* could not flush... */
342
		Assert(!file->dirty);
343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373
	}

	while (size > 0)
	{
		if (file->pos >= file->nbytes)
		{
			/* Try to load more data into buffer. */
			file->curOffset += file->pos;
			file->pos = 0;
			file->nbytes = 0;
			BufFileLoadBuffer(file);
			if (file->nbytes <= 0)
				break;			/* no more data available */
		}

		nthistime = file->nbytes - file->pos;
		if (nthistime > size)
			nthistime = size;
		Assert(nthistime > 0);

		memcpy(ptr, file->buffer + file->pos, nthistime);

		file->pos += nthistime;
		ptr = (void *) ((char *) ptr + nthistime);
		size -= nthistime;
		nread += nthistime;
	}

	return nread;
}

374 375
/*
 * BufFileWrite
376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423
 *
 * Like fwrite() except we assume 1-byte element size.
 */
size_t
BufFileWrite(BufFile *file, void *ptr, size_t size)
{
	size_t		nwritten = 0;
	size_t		nthistime;

	while (size > 0)
	{
		if (file->pos >= BLCKSZ)
		{
			/* Buffer full, dump it out */
			if (file->dirty)
			{
				BufFileDumpBuffer(file);
				if (file->dirty)
					break;		/* I/O error */
			}
			else
			{
				/* Hmm, went directly from reading to writing? */
				file->curOffset += file->pos;
				file->pos = 0;
				file->nbytes = 0;
			}
		}

		nthistime = BLCKSZ - file->pos;
		if (nthistime > size)
			nthistime = size;
		Assert(nthistime > 0);

		memcpy(file->buffer + file->pos, ptr, nthistime);

		file->dirty = true;
		file->pos += nthistime;
		if (file->nbytes < file->pos)
			file->nbytes = file->pos;
		ptr = (void *) ((char *) ptr + nthistime);
		size -= nthistime;
		nwritten += nthistime;
	}

	return nwritten;
}

424 425
/*
 * BufFileFlush
426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441
 *
 * Like fflush()
 */
static int
BufFileFlush(BufFile *file)
{
	if (file->dirty)
	{
		BufFileDumpBuffer(file);
		if (file->dirty)
			return EOF;
	}

	return 0;
}

442 443
/*
 * BufFileSeek
444
 *
445 446 447 448 449 450
 * Like fseek(), except that target position needs two values in order to
 * work when logical filesize exceeds maximum value representable by long.
 * We do not support relative seeks across more than LONG_MAX, however.
 *
 * Result is 0 if OK, EOF if not.  Logical position is not moved if an
 * impossible seek is attempted.
451 452
 */
int
453
BufFileSeek(BufFile *file, int fileno, off_t offset, int whence)
454
{
455
	int			newFile;
456
	off_t		newOffset;
457

458 459 460
	switch (whence)
	{
		case SEEK_SET:
461
			if (fileno < 0)
462 463 464 465 466
				return EOF;
			newFile = fileno;
			newOffset = offset;
			break;
		case SEEK_CUR:
467

468
			/*
469
			 * Relative seek considers only the signed offset, ignoring
470
			 * fileno. Note that large offsets (> 1 gig) risk overflow in this
471
			 * add, unless we have 64-bit off_t.
472 473 474 475 476 477 478 479 480 481
			 */
			newFile = file->curFile;
			newOffset = (file->curOffset + file->pos) + offset;
			break;
#ifdef NOT_USED
		case SEEK_END:
			/* could be implemented, not needed currently */
			break;
#endif
		default:
482
			elog(ERROR, "invalid whence: %d", whence);
483 484 485 486 487 488 489 490 491 492 493 494 495 496
			return EOF;
	}
	while (newOffset < 0)
	{
		if (--newFile < 0)
			return EOF;
		newOffset += MAX_PHYSICAL_FILESIZE;
	}
	if (newFile == file->curFile &&
		newOffset >= file->curOffset &&
		newOffset <= file->curOffset + file->nbytes)
	{
		/*
		 * Seek is to a point within existing buffer; we can just adjust
497 498 499
		 * pos-within-buffer, without flushing buffer.	Note this is OK
		 * whether reading or writing, but buffer remains dirty if we were
		 * writing.
500 501 502 503 504 505 506
		 */
		file->pos = (int) (newOffset - file->curOffset);
		return 0;
	}
	/* Otherwise, must reposition buffer, so flush any dirty data */
	if (BufFileFlush(file) != 0)
		return EOF;
507

508
	/*
509
	 * At this point and no sooner, check for seek past last segment. The
510 511
	 * above flush could have created a new segment, so checking sooner would
	 * not work (at least not with this code).
512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530
	 */
	if (file->isTemp)
	{
		/* convert seek to "start of next seg" to "end of last seg" */
		if (newFile == file->numFiles && newOffset == 0)
		{
			newFile--;
			newOffset = MAX_PHYSICAL_FILESIZE;
		}
		while (newOffset > MAX_PHYSICAL_FILESIZE)
		{
			if (++newFile >= file->numFiles)
				return EOF;
			newOffset -= MAX_PHYSICAL_FILESIZE;
		}
	}
	if (newFile >= file->numFiles)
		return EOF;
	/* Seek is OK! */
531 532 533 534 535 536 537
	file->curFile = newFile;
	file->curOffset = newOffset;
	file->pos = 0;
	file->nbytes = 0;
	return 0;
}

538
void
539
BufFileTell(BufFile *file, int *fileno, off_t *offset)
540 541 542 543
{
	*fileno = file->curFile;
	*offset = file->curOffset + file->pos;
}
544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559

/*
 * BufFileSeekBlock --- block-oriented seek
 *
 * Performs absolute seek to the start of the n'th BLCKSZ-sized block of
 * the file.  Note that users of this interface will fail if their files
 * exceed BLCKSZ * LONG_MAX bytes, but that is quite a lot; we don't work
 * with tables bigger than that, either...
 *
 * Result is 0 if OK, EOF if not.  Logical position is not moved if an
 * impossible seek is attempted.
 */
int
BufFileSeekBlock(BufFile *file, long blknum)
{
	return BufFileSeek(file,
560 561
					   (int) (blknum / BUFFILE_SEG_SIZE),
					   (off_t) (blknum % BUFFILE_SEG_SIZE) * BLCKSZ,
562 563 564
					   SEEK_SET);
}

565
#ifdef NOT_USED
566 567 568 569 570 571 572 573
/*
 * BufFileTellBlock --- block-oriented tell
 *
 * Any fractional part of a block in the current seek position is ignored.
 */
long
BufFileTellBlock(BufFile *file)
{
574
	long		blknum;
575 576

	blknum = (file->curOffset + file->pos) / BLCKSZ;
577
	blknum += file->curFile * BUFFILE_SEG_SIZE;
578 579
	return blknum;
}
580

581
#endif