PostgreSQL Source Code  git master
logtape.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * logtape.c
4  * Management of "logical tapes" within temporary files.
5  *
6  * This module exists to support sorting via multiple merge passes (see
7  * tuplesort.c). Merging is an ideal algorithm for tape devices, but if
8  * we implement it on disk by creating a separate file for each "tape",
9  * there is an annoying problem: the peak space usage is at least twice
10  * the volume of actual data to be sorted. (This must be so because each
11  * datum will appear in both the input and output tapes of the final
12  * merge pass.)
13  *
14  * We can work around this problem by recognizing that any one tape
15  * dataset (with the possible exception of the final output) is written
16  * and read exactly once in a perfectly sequential manner. Therefore,
17  * a datum once read will not be required again, and we can recycle its
18  * space for use by the new tape dataset(s) being generated. In this way,
19  * the total space usage is essentially just the actual data volume, plus
20  * insignificant bookkeeping and start/stop overhead.
21  *
22  * Few OSes allow arbitrary parts of a file to be released back to the OS,
23  * so we have to implement this space-recycling ourselves within a single
24  * logical file. logtape.c exists to perform this bookkeeping and provide
25  * the illusion of N independent tape devices to tuplesort.c. Note that
26  * logtape.c itself depends on buffile.c to provide a "logical file" of
27  * larger size than the underlying OS may support.
28  *
29  * For simplicity, we allocate and release space in the underlying file
30  * in BLCKSZ-size blocks. Space allocation boils down to keeping track
31  * of which blocks in the underlying file belong to which logical tape,
32  * plus any blocks that are free (recycled and not yet reused).
33  * The blocks in each logical tape form a chain, with a prev- and next-
34  * pointer in each block.
35  *
36  * The initial write pass is guaranteed to fill the underlying file
37  * perfectly sequentially, no matter how data is divided into logical tapes.
38  * Once we begin merge passes, the access pattern becomes considerably
39  * less predictable --- but the seeking involved should be comparable to
40  * what would happen if we kept each logical tape in a separate file,
41  * so there's no serious performance penalty paid to obtain the space
42  * savings of recycling. We try to localize the write accesses by always
43  * writing to the lowest-numbered free block when we have a choice; it's
44  * not clear this helps much, but it can't hurt. (XXX perhaps a LIFO
45  * policy for free blocks would be better?)
46  *
47  * To further make the I/Os more sequential, we can use a larger buffer
48  * when reading, and read multiple blocks from the same tape in one go,
49  * whenever the buffer becomes empty.
50  *
51  * To support the above policy of writing to the lowest free block, the
52  * freelist is a min heap.
53  *
54  * Since all the bookkeeping and buffer memory is allocated with palloc(),
55  * and the underlying file(s) are made with OpenTemporaryFile, all resources
56  * for a logical tape set are certain to be cleaned up even if processing
57  * is aborted by ereport(ERROR). To avoid confusion, the caller should take
58  * care that all calls for a single LogicalTapeSet are made in the same
59  * palloc context.
60  *
61  * To support parallel sort operations involving coordinated callers to
62  * tuplesort.c routines across multiple workers, it is necessary to
63  * concatenate each worker BufFile/tapeset into one single logical tapeset
64  * managed by the leader. Workers should have produced one final
65  * materialized tape (their entire output) when this happens in leader.
66  * There will always be the same number of runs as input tapes, and the same
67  * number of input tapes as participants (worker Tuplesortstates).
68  *
69  * Portions Copyright (c) 1996-2022, PostgreSQL Global Development Group
70  * Portions Copyright (c) 1994, Regents of the University of California
71  *
72  * IDENTIFICATION
73  * src/backend/utils/sort/logtape.c
74  *
75  *-------------------------------------------------------------------------
76  */
77 
78 #include "postgres.h"
79 
80 #include <fcntl.h>
81 
82 #include "storage/buffile.h"
83 #include "utils/builtins.h"
84 #include "utils/logtape.h"
85 #include "utils/memdebug.h"
86 #include "utils/memutils.h"
87 
88 /*
89  * A TapeBlockTrailer is stored at the end of each BLCKSZ block.
90  *
91  * The first block of a tape has prev == -1. The last block of a tape
92  * stores the number of valid bytes on the block, inverted, in 'next'
93  * Therefore next < 0 indicates the last block.
94  */
95 typedef struct TapeBlockTrailer
96 {
97  long prev; /* previous block on this tape, or -1 on first
98  * block */
99  long next; /* next block on this tape, or # of valid
100  * bytes on last block (if < 0) */
102 
103 #define TapeBlockPayloadSize (BLCKSZ - sizeof(TapeBlockTrailer))
104 #define TapeBlockGetTrailer(buf) \
105  ((TapeBlockTrailer *) ((char *) buf + TapeBlockPayloadSize))
106 
107 #define TapeBlockIsLast(buf) (TapeBlockGetTrailer(buf)->next < 0)
108 #define TapeBlockGetNBytes(buf) \
109  (TapeBlockIsLast(buf) ? \
110  (- TapeBlockGetTrailer(buf)->next) : TapeBlockPayloadSize)
111 #define TapeBlockSetNBytes(buf, nbytes) \
112  (TapeBlockGetTrailer(buf)->next = -(nbytes))
113 
114 /*
115  * When multiple tapes are being written to concurrently (as in HashAgg),
116  * avoid excessive fragmentation by preallocating block numbers to individual
117  * tapes. Each preallocation doubles in size starting at
118  * TAPE_WRITE_PREALLOC_MIN blocks up to TAPE_WRITE_PREALLOC_MAX blocks.
119  *
120  * No filesystem operations are performed for preallocation; only the block
121  * numbers are reserved. This may lead to sparse writes, which will cause
122  * ltsWriteBlock() to fill in holes with zeros.
123  */
124 #define TAPE_WRITE_PREALLOC_MIN 8
125 #define TAPE_WRITE_PREALLOC_MAX 128
126 
127 /*
128  * This data structure represents a single "logical tape" within the set
129  * of logical tapes stored in the same file.
130  *
131  * While writing, we hold the current partially-written data block in the
132  * buffer. While reading, we can hold multiple blocks in the buffer. Note
133  * that we don't retain the trailers of a block when it's read into the
134  * buffer. The buffer therefore contains one large contiguous chunk of data
135  * from the tape.
136  */
138 {
139  LogicalTapeSet *tapeSet; /* tape set this tape is part of */
140 
141  bool writing; /* T while in write phase */
142  bool frozen; /* T if blocks should not be freed when read */
143  bool dirty; /* does buffer need to be written? */
144 
145  /*
146  * Block numbers of the first, current, and next block of the tape.
147  *
148  * The "current" block number is only valid when writing, or reading from
149  * a frozen tape. (When reading from an unfrozen tape, we use a larger
150  * read buffer that holds multiple blocks, so the "current" block is
151  * ambiguous.)
152  *
153  * When concatenation of worker tape BufFiles is performed, an offset to
154  * the first block in the unified BufFile space is applied during reads.
155  */
160 
161  /*
162  * Buffer for current data block(s).
163  */
164  char *buffer; /* physical buffer (separately palloc'd) */
165  int buffer_size; /* allocated size of the buffer */
166  int max_size; /* highest useful, safe buffer_size */
167  int pos; /* next read/write position in buffer */
168  int nbytes; /* total # of valid bytes in buffer */
169 
170  /*
171  * Preallocated block numbers are held in an array sorted in descending
172  * order; blocks are consumed from the end of the array (lowest block
173  * numbers first).
174  */
175  long *prealloc;
176  int nprealloc; /* number of elements in list */
177  int prealloc_size; /* number of elements list can hold */
178 };
179 
180 /*
181  * This data structure represents a set of related "logical tapes" sharing
182  * space in a single underlying file. (But that "file" may be multiple files
183  * if needed to escape OS limits on file size; buffile.c handles that for us.)
184  * Tapes belonging to a tape set can be created and destroyed on-the-fly, on
185  * demand.
186  */
188 {
189  BufFile *pfile; /* underlying file for whole tape set */
191  int worker; /* worker # if shared, -1 for leader/serial */
192 
193  /*
194  * File size tracking. nBlocksWritten is the size of the underlying file,
195  * in BLCKSZ blocks. nBlocksAllocated is the number of blocks allocated
196  * by ltsReleaseBlock(), and it is always greater than or equal to
197  * nBlocksWritten. Blocks between nBlocksAllocated and nBlocksWritten are
198  * blocks that have been allocated for a tape, but have not been written
199  * to the underlying file yet. nHoleBlocks tracks the total number of
200  * blocks that are in unused holes between worker spaces following BufFile
201  * concatenation.
202  */
203  long nBlocksAllocated; /* # of blocks allocated */
204  long nBlocksWritten; /* # of blocks used in underlying file */
205  long nHoleBlocks; /* # of "hole" blocks left */
206 
207  /*
208  * We store the numbers of recycled-and-available blocks in freeBlocks[].
209  * When there are no such blocks, we extend the underlying file.
210  *
211  * If forgetFreeSpace is true then any freed blocks are simply forgotten
212  * rather than being remembered in freeBlocks[]. See notes for
213  * LogicalTapeSetForgetFreeSpace().
214  */
215  bool forgetFreeSpace; /* are we remembering free blocks? */
216  long *freeBlocks; /* resizable array holding minheap */
217  long nFreeBlocks; /* # of currently free blocks */
218  Size freeBlocksLen; /* current allocated length of freeBlocks[] */
219  bool enable_prealloc; /* preallocate write blocks? */
220 };
221 
223 static void ltsWriteBlock(LogicalTapeSet *lts, long blocknum, void *buffer);
224 static void ltsReadBlock(LogicalTapeSet *lts, long blocknum, void *buffer);
225 static long ltsGetBlock(LogicalTapeSet *lts, LogicalTape *lt);
226 static long ltsGetFreeBlock(LogicalTapeSet *lts);
227 static long ltsGetPreallocBlock(LogicalTapeSet *lts, LogicalTape *lt);
228 static void ltsReleaseBlock(LogicalTapeSet *lts, long blocknum);
229 static void ltsInitReadBuffer(LogicalTape *lt);
230 
231 
232 /*
233  * Write a block-sized buffer to the specified block of the underlying file.
234  *
235  * No need for an error return convention; we ereport() on any error.
236  */
237 static void
238 ltsWriteBlock(LogicalTapeSet *lts, long blocknum, void *buffer)
239 {
240  /*
241  * BufFile does not support "holes", so if we're about to write a block
242  * that's past the current end of file, fill the space between the current
243  * end of file and the target block with zeros.
244  *
245  * This can happen either when tapes preallocate blocks; or for the last
246  * block of a tape which might not have been flushed.
247  *
248  * Note that BufFile concatenation can leave "holes" in BufFile between
249  * worker-owned block ranges. These are tracked for reporting purposes
250  * only. We never read from nor write to these hole blocks, and so they
251  * are not considered here.
252  */
253  while (blocknum > lts->nBlocksWritten)
254  {
255  PGAlignedBlock zerobuf;
256 
257  MemSet(zerobuf.data, 0, sizeof(zerobuf));
258 
259  ltsWriteBlock(lts, lts->nBlocksWritten, zerobuf.data);
260  }
261 
262  /* Write the requested block */
263  if (BufFileSeekBlock(lts->pfile, blocknum) != 0)
264  ereport(ERROR,
266  errmsg("could not seek to block %ld of temporary file",
267  blocknum)));
268  BufFileWrite(lts->pfile, buffer, BLCKSZ);
269 
270  /* Update nBlocksWritten, if we extended the file */
271  if (blocknum == lts->nBlocksWritten)
272  lts->nBlocksWritten++;
273 }
274 
275 /*
276  * Read a block-sized buffer from the specified block of the underlying file.
277  *
278  * No need for an error return convention; we ereport() on any error. This
279  * module should never attempt to read a block it doesn't know is there.
280  */
281 static void
282 ltsReadBlock(LogicalTapeSet *lts, long blocknum, void *buffer)
283 {
284  size_t nread;
285 
286  if (BufFileSeekBlock(lts->pfile, blocknum) != 0)
287  ereport(ERROR,
289  errmsg("could not seek to block %ld of temporary file",
290  blocknum)));
291  nread = BufFileRead(lts->pfile, buffer, BLCKSZ);
292  if (nread != BLCKSZ)
293  ereport(ERROR,
295  errmsg("could not read block %ld of temporary file: read only %zu of %zu bytes",
296  blocknum, nread, (size_t) BLCKSZ)));
297 }
298 
299 /*
300  * Read as many blocks as we can into the per-tape buffer.
301  *
302  * Returns true if anything was read, 'false' on EOF.
303  */
304 static bool
306 {
307  lt->pos = 0;
308  lt->nbytes = 0;
309 
310  do
311  {
312  char *thisbuf = lt->buffer + lt->nbytes;
313  long datablocknum = lt->nextBlockNumber;
314 
315  /* Fetch next block number */
316  if (datablocknum == -1L)
317  break; /* EOF */
318  /* Apply worker offset, needed for leader tapesets */
319  datablocknum += lt->offsetBlockNumber;
320 
321  /* Read the block */
322  ltsReadBlock(lt->tapeSet, datablocknum, (void *) thisbuf);
323  if (!lt->frozen)
324  ltsReleaseBlock(lt->tapeSet, datablocknum);
326 
327  lt->nbytes += TapeBlockGetNBytes(thisbuf);
328  if (TapeBlockIsLast(thisbuf))
329  {
330  lt->nextBlockNumber = -1L;
331  /* EOF */
332  break;
333  }
334  else
335  lt->nextBlockNumber = TapeBlockGetTrailer(thisbuf)->next;
336 
337  /* Advance to next block, if we have buffer space left */
338  } while (lt->buffer_size - lt->nbytes > BLCKSZ);
339 
340  return (lt->nbytes > 0);
341 }
342 
343 static inline unsigned long
344 left_offset(unsigned long i)
345 {
346  return 2 * i + 1;
347 }
348 
349 static inline unsigned long
350 right_offset(unsigned long i)
351 {
352  return 2 * i + 2;
353 }
354 
355 static inline unsigned long
356 parent_offset(unsigned long i)
357 {
358  return (i - 1) / 2;
359 }
360 
361 /*
362  * Get the next block for writing.
363  */
364 static long
366 {
367  if (lts->enable_prealloc)
368  return ltsGetPreallocBlock(lts, lt);
369  else
370  return ltsGetFreeBlock(lts);
371 }
372 
373 /*
374  * Select the lowest currently unused block from the tape set's global free
375  * list min heap.
376  */
377 static long
379 {
380  long *heap = lts->freeBlocks;
381  long blocknum;
382  int heapsize;
383  long holeval;
384  unsigned long holepos;
385 
386  /* freelist empty; allocate a new block */
387  if (lts->nFreeBlocks == 0)
388  return lts->nBlocksAllocated++;
389 
390  /* easy if heap contains one element */
391  if (lts->nFreeBlocks == 1)
392  {
393  lts->nFreeBlocks--;
394  return lts->freeBlocks[0];
395  }
396 
397  /* remove top of minheap */
398  blocknum = heap[0];
399 
400  /* we'll replace it with end of minheap array */
401  holeval = heap[--lts->nFreeBlocks];
402 
403  /* sift down */
404  holepos = 0; /* holepos is where the "hole" is */
405  heapsize = lts->nFreeBlocks;
406  while (true)
407  {
408  unsigned long left = left_offset(holepos);
409  unsigned long right = right_offset(holepos);
410  unsigned long min_child;
411 
412  if (left < heapsize && right < heapsize)
413  min_child = (heap[left] < heap[right]) ? left : right;
414  else if (left < heapsize)
415  min_child = left;
416  else if (right < heapsize)
417  min_child = right;
418  else
419  break;
420 
421  if (heap[min_child] >= holeval)
422  break;
423 
424  heap[holepos] = heap[min_child];
425  holepos = min_child;
426  }
427  heap[holepos] = holeval;
428 
429  return blocknum;
430 }
431 
432 /*
433  * Return the lowest free block number from the tape's preallocation list.
434  * Refill the preallocation list with blocks from the tape set's free list if
435  * necessary.
436  */
437 static long
439 {
440  /* sorted in descending order, so return the last element */
441  if (lt->nprealloc > 0)
442  return lt->prealloc[--lt->nprealloc];
443 
444  if (lt->prealloc == NULL)
445  {
447  lt->prealloc = (long *) palloc(sizeof(long) * lt->prealloc_size);
448  }
449  else if (lt->prealloc_size < TAPE_WRITE_PREALLOC_MAX)
450  {
451  /* when the preallocation list runs out, double the size */
452  lt->prealloc_size *= 2;
455  lt->prealloc = (long *) repalloc(lt->prealloc,
456  sizeof(long) * lt->prealloc_size);
457  }
458 
459  /* refill preallocation list */
460  lt->nprealloc = lt->prealloc_size;
461  for (int i = lt->nprealloc; i > 0; i--)
462  {
463  lt->prealloc[i - 1] = ltsGetFreeBlock(lts);
464 
465  /* verify descending order */
466  Assert(i == lt->nprealloc || lt->prealloc[i - 1] > lt->prealloc[i]);
467  }
468 
469  return lt->prealloc[--lt->nprealloc];
470 }
471 
472 /*
473  * Return a block# to the freelist.
474  */
475 static void
476 ltsReleaseBlock(LogicalTapeSet *lts, long blocknum)
477 {
478  long *heap;
479  unsigned long holepos;
480 
481  /*
482  * Do nothing if we're no longer interested in remembering free space.
483  */
484  if (lts->forgetFreeSpace)
485  return;
486 
487  /*
488  * Enlarge freeBlocks array if full.
489  */
490  if (lts->nFreeBlocks >= lts->freeBlocksLen)
491  {
492  /*
493  * If the freelist becomes very large, just return and leak this free
494  * block.
495  */
496  if (lts->freeBlocksLen * 2 * sizeof(long) > MaxAllocSize)
497  return;
498 
499  lts->freeBlocksLen *= 2;
500  lts->freeBlocks = (long *) repalloc(lts->freeBlocks,
501  lts->freeBlocksLen * sizeof(long));
502  }
503 
504  /* create a "hole" at end of minheap array */
505  heap = lts->freeBlocks;
506  holepos = lts->nFreeBlocks;
507  lts->nFreeBlocks++;
508 
509  /* sift up to insert blocknum */
510  while (holepos != 0)
511  {
512  unsigned long parent = parent_offset(holepos);
513 
514  if (heap[parent] < blocknum)
515  break;
516 
517  heap[holepos] = heap[parent];
518  holepos = parent;
519  }
520  heap[holepos] = blocknum;
521 }
522 
523 /*
524  * Lazily allocate and initialize the read buffer. This avoids waste when many
525  * tapes are open at once, but not all are active between rewinding and
526  * reading.
527  */
528 static void
530 {
531  Assert(lt->buffer_size > 0);
532  lt->buffer = palloc(lt->buffer_size);
533 
534  /* Read the first block, or reset if tape is empty */
536  lt->pos = 0;
537  lt->nbytes = 0;
538  ltsReadFillBuffer(lt);
539 }
540 
541 /*
542  * Create a tape set, backed by a temporary underlying file.
543  *
544  * The tape set is initially empty. Use LogicalTapeCreate() to create
545  * tapes in it.
546  *
547  * Serial callers pass NULL argument for shared, and -1 for worker. Parallel
548  * worker callers pass a shared file handle and their own worker number.
549  *
550  * Leader callers pass a shared file handle and -1 for worker. After creating
551  * the tape set, use LogicalTapeImport() to import the worker tapes into it.
552  *
553  * Currently, the leader will only import worker tapes into the set, it does
554  * not create tapes of its own, although in principle that should work.
555  */
557 LogicalTapeSetCreate(bool preallocate, SharedFileSet *fileset, int worker)
558 {
559  LogicalTapeSet *lts;
560 
561  /*
562  * Create top-level struct including per-tape LogicalTape structs.
563  */
564  lts = (LogicalTapeSet *) palloc(sizeof(LogicalTapeSet));
565  lts->nBlocksAllocated = 0L;
566  lts->nBlocksWritten = 0L;
567  lts->nHoleBlocks = 0L;
568  lts->forgetFreeSpace = false;
569  lts->freeBlocksLen = 32; /* reasonable initial guess */
570  lts->freeBlocks = (long *) palloc(lts->freeBlocksLen * sizeof(long));
571  lts->nFreeBlocks = 0;
572  lts->enable_prealloc = preallocate;
573 
574  lts->fileset = fileset;
575  lts->worker = worker;
576 
577  /*
578  * Create temp BufFile storage as required.
579  *
580  * In leader, we hijack the BufFile of the first tape that's imported, and
581  * concatenate the BufFiles of any subsequent tapes to that. Hence don't
582  * create a BufFile here. Things are simpler for the worker case and the
583  * serial case, though. They are generally very similar -- workers use a
584  * shared fileset, whereas serial sorts use a conventional serial BufFile.
585  */
586  if (fileset && worker == -1)
587  lts->pfile = NULL;
588  else if (fileset)
589  {
590  char filename[MAXPGPATH];
591 
592  pg_itoa(worker, filename);
593  lts->pfile = BufFileCreateFileSet(&fileset->fs, filename);
594  }
595  else
596  lts->pfile = BufFileCreateTemp(false);
597 
598  return lts;
599 }
600 
601 /*
602  * Claim ownership of a logical tape from an existing shared BufFile.
603  *
604  * Caller should be leader process. Though tapes are marked as frozen in
605  * workers, they are not frozen when opened within leader, since unfrozen tapes
606  * use a larger read buffer. (Frozen tapes have smaller read buffer, optimized
607  * for random access.)
608  */
609 LogicalTape *
610 LogicalTapeImport(LogicalTapeSet *lts, int worker, TapeShare *shared)
611 {
612  LogicalTape *lt;
613  long tapeblocks;
614  char filename[MAXPGPATH];
615  BufFile *file;
616  int64 filesize;
617 
618  lt = ltsCreateTape(lts);
619 
620  /*
621  * build concatenated view of all buffiles, remembering the block number
622  * where each source file begins.
623  */
624  pg_itoa(worker, filename);
625  file = BufFileOpenFileSet(&lts->fileset->fs, filename, O_RDONLY, false);
626  filesize = BufFileSize(file);
627 
628  /*
629  * Stash first BufFile, and concatenate subsequent BufFiles to that. Store
630  * block offset into each tape as we go.
631  */
632  lt->firstBlockNumber = shared->firstblocknumber;
633  if (lts->pfile == NULL)
634  {
635  lts->pfile = file;
636  lt->offsetBlockNumber = 0L;
637  }
638  else
639  {
640  lt->offsetBlockNumber = BufFileAppend(lts->pfile, file);
641  }
642  /* Don't allocate more for read buffer than could possibly help */
643  lt->max_size = Min(MaxAllocSize, filesize);
644  tapeblocks = filesize / BLCKSZ;
645 
646  /*
647  * Update # of allocated blocks and # blocks written to reflect the
648  * imported BufFile. Allocated/written blocks include space used by holes
649  * left between concatenated BufFiles. Also track the number of hole
650  * blocks so that we can later work backwards to calculate the number of
651  * physical blocks for instrumentation.
652  */
654 
655  lts->nBlocksAllocated = lt->offsetBlockNumber + tapeblocks;
656  lts->nBlocksWritten = lts->nBlocksAllocated;
657 
658  return lt;
659 }
660 
661 /*
662  * Close a logical tape set and release all resources.
663  *
664  * NOTE: This doesn't close any of the tapes! You must close them
665  * first, or you can let them be destroyed along with the memory context.
666  */
667 void
669 {
670  BufFileClose(lts->pfile);
671  pfree(lts->freeBlocks);
672  pfree(lts);
673 }
674 
675 /*
676  * Create a logical tape in the given tapeset.
677  *
678  * The tape is initialized in write state.
679  */
680 LogicalTape *
682 {
683  /*
684  * The only thing that currently prevents creating new tapes in leader is
685  * the fact that BufFiles opened using BufFileOpenShared() are read-only
686  * by definition, but that could be changed if it seemed worthwhile. For
687  * now, writing to the leader tape will raise a "Bad file descriptor"
688  * error, so tuplesort must avoid writing to the leader tape altogether.
689  */
690  if (lts->fileset && lts->worker == -1)
691  elog(ERROR, "cannot create new tapes in leader process");
692 
693  return ltsCreateTape(lts);
694 }
695 
696 static LogicalTape *
698 {
699  LogicalTape *lt;
700 
701  /*
702  * Create per-tape struct. Note we allocate the I/O buffer lazily.
703  */
704  lt = palloc(sizeof(LogicalTape));
705  lt->tapeSet = lts;
706  lt->writing = true;
707  lt->frozen = false;
708  lt->dirty = false;
709  lt->firstBlockNumber = -1L;
710  lt->curBlockNumber = -1L;
711  lt->nextBlockNumber = -1L;
712  lt->offsetBlockNumber = 0L;
713  lt->buffer = NULL;
714  lt->buffer_size = 0;
715  /* palloc() larger than MaxAllocSize would fail */
716  lt->max_size = MaxAllocSize;
717  lt->pos = 0;
718  lt->nbytes = 0;
719  lt->prealloc = NULL;
720  lt->nprealloc = 0;
721  lt->prealloc_size = 0;
722 
723  return lt;
724 }
725 
726 /*
727  * Close a logical tape.
728  *
729  * Note: This doesn't return any blocks to the free list! You must read
730  * the tape to the end first, to reuse the space. In current use, though,
731  * we only close tapes after fully reading them.
732  */
733 void
735 {
736  if (lt->buffer)
737  pfree(lt->buffer);
738  pfree(lt);
739 }
740 
741 /*
742  * Mark a logical tape set as not needing management of free space anymore.
743  *
744  * This should be called if the caller does not intend to write any more data
745  * into the tape set, but is reading from un-frozen tapes. Since no more
746  * writes are planned, remembering free blocks is no longer useful. Setting
747  * this flag lets us avoid wasting time and space in ltsReleaseBlock(), which
748  * is not designed to handle large numbers of free blocks.
749  */
750 void
752 {
753  lts->forgetFreeSpace = true;
754 }
755 
756 /*
757  * Write to a logical tape.
758  *
759  * There are no error returns; we ereport() on failure.
760  */
761 void
762 LogicalTapeWrite(LogicalTape *lt, void *ptr, size_t size)
763 {
764  LogicalTapeSet *lts = lt->tapeSet;
765  size_t nthistime;
766 
767  Assert(lt->writing);
768  Assert(lt->offsetBlockNumber == 0L);
769 
770  /* Allocate data buffer and first block on first write */
771  if (lt->buffer == NULL)
772  {
773  lt->buffer = (char *) palloc(BLCKSZ);
774  lt->buffer_size = BLCKSZ;
775  }
776  if (lt->curBlockNumber == -1)
777  {
778  Assert(lt->firstBlockNumber == -1);
779  Assert(lt->pos == 0);
780 
781  lt->curBlockNumber = ltsGetBlock(lts, lt);
783 
784  TapeBlockGetTrailer(lt->buffer)->prev = -1L;
785  }
786 
787  Assert(lt->buffer_size == BLCKSZ);
788  while (size > 0)
789  {
790  if (lt->pos >= (int) TapeBlockPayloadSize)
791  {
792  /* Buffer full, dump it out */
793  long nextBlockNumber;
794 
795  if (!lt->dirty)
796  {
797  /* Hmm, went directly from reading to writing? */
798  elog(ERROR, "invalid logtape state: should be dirty");
799  }
800 
801  /*
802  * First allocate the next block, so that we can store it in the
803  * 'next' pointer of this block.
804  */
805  nextBlockNumber = ltsGetBlock(lt->tapeSet, lt);
806 
807  /* set the next-pointer and dump the current block. */
808  TapeBlockGetTrailer(lt->buffer)->next = nextBlockNumber;
809  ltsWriteBlock(lt->tapeSet, lt->curBlockNumber, (void *) lt->buffer);
810 
811  /* initialize the prev-pointer of the next block */
812  TapeBlockGetTrailer(lt->buffer)->prev = lt->curBlockNumber;
813  lt->curBlockNumber = nextBlockNumber;
814  lt->pos = 0;
815  lt->nbytes = 0;
816  }
817 
818  nthistime = TapeBlockPayloadSize - lt->pos;
819  if (nthistime > size)
820  nthistime = size;
821  Assert(nthistime > 0);
822 
823  memcpy(lt->buffer + lt->pos, ptr, nthistime);
824 
825  lt->dirty = true;
826  lt->pos += nthistime;
827  if (lt->nbytes < lt->pos)
828  lt->nbytes = lt->pos;
829  ptr = (void *) ((char *) ptr + nthistime);
830  size -= nthistime;
831  }
832 }
833 
834 /*
835  * Rewind logical tape and switch from writing to reading.
836  *
837  * The tape must currently be in writing state, or "frozen" in read state.
838  *
839  * 'buffer_size' specifies how much memory to use for the read buffer.
840  * Regardless of the argument, the actual amount of memory used is between
841  * BLCKSZ and MaxAllocSize, and is a multiple of BLCKSZ. The given value is
842  * rounded down and truncated to fit those constraints, if necessary. If the
843  * tape is frozen, the 'buffer_size' argument is ignored, and a small BLCKSZ
844  * byte buffer is used.
845  */
846 void
847 LogicalTapeRewindForRead(LogicalTape *lt, size_t buffer_size)
848 {
849  LogicalTapeSet *lts = lt->tapeSet;
850 
851  /*
852  * Round and cap buffer_size if needed.
853  */
854  if (lt->frozen)
855  buffer_size = BLCKSZ;
856  else
857  {
858  /* need at least one block */
859  if (buffer_size < BLCKSZ)
860  buffer_size = BLCKSZ;
861 
862  /* palloc() larger than max_size is unlikely to be helpful */
863  if (buffer_size > lt->max_size)
864  buffer_size = lt->max_size;
865 
866  /* round down to BLCKSZ boundary */
867  buffer_size -= buffer_size % BLCKSZ;
868  }
869 
870  if (lt->writing)
871  {
872  /*
873  * Completion of a write phase. Flush last partial data block, and
874  * rewind for normal (destructive) read.
875  */
876  if (lt->dirty)
877  {
878  /*
879  * As long as we've filled the buffer at least once, its contents
880  * are entirely defined from valgrind's point of view, even though
881  * contents beyond the current end point may be stale. But it's
882  * possible - at least in the case of a parallel sort - to sort
883  * such small amount of data that we do not fill the buffer even
884  * once. Tell valgrind that its contents are defined, so it
885  * doesn't bleat.
886  */
888  lt->buffer_size - lt->nbytes);
889 
890  TapeBlockSetNBytes(lt->buffer, lt->nbytes);
891  ltsWriteBlock(lt->tapeSet, lt->curBlockNumber, (void *) lt->buffer);
892  }
893  lt->writing = false;
894  }
895  else
896  {
897  /*
898  * This is only OK if tape is frozen; we rewind for (another) read
899  * pass.
900  */
901  Assert(lt->frozen);
902  }
903 
904  if (lt->buffer)
905  pfree(lt->buffer);
906 
907  /* the buffer is lazily allocated, but set the size here */
908  lt->buffer = NULL;
909  lt->buffer_size = buffer_size;
910 
911  /* free the preallocation list, and return unused block numbers */
912  if (lt->prealloc != NULL)
913  {
914  for (int i = lt->nprealloc; i > 0; i--)
915  ltsReleaseBlock(lts, lt->prealloc[i - 1]);
916  pfree(lt->prealloc);
917  lt->prealloc = NULL;
918  lt->nprealloc = 0;
919  lt->prealloc_size = 0;
920  }
921 }
922 
923 /*
924  * Read from a logical tape.
925  *
926  * Early EOF is indicated by return value less than #bytes requested.
927  */
928 size_t
929 LogicalTapeRead(LogicalTape *lt, void *ptr, size_t size)
930 {
931  size_t nread = 0;
932  size_t nthistime;
933 
934  Assert(!lt->writing);
935 
936  if (lt->buffer == NULL)
937  ltsInitReadBuffer(lt);
938 
939  while (size > 0)
940  {
941  if (lt->pos >= lt->nbytes)
942  {
943  /* Try to load more data into buffer. */
944  if (!ltsReadFillBuffer(lt))
945  break; /* EOF */
946  }
947 
948  nthistime = lt->nbytes - lt->pos;
949  if (nthistime > size)
950  nthistime = size;
951  Assert(nthistime > 0);
952 
953  memcpy(ptr, lt->buffer + lt->pos, nthistime);
954 
955  lt->pos += nthistime;
956  ptr = (void *) ((char *) ptr + nthistime);
957  size -= nthistime;
958  nread += nthistime;
959  }
960 
961  return nread;
962 }
963 
964 /*
965  * "Freeze" the contents of a tape so that it can be read multiple times
966  * and/or read backwards. Once a tape is frozen, its contents will not
967  * be released until the LogicalTapeSet is destroyed. This is expected
968  * to be used only for the final output pass of a merge.
969  *
970  * This *must* be called just at the end of a write pass, before the
971  * tape is rewound (after rewind is too late!). It performs a rewind
972  * and switch to read mode "for free". An immediately following rewind-
973  * for-read call is OK but not necessary.
974  *
975  * share output argument is set with details of storage used for tape after
976  * freezing, which may be passed to LogicalTapeSetCreate within leader
977  * process later. This metadata is only of interest to worker callers
978  * freezing their final output for leader (single materialized tape).
979  * Serial sorts should set share to NULL.
980  */
981 void
983 {
984  LogicalTapeSet *lts = lt->tapeSet;
985 
986  Assert(lt->writing);
987  Assert(lt->offsetBlockNumber == 0L);
988 
989  /*
990  * Completion of a write phase. Flush last partial data block, and rewind
991  * for nondestructive read.
992  */
993  if (lt->dirty)
994  {
995  /*
996  * As long as we've filled the buffer at least once, its contents are
997  * entirely defined from valgrind's point of view, even though
998  * contents beyond the current end point may be stale. But it's
999  * possible - at least in the case of a parallel sort - to sort such
1000  * small amount of data that we do not fill the buffer even once. Tell
1001  * valgrind that its contents are defined, so it doesn't bleat.
1002  */
1004  lt->buffer_size - lt->nbytes);
1005 
1006  TapeBlockSetNBytes(lt->buffer, lt->nbytes);
1007  ltsWriteBlock(lt->tapeSet, lt->curBlockNumber, (void *) lt->buffer);
1008  }
1009  lt->writing = false;
1010  lt->frozen = true;
1011 
1012  /*
1013  * The seek and backspace functions assume a single block read buffer.
1014  * That's OK with current usage. A larger buffer is helpful to make the
1015  * read pattern of the backing file look more sequential to the OS, when
1016  * we're reading from multiple tapes. But at the end of a sort, when a
1017  * tape is frozen, we only read from a single tape anyway.
1018  */
1019  if (!lt->buffer || lt->buffer_size != BLCKSZ)
1020  {
1021  if (lt->buffer)
1022  pfree(lt->buffer);
1023  lt->buffer = palloc(BLCKSZ);
1024  lt->buffer_size = BLCKSZ;
1025  }
1026 
1027  /* Read the first block, or reset if tape is empty */
1028  lt->curBlockNumber = lt->firstBlockNumber;
1029  lt->pos = 0;
1030  lt->nbytes = 0;
1031 
1032  if (lt->firstBlockNumber == -1L)
1033  lt->nextBlockNumber = -1L;
1034  ltsReadBlock(lt->tapeSet, lt->curBlockNumber, (void *) lt->buffer);
1035  if (TapeBlockIsLast(lt->buffer))
1036  lt->nextBlockNumber = -1L;
1037  else
1038  lt->nextBlockNumber = TapeBlockGetTrailer(lt->buffer)->next;
1039  lt->nbytes = TapeBlockGetNBytes(lt->buffer);
1040 
1041  /* Handle extra steps when caller is to share its tapeset */
1042  if (share)
1043  {
1045  share->firstblocknumber = lt->firstBlockNumber;
1046  }
1047 }
1048 
1049 /*
1050  * Backspace the tape a given number of bytes. (We also support a more
1051  * general seek interface, see below.)
1052  *
1053  * *Only* a frozen-for-read tape can be backed up; we don't support
1054  * random access during write, and an unfrozen read tape may have
1055  * already discarded the desired data!
1056  *
1057  * Returns the number of bytes backed up. It can be less than the
1058  * requested amount, if there isn't that much data before the current
1059  * position. The tape is positioned to the beginning of the tape in
1060  * that case.
1061  */
1062 size_t
1064 {
1065  size_t seekpos = 0;
1066 
1067  Assert(lt->frozen);
1068  Assert(lt->buffer_size == BLCKSZ);
1069 
1070  if (lt->buffer == NULL)
1071  ltsInitReadBuffer(lt);
1072 
1073  /*
1074  * Easy case for seek within current block.
1075  */
1076  if (size <= (size_t) lt->pos)
1077  {
1078  lt->pos -= (int) size;
1079  return size;
1080  }
1081 
1082  /*
1083  * Not-so-easy case, have to walk back the chain of blocks. This
1084  * implementation would be pretty inefficient for long seeks, but we
1085  * really aren't doing that (a seek over one tuple is typical).
1086  */
1087  seekpos = (size_t) lt->pos; /* part within this block */
1088  while (size > seekpos)
1089  {
1090  long prev = TapeBlockGetTrailer(lt->buffer)->prev;
1091 
1092  if (prev == -1L)
1093  {
1094  /* Tried to back up beyond the beginning of tape. */
1095  if (lt->curBlockNumber != lt->firstBlockNumber)
1096  elog(ERROR, "unexpected end of tape");
1097  lt->pos = 0;
1098  return seekpos;
1099  }
1100 
1101  ltsReadBlock(lt->tapeSet, prev, (void *) lt->buffer);
1102 
1103  if (TapeBlockGetTrailer(lt->buffer)->next != lt->curBlockNumber)
1104  elog(ERROR, "broken tape, next of block %ld is %ld, expected %ld",
1105  prev,
1106  TapeBlockGetTrailer(lt->buffer)->next,
1107  lt->curBlockNumber);
1108 
1110  lt->curBlockNumber = prev;
1111  lt->nextBlockNumber = TapeBlockGetTrailer(lt->buffer)->next;
1112 
1113  seekpos += TapeBlockPayloadSize;
1114  }
1115 
1116  /*
1117  * 'seekpos' can now be greater than 'size', because it points to the
1118  * beginning the target block. The difference is the position within the
1119  * page.
1120  */
1121  lt->pos = seekpos - size;
1122  return size;
1123 }
1124 
1125 /*
1126  * Seek to an arbitrary position in a logical tape.
1127  *
1128  * *Only* a frozen-for-read tape can be seeked.
1129  *
1130  * Must be called with a block/offset previously returned by
1131  * LogicalTapeTell().
1132  */
1133 void
1134 LogicalTapeSeek(LogicalTape *lt, long blocknum, int offset)
1135 {
1136  Assert(lt->frozen);
1137  Assert(offset >= 0 && offset <= TapeBlockPayloadSize);
1138  Assert(lt->buffer_size == BLCKSZ);
1139 
1140  if (lt->buffer == NULL)
1141  ltsInitReadBuffer(lt);
1142 
1143  if (blocknum != lt->curBlockNumber)
1144  {
1145  ltsReadBlock(lt->tapeSet, blocknum, (void *) lt->buffer);
1146  lt->curBlockNumber = blocknum;
1148  lt->nextBlockNumber = TapeBlockGetTrailer(lt->buffer)->next;
1149  }
1150 
1151  if (offset > lt->nbytes)
1152  elog(ERROR, "invalid tape seek position");
1153  lt->pos = offset;
1154 }
1155 
1156 /*
1157  * Obtain current position in a form suitable for a later LogicalTapeSeek.
1158  *
1159  * NOTE: it'd be OK to do this during write phase with intention of using
1160  * the position for a seek after freezing. Not clear if anyone needs that.
1161  */
1162 void
1163 LogicalTapeTell(LogicalTape *lt, long *blocknum, int *offset)
1164 {
1165  if (lt->buffer == NULL)
1166  ltsInitReadBuffer(lt);
1167 
1168  Assert(lt->offsetBlockNumber == 0L);
1169 
1170  /* With a larger buffer, 'pos' wouldn't be the same as offset within page */
1171  Assert(lt->buffer_size == BLCKSZ);
1172 
1173  *blocknum = lt->curBlockNumber;
1174  *offset = lt->pos;
1175 }
1176 
1177 /*
1178  * Obtain total disk space currently used by a LogicalTapeSet, in blocks.
1179  *
1180  * This should not be called while there are open write buffers; otherwise it
1181  * may not account for buffered data.
1182  */
1183 long
1185 {
1186  return lts->nBlocksWritten - lts->nHoleBlocks;
1187 }
void BufFileExportFileSet(BufFile *file)
Definition: buffile.c:389
size_t BufFileRead(BufFile *file, void *ptr, size_t size)
Definition: buffile.c:582
long BufFileAppend(BufFile *target, BufFile *source)
Definition: buffile.c:872
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:800
BufFile * BufFileCreateTemp(bool interXact)
Definition: buffile.c:188
void BufFileWrite(BufFile *file, void *ptr, size_t size)
Definition: buffile.c:625
int64 BufFileSize(BufFile *file)
Definition: buffile.c:833
BufFile * BufFileCreateFileSet(FileSet *fileset, const char *name)
Definition: buffile.c:262
void BufFileClose(BufFile *file)
Definition: buffile.c:407
#define Min(x, y)
Definition: c.h:986
#define MemSet(start, val, len)
Definition: c.h:1008
size_t Size
Definition: c.h:540
int errcode_for_file_access(void)
Definition: elog.c:716
int errmsg(const char *fmt,...)
Definition: elog.c:904
#define ERROR
Definition: elog.h:33
#define elog(elevel,...)
Definition: elog.h:218
#define ereport(elevel,...)
Definition: elog.h:143
int i
Definition: isn.c:73
Assert(fmt[strlen(fmt) - 1] !='\n')
LogicalTape * LogicalTapeCreate(LogicalTapeSet *lts)
Definition: logtape.c:681
void LogicalTapeRewindForRead(LogicalTape *lt, size_t buffer_size)
Definition: logtape.c:847
#define TapeBlockGetTrailer(buf)
Definition: logtape.c:104
static LogicalTape * ltsCreateTape(LogicalTapeSet *lts)
Definition: logtape.c:697
void LogicalTapeSetForgetFreeSpace(LogicalTapeSet *lts)
Definition: logtape.c:751
size_t LogicalTapeBackspace(LogicalTape *lt, size_t size)
Definition: logtape.c:1063
size_t LogicalTapeRead(LogicalTape *lt, void *ptr, size_t size)
Definition: logtape.c:929
static long ltsGetPreallocBlock(LogicalTapeSet *lts, LogicalTape *lt)
Definition: logtape.c:438
void LogicalTapeClose(LogicalTape *lt)
Definition: logtape.c:734
#define TapeBlockPayloadSize
Definition: logtape.c:103
static unsigned long parent_offset(unsigned long i)
Definition: logtape.c:356
struct TapeBlockTrailer TapeBlockTrailer
void LogicalTapeSetClose(LogicalTapeSet *lts)
Definition: logtape.c:668
static bool ltsReadFillBuffer(LogicalTape *lt)
Definition: logtape.c:305
void LogicalTapeWrite(LogicalTape *lt, void *ptr, size_t size)
Definition: logtape.c:762
static void ltsInitReadBuffer(LogicalTape *lt)
Definition: logtape.c:529
#define TAPE_WRITE_PREALLOC_MIN
Definition: logtape.c:124
static long ltsGetFreeBlock(LogicalTapeSet *lts)
Definition: logtape.c:378
static unsigned long right_offset(unsigned long i)
Definition: logtape.c:350
#define TapeBlockIsLast(buf)
Definition: logtape.c:107
#define TAPE_WRITE_PREALLOC_MAX
Definition: logtape.c:125
static long ltsGetBlock(LogicalTapeSet *lts, LogicalTape *lt)
Definition: logtape.c:365
void LogicalTapeTell(LogicalTape *lt, long *blocknum, int *offset)
Definition: logtape.c:1163
void LogicalTapeSeek(LogicalTape *lt, long blocknum, int offset)
Definition: logtape.c:1134
#define TapeBlockGetNBytes(buf)
Definition: logtape.c:108
static unsigned long left_offset(unsigned long i)
Definition: logtape.c:344
LogicalTapeSet * LogicalTapeSetCreate(bool preallocate, SharedFileSet *fileset, int worker)
Definition: logtape.c:557
static void ltsWriteBlock(LogicalTapeSet *lts, long blocknum, void *buffer)
Definition: logtape.c:238
static void ltsReadBlock(LogicalTapeSet *lts, long blocknum, void *buffer)
Definition: logtape.c:282
long LogicalTapeSetBlocks(LogicalTapeSet *lts)
Definition: logtape.c:1184
#define TapeBlockSetNBytes(buf, nbytes)
Definition: logtape.c:111
static void ltsReleaseBlock(LogicalTapeSet *lts, long blocknum)
Definition: logtape.c:476
void LogicalTapeFreeze(LogicalTape *lt, TapeShare *share)
Definition: logtape.c:982
LogicalTape * LogicalTapeImport(LogicalTapeSet *lts, int worker, TapeShare *shared)
Definition: logtape.c:610
void pfree(void *pointer)
Definition: mcxt.c:1175
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:1188
void * palloc(Size size)
Definition: mcxt.c:1068
#define VALGRIND_MAKE_MEM_DEFINED(addr, size)
Definition: memdebug.h:26
#define MaxAllocSize
Definition: memutils.h:40
int pg_itoa(int16 i, char *a)
Definition: numutils.c:334
#define MAXPGPATH
while(p+4<=pend)
static char * filename
Definition: pg_dumpall.c:94
long nFreeBlocks
Definition: logtape.c:217
BufFile * pfile
Definition: logtape.c:189
bool forgetFreeSpace
Definition: logtape.c:215
long nBlocksAllocated
Definition: logtape.c:203
SharedFileSet * fileset
Definition: logtape.c:190
long nHoleBlocks
Definition: logtape.c:205
Size freeBlocksLen
Definition: logtape.c:218
long * freeBlocks
Definition: logtape.c:216
long nBlocksWritten
Definition: logtape.c:204
bool enable_prealloc
Definition: logtape.c:219
long curBlockNumber
Definition: logtape.c:157
int max_size
Definition: logtape.c:166
long * prealloc
Definition: logtape.c:175
int nprealloc
Definition: logtape.c:176
char * buffer
Definition: logtape.c:164
bool frozen
Definition: logtape.c:142
int prealloc_size
Definition: logtape.c:177
long offsetBlockNumber
Definition: logtape.c:159
long nextBlockNumber
Definition: logtape.c:158
int buffer_size
Definition: logtape.c:165
long firstBlockNumber
Definition: logtape.c:156
bool writing
Definition: logtape.c:141
LogicalTapeSet * tapeSet
Definition: logtape.c:139
int nbytes
Definition: logtape.c:168
bool dirty
Definition: logtape.c:143
long firstblocknumber
Definition: logtape.h:54
char data[BLCKSZ]
Definition: c.h:1138