LCOV - differential code coverage report
Current view: top level - src/backend/utils/sort - tuplesort.c (source / functions) Coverage Total Hit UNC UBC GNC CBC DCB
Current: 4b3c9325757dfd8f2312e9f1a8decf4431f344ae vs e87b024bfb8dd55e3049b1b6e6ab4e810cf1abc8 Lines: 92.2 % 984 907 77 34 873 34
Current Date: 2026-11-28 16:48:44 +0900 Functions: 100.0 % 58 58 13 45 4
Baseline: lcov-20261128-baseline Branches: 66.9 % 692 463 1 228 19 444
Baseline Date: 2026-11-28 16:48:48 +0900 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
(7,30] days: 100.0 % 4 4 4
(30,360] days: 100.0 % 168 168 30 138
(360..) days: 90.5 % 812 735 77 735
Function coverage date bins:
(7,30] days: 100.0 % 1 1 1
(30,360] days: 100.0 % 8 8 4 4
(360..) days: 100.0 % 49 49 8 41
Branch coverage date bins:
(7,30] days: 100.0 % 2 2 2
(30,360] days: 91.2 % 102 93 1 8 17 76
(360..) days: 62.6 % 588 368 220 368

 Age         Owner                    Branch data    TLA  Line data    Source code
                                  1                 :                : /*-------------------------------------------------------------------------
                                  2                 :                :  *
                                  3                 :                :  * tuplesort.c
                                  4                 :                :  *    Generalized tuple sorting routines.
                                  5                 :                :  *
                                  6                 :                :  * This module provides a generalized facility for tuple sorting, which can be
                                  7                 :                :  * applied to different kinds of sortable objects.  Implementation of
                                  8                 :                :  * the particular sorting variants is given in tuplesortvariants.c.
                                  9                 :                :  * This module works efficiently for both small and large amounts
                                 10                 :                :  * of data.  Small amounts are sorted in-memory.  Large amounts are
                                 11                 :                :  * sorted using temporary files and a standard external sort
                                 12                 :                :  * algorithm.
                                 13                 :                :  *
                                 14                 :                :  * See Knuth, volume 3, for more than you want to know about external
                                 15                 :                :  * sorting algorithms.  The algorithm we use is a balanced k-way merge.
                                 16                 :                :  * Before PostgreSQL 15, we used the polyphase merge algorithm (Knuth's
                                 17                 :                :  * Algorithm 5.4.2D), but with modern hardware, a straightforward balanced
                                 18                 :                :  * merge is better.  Knuth is assuming that tape drives are expensive
                                 19                 :                :  * beasts, and in particular that there will always be many more runs than
                                 20                 :                :  * tape drives.  The polyphase merge algorithm was good at keeping all the
                                 21                 :                :  * tape drives busy, but in our implementation a "tape drive" doesn't cost
                                 22                 :                :  * much more than a few Kb of memory buffers, so we can afford to have
                                 23                 :                :  * lots of them.  In particular, if we can have as many tape drives as
                                 24                 :                :  * sorted runs, we can eliminate any repeated I/O at all.
                                 25                 :                :  *
                                 26                 :                :  * Historically, we divided the input into sorted runs using replacement
                                 27                 :                :  * selection, in the form of a priority tree implemented as a heap
                                 28                 :                :  * (essentially Knuth's Algorithm 5.2.3H), but now we always use quicksort
                                 29                 :                :  * or radix sort for run generation.
                                 30                 :                :  *
                                 31                 :                :  * The approximate amount of memory allowed for any one sort operation
                                 32                 :                :  * is specified in kilobytes by the caller (most pass work_mem).  Initially,
                                 33                 :                :  * we absorb tuples and simply store them in an unsorted array as long as
                                 34                 :                :  * we haven't exceeded workMem.  If we reach the end of the input without
                                 35                 :                :  * exceeding workMem, we sort the array in memory and subsequently return
                                 36                 :                :  * tuples just by scanning the tuple array sequentially.  If we do exceed
                                 37                 :                :  * workMem, we begin to emit tuples into sorted runs in temporary tapes.
                                 38                 :                :  * When tuples are dumped in batch after in-memory sorting, we begin a new run
                                 39                 :                :  * with a new output tape.  If we reach the max number of tapes, we write
                                 40                 :                :  * subsequent runs on the existing tapes in a round-robin fashion.  We will
                                 41                 :                :  * need multiple merge passes to finish the merge in that case.  After the
                                 42                 :                :  * end of the input is reached, we dump out remaining tuples in memory into
                                 43                 :                :  * a final run, then merge the runs.
                                 44                 :                :  *
                                 45                 :                :  * When merging runs, we use a heap containing just the frontmost tuple from
                                 46                 :                :  * each source run; we repeatedly output the smallest tuple and replace it
                                 47                 :                :  * with the next tuple from its source tape (if any).  When the heap empties,
                                 48                 :                :  * the merge is complete.  The basic merge algorithm thus needs very little
                                 49                 :                :  * memory --- only M tuples for an M-way merge, and M is constrained to a
                                 50                 :                :  * small number.  However, we can still make good use of our full workMem
                                 51                 :                :  * allocation by pre-reading additional blocks from each source tape.  Without
                                 52                 :                :  * prereading, our access pattern to the temporary file would be very erratic;
                                 53                 :                :  * on average we'd read one block from each of M source tapes during the same
                                 54                 :                :  * time that we're writing M blocks to the output tape, so there is no
                                 55                 :                :  * sequentiality of access at all, defeating the read-ahead methods used by
                                 56                 :                :  * most Unix kernels.  Worse, the output tape gets written into a very random
                                 57                 :                :  * sequence of blocks of the temp file, ensuring that things will be even
                                 58                 :                :  * worse when it comes time to read that tape.  A straightforward merge pass
                                 59                 :                :  * thus ends up doing a lot of waiting for disk seeks.  We can improve matters
                                 60                 :                :  * by prereading from each source tape sequentially, loading about workMem/M
                                 61                 :                :  * bytes from each tape in turn, and making the sequential blocks immediately
                                 62                 :                :  * available for reuse.  This approach helps to localize both read and write
                                 63                 :                :  * accesses.  The pre-reading is handled by logtape.c, we just tell it how
                                 64                 :                :  * much memory to use for the buffers.
                                 65                 :                :  *
                                 66                 :                :  * In the current code we determine the number of input tapes M on the basis
                                 67                 :                :  * of workMem: we want workMem/M to be large enough that we read a fair
                                 68                 :                :  * amount of data each time we read from a tape, so as to maintain the
                                 69                 :                :  * locality of access described above.  Nonetheless, with large workMem we
                                 70                 :                :  * can have many tapes.  The logical "tapes" are implemented by logtape.c,
                                 71                 :                :  * which avoids space wastage by recycling disk space as soon as each block
                                 72                 :                :  * is read from its "tape".
                                 73                 :                :  *
                                 74                 :                :  * When the caller requests random access to the sort result, we form
                                 75                 :                :  * the final sorted run on a logical tape which is then "frozen", so
                                 76                 :                :  * that we can access it randomly.  When the caller does not need random
                                 77                 :                :  * access, we return from tuplesort_performsort() as soon as we are down
                                 78                 :                :  * to one run per logical tape.  The final merge is then performed
                                 79                 :                :  * on-the-fly as the caller repeatedly calls tuplesort_getXXX; this
                                 80                 :                :  * saves one cycle of writing all the data out to disk and reading it in.
                                 81                 :                :  *
                                 82                 :                :  * This module supports parallel sorting.  Parallel sorts involve coordination
                                 83                 :                :  * among one or more worker processes, and a leader process, each with its own
                                 84                 :                :  * tuplesort state.  The leader process (or, more accurately, the
                                 85                 :                :  * Tuplesortstate associated with a leader process) creates a full tapeset
                                 86                 :                :  * consisting of worker tapes with one run to merge; a run for every
                                 87                 :                :  * worker process.  This is then merged.  Worker processes are guaranteed to
                                 88                 :                :  * produce exactly one output run from their partial input.
                                 89                 :                :  *
                                 90                 :                :  *
                                 91                 :                :  * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
                                 92                 :                :  * Portions Copyright (c) 1994, Regents of the University of California
                                 93                 :                :  *
                                 94                 :                :  * IDENTIFICATION
                                 95                 :                :  *    src/backend/utils/sort/tuplesort.c
                                 96                 :                :  *
                                 97                 :                :  *-------------------------------------------------------------------------
                                 98                 :                :  */
                                 99                 :                : 
                                100                 :                : #include "postgres.h"
                                101                 :                : 
                                102                 :                : #include <limits.h>
                                103                 :                : 
                                104                 :                : #include "commands/tablespace.h"
                                105                 :                : #include "miscadmin.h"
                                106                 :                : #include "pg_trace.h"
                                107                 :                : #include "port/atomics.h"
                                108                 :                : #include "port/pg_bitutils.h"
                                109                 :                : #include "storage/shmem.h"
                                110                 :                : #include "utils/guc.h"
                                111                 :                : #include "utils/memutils.h"
                                112                 :                : #include "utils/pg_rusage.h"
                                113                 :                : #include "utils/tuplesort.h"
                                114                 :                : 
                                115                 :                : /*
                                116                 :                :  * Initial size of memtuples array.  This must be more than
                                117                 :                :  * ALLOCSET_SEPARATE_THRESHOLD; see comments in grow_memtuples().  Clamp at
                                118                 :                :  * 1024 elements to avoid excessive reallocs.
                                119                 :                :  */
                                120                 :                : #define INITIAL_MEMTUPSIZE Max(1024, \
                                121                 :                :     ALLOCSET_SEPARATE_THRESHOLD / sizeof(SortTuple) + 1)
                                122                 :                : 
                                123                 :                : /* GUC variables */
                                124                 :                : bool        trace_sort = false;
                                125                 :                : 
                                126                 :                : #ifdef DEBUG_BOUNDED_SORT
                                127                 :                : bool        optimize_bounded_sort = true;
                                128                 :                : #endif
                                129                 :                : 
                                130                 :                : 
                                131                 :                : /*
                                132                 :                :  * During merge, we use a pre-allocated set of fixed-size slots to hold
                                133                 :                :  * tuples.  To avoid palloc/pfree overhead.
                                134                 :                :  *
                                135                 :                :  * Merge doesn't require a lot of memory, so we can afford to waste some,
                                136                 :                :  * by using gratuitously-sized slots.  If a tuple is larger than 1 kB, the
                                137                 :                :  * palloc() overhead is not significant anymore.
                                138                 :                :  *
                                139                 :                :  * 'nextfree' is valid when this chunk is in the free list.  When in use, the
                                140                 :                :  * slot holds a tuple.
                                141                 :                :  */
                                142                 :                : #define SLAB_SLOT_SIZE 1024
                                143                 :                : 
                                144                 :                : typedef union SlabSlot
                                145                 :                : {
                                146                 :                :     union SlabSlot *nextfree;
                                147                 :                :     char        buffer[SLAB_SLOT_SIZE];
                                148                 :                : } SlabSlot;
                                149                 :                : 
                                150                 :                : /*
                                151                 :                :  * Possible states of a Tuplesort object.  These denote the states that
                                152                 :                :  * persist between calls of Tuplesort routines.
                                153                 :                :  */
                                154                 :                : typedef enum
                                155                 :                : {
                                156                 :                :     TSS_INITIAL,                /* Loading tuples; still within memory limit */
                                157                 :                :     TSS_BOUNDED,                /* Loading tuples into bounded-size heap */
                                158                 :                :     TSS_BUILDRUNS,              /* Loading tuples; writing to tape */
                                159                 :                :     TSS_SORTEDINMEM,            /* Sort completed entirely in memory */
                                160                 :                :     TSS_SORTEDONTAPE,           /* Sort completed, final run is on tape */
                                161                 :                :     TSS_FINALMERGE,             /* Performing final merge on-the-fly */
                                162                 :                : } TupSortStatus;
                                163                 :                : 
                                164                 :                : /*
                                165                 :                :  * Parameters for calculation of number of tapes to use --- see inittapes()
                                166                 :                :  * and tuplesort_merge_order().
                                167                 :                :  *
                                168                 :                :  * In this calculation we assume that each tape will cost us about 1 blocks
                                169                 :                :  * worth of buffer space.  This ignores the overhead of all the other data
                                170                 :                :  * structures needed for each tape, but it's probably close enough.
                                171                 :                :  *
                                172                 :                :  * MERGE_BUFFER_SIZE is how much buffer space we'd like to allocate for each
                                173                 :                :  * input tape, for pre-reading (see discussion at top of file).  This is *in
                                174                 :                :  * addition to* the 1 block already included in TAPE_BUFFER_OVERHEAD.
                                175                 :                :  */
                                176                 :                : #define MINORDER        6       /* minimum merge order */
                                177                 :                : #define MAXORDER        500     /* maximum merge order */
                                178                 :                : #define TAPE_BUFFER_OVERHEAD        BLCKSZ
                                179                 :                : #define MERGE_BUFFER_SIZE           (BLCKSZ * 32)
                                180                 :                : 
                                181                 :                : 
                                182                 :                : /*
                                183                 :                :  * Private state of a Tuplesort operation.
                                184                 :                :  */
                                185                 :                : struct Tuplesortstate
                                186                 :                : {
                                187                 :                :     TuplesortPublic base;
                                188                 :                :     TupSortStatus status;       /* enumerated value as shown above */
                                189                 :                :     bool        bounded;        /* did caller specify a maximum number of
                                190                 :                :                                  * tuples to return? */
                                191                 :                :     bool        boundUsed;      /* true if we made use of a bounded heap */
                                192                 :                :     int         bound;          /* if bounded, the maximum number of tuples */
                                193                 :                :     int64       tupleMem;       /* memory consumed by individual tuples.
                                194                 :                :                                  * storing this separately from what we track
                                195                 :                :                                  * in availMem allows us to subtract the
                                196                 :                :                                  * memory consumed by all tuples when dumping
                                197                 :                :                                  * tuples to tape */
                                198                 :                :     int64       availMem;       /* remaining memory available, in bytes */
                                199                 :                :     int64       allowedMem;     /* total memory allowed, in bytes */
                                200                 :                :     int         maxTapes;       /* max number of input tapes to merge in each
                                201                 :                :                                  * pass */
                                202                 :                :     int64       maxSpace;       /* maximum amount of space occupied among sort
                                203                 :                :                                  * of groups, either in-memory or on-disk */
                                204                 :                :     bool        isMaxSpaceDisk; /* true when maxSpace tracks on-disk space,
                                205                 :                :                                  * false means in-memory */
                                206                 :                :     TupSortStatus maxSpaceStatus;   /* sort status when maxSpace was reached */
                                207                 :                :     LogicalTapeSet *tapeset;    /* logtape.c object for tapes in a temp file */
                                208                 :                : 
                                209                 :                :     /*
                                210                 :                :      * This array holds the tuples now in sort memory.  If we are in state
                                211                 :                :      * INITIAL, the tuples are in no particular order; if we are in state
                                212                 :                :      * SORTEDINMEM, the tuples are in final sorted order; in states BUILDRUNS
                                213                 :                :      * and FINALMERGE, the tuples are organized in "heap" order per Algorithm
                                214                 :                :      * H.  In state SORTEDONTAPE, the array is not used.
                                215                 :                :      */
                                216                 :                :     SortTuple  *memtuples;      /* array of SortTuple structs */
                                217                 :                :     int         memtupcount;    /* number of tuples currently present */
                                218                 :                :     int         memtupsize;     /* allocated length of memtuples array */
                                219                 :                :     bool        growmemtuples;  /* memtuples' growth still underway? */
                                220                 :                : 
                                221                 :                :     /*
                                222                 :                :      * Memory for tuples is sometimes allocated using a simple slab allocator,
                                223                 :                :      * rather than with palloc().  Currently, we switch to slab allocation
                                224                 :                :      * when we start merging.  Merging only needs to keep a small, fixed
                                225                 :                :      * number of tuples in memory at any time, so we can avoid the
                                226                 :                :      * palloc/pfree overhead by recycling a fixed number of fixed-size slots
                                227                 :                :      * to hold the tuples.
                                228                 :                :      *
                                229                 :                :      * For the slab, we use one large allocation, divided into SLAB_SLOT_SIZE
                                230                 :                :      * slots.  The allocation is sized to have one slot per tape, plus one
                                231                 :                :      * additional slot.  We need that many slots to hold all the tuples kept
                                232                 :                :      * in the heap during merge, plus the one we have last returned from the
                                233                 :                :      * sort, with tuplesort_gettuple.
                                234                 :                :      *
                                235                 :                :      * Initially, all the slots are kept in a linked list of free slots.  When
                                236                 :                :      * a tuple is read from a tape, it is put to the next available slot, if
                                237                 :                :      * it fits.  If the tuple is larger than SLAB_SLOT_SIZE, it is palloc'd
                                238                 :                :      * instead.
                                239                 :                :      *
                                240                 :                :      * When we're done processing a tuple, we return the slot back to the free
                                241                 :                :      * list, or pfree() if it was palloc'd.  We know that a tuple was
                                242                 :                :      * allocated from the slab, if its pointer value is between
                                243                 :                :      * slabMemoryBegin and -End.
                                244                 :                :      *
                                245                 :                :      * When the slab allocator is used, the USEMEM/LACKMEM mechanism of
                                246                 :                :      * tracking memory usage is not used.
                                247                 :                :      */
                                248                 :                :     bool        slabAllocatorUsed;
                                249                 :                : 
                                250                 :                :     char       *slabMemoryBegin;    /* beginning of slab memory arena */
                                251                 :                :     char       *slabMemoryEnd;  /* end of slab memory arena */
                                252                 :                :     SlabSlot   *slabFreeHead;   /* head of free list */
                                253                 :                : 
                                254                 :                :     /* Memory used for input and output tape buffers. */
                                255                 :                :     size_t      tape_buffer_mem;
                                256                 :                : 
                                257                 :                :     /*
                                258                 :                :      * When we return a tuple to the caller in tuplesort_gettuple_XXX, that
                                259                 :                :      * came from a tape (that is, in TSS_SORTEDONTAPE or TSS_FINALMERGE
                                260                 :                :      * modes), we remember the tuple in 'lastReturnedTuple', so that we can
                                261                 :                :      * recycle the memory on next gettuple call.
                                262                 :                :      */
                                263                 :                :     void       *lastReturnedTuple;
                                264                 :                : 
                                265                 :                :     /*
                                266                 :                :      * While building initial runs, this is the current output run number.
                                267                 :                :      * Afterwards, it is the number of initial runs we made.
                                268                 :                :      */
                                269                 :                :     int         currentRun;
                                270                 :                : 
                                271                 :                :     /*
                                272                 :                :      * Logical tapes, for merging.
                                273                 :                :      *
                                274                 :                :      * The initial runs are written in the output tapes.  In each merge pass,
                                275                 :                :      * the output tapes of the previous pass become the input tapes, and new
                                276                 :                :      * output tapes are created as needed.  When nInputTapes equals
                                277                 :                :      * nInputRuns, there is only one merge pass left.
                                278                 :                :      */
                                279                 :                :     LogicalTape **inputTapes;
                                280                 :                :     int         nInputTapes;
                                281                 :                :     int         nInputRuns;
                                282                 :                : 
                                283                 :                :     LogicalTape **outputTapes;
                                284                 :                :     int         nOutputTapes;
                                285                 :                :     int         nOutputRuns;
                                286                 :                : 
                                287                 :                :     LogicalTape *destTape;      /* current output tape */
                                288                 :                : 
                                289                 :                :     /*
                                290                 :                :      * These variables are used after completion of sorting to keep track of
                                291                 :                :      * the next tuple to return.  (In the tape case, the tape's current read
                                292                 :                :      * position is also critical state.)
                                293                 :                :      */
                                294                 :                :     LogicalTape *result_tape;   /* actual tape of finished output */
                                295                 :                :     int         current;        /* array index (only used if SORTEDINMEM) */
                                296                 :                :     bool        eof_reached;    /* reached EOF (needed for cursors) */
                                297                 :                : 
                                298                 :                :     /* markpos_xxx holds marked position for mark and restore */
                                299                 :                :     int64       markpos_block;  /* tape block# (only used if SORTEDONTAPE) */
                                300                 :                :     int         markpos_offset; /* saved "current", or offset in tape block */
                                301                 :                :     bool        markpos_eof;    /* saved "eof_reached" */
                                302                 :                : 
                                303                 :                :     /*
                                304                 :                :      * These variables are used during parallel sorting.
                                305                 :                :      *
                                306                 :                :      * worker is our worker identifier.  Follows the general convention that
                                307                 :                :      * -1 value relates to a leader tuplesort, and values >= 0 worker
                                308                 :                :      * tuplesorts. (-1 can also be a serial tuplesort.)
                                309                 :                :      *
                                310                 :                :      * shared is mutable shared memory state, which is used to coordinate
                                311                 :                :      * parallel sorts.
                                312                 :                :      *
                                313                 :                :      * nParticipants is the number of worker Tuplesortstates known by the
                                314                 :                :      * leader to have actually been launched, which implies that they must
                                315                 :                :      * finish a run that the leader needs to merge.  Typically includes a
                                316                 :                :      * worker state held by the leader process itself.  Set in the leader
                                317                 :                :      * Tuplesortstate only.
                                318                 :                :      */
                                319                 :                :     int         worker;
                                320                 :                :     Sharedsort *shared;
                                321                 :                :     int         nParticipants;
                                322                 :                : 
                                323                 :                :     /*
                                324                 :                :      * Additional state for managing "abbreviated key" sortsupport routines
                                325                 :                :      * (which currently may be used by all cases except the hash index case).
                                326                 :                :      * Tracks the intervals at which the optimization's effectiveness is
                                327                 :                :      * tested.
                                328                 :                :      */
                                329                 :                :     int64       abbrevNext;     /* Tuple # at which to next check
                                330                 :                :                                  * applicability */
                                331                 :                : 
                                332                 :                :     /*
                                333                 :                :      * Resource snapshot for time of sort start.
                                334                 :                :      */
                                335                 :                :     PGRUsage    ru_start;
                                336                 :                : };
                                337                 :                : 
                                338                 :                : /*
                                339                 :                :  * Private mutable state of tuplesort-parallel-operation.  This is allocated
                                340                 :                :  * in shared memory.
                                341                 :                :  */
                                342                 :                : struct Sharedsort
                                343                 :                : {
                                344                 :                :     /*
                                345                 :                :      * currentWorker generates ordinal identifier numbers for parallel sort
                                346                 :                :      * workers.  These start from 0, and are always gapless.
                                347                 :                :      *
                                348                 :                :      * Workers increment workersFinished to indicate having finished.  If this
                                349                 :                :      * is equal to state.nParticipants within the leader, leader is ready to
                                350                 :                :      * merge worker runs.
                                351                 :                :      */
                                352                 :                :     pg_atomic_uint32 currentWorker;
                                353                 :                :     pg_atomic_uint32 workersFinished;
                                354                 :                : 
                                355                 :                :     /* Temporary file space */
                                356                 :                :     SharedFileSet fileset;
                                357                 :                : 
                                358                 :                :     /* Size of tapes flexible array */
                                359                 :                :     int         nTapes;
                                360                 :                : 
                                361                 :                :     /*
                                362                 :                :      * Tapes array used by workers to report back information needed by the
                                363                 :                :      * leader to concatenate all worker tapes into one for merging
                                364                 :                :      */
                                365                 :                :     pg_attribute_counted_by(nTapes) TapeShare tapes[FLEXIBLE_ARRAY_MEMBER];
                                366                 :                : };
                                367                 :                : 
                                368                 :                : /*
                                369                 :                :  * Is the given tuple allocated from the slab memory arena?
                                370                 :                :  */
                                371                 :                : #define IS_SLAB_SLOT(state, tuple) \
                                372                 :                :     ((char *) (tuple) >= (state)->slabMemoryBegin && \
                                373                 :                :      (char *) (tuple) < (state)->slabMemoryEnd)
                                374                 :                : 
                                375                 :                : /*
                                376                 :                :  * Return the given tuple to the slab memory free list, or free it
                                377                 :                :  * if it was palloc'd.
                                378                 :                :  */
                                379                 :                : #define RELEASE_SLAB_SLOT(state, tuple) \
                                380                 :                :     do { \
                                381                 :                :         SlabSlot *buf = (SlabSlot *) tuple; \
                                382                 :                :         \
                                383                 :                :         if (IS_SLAB_SLOT((state), buf)) \
                                384                 :                :         { \
                                385                 :                :             buf->nextfree = (state)->slabFreeHead; \
                                386                 :                :             (state)->slabFreeHead = buf; \
                                387                 :                :         } else \
                                388                 :                :             pfree(buf); \
                                389                 :                :     } while(0)
                                390                 :                : 
                                391                 :                : #define REMOVEABBREV(state,stup,count)  ((*(state)->base.removeabbrev) (state, stup, count))
                                392                 :                : #define COMPARETUP(state,a,b)   ((*(state)->base.comparetup) (a, b, state))
                                393                 :                : #define WRITETUP(state,tape,stup)   ((*(state)->base.writetup) (state, tape, stup))
                                394                 :                : #define READTUP(state,stup,tape,len) ((*(state)->base.readtup) (state, stup, tape, len))
                                395                 :                : #define FREESTATE(state)    ((state)->base.freestate ? (*(state)->base.freestate) (state) : (void) 0)
                                396                 :                : #define LACKMEM(state)      ((state)->availMem < 0 && !(state)->slabAllocatorUsed)
                                397                 :                : #define USEMEM(state,amt)   ((state)->availMem -= (amt))
                                398                 :                : #define FREEMEM(state,amt)  ((state)->availMem += (amt))
                                399                 :                : #define SERIAL(state)       ((state)->shared == NULL)
                                400                 :                : #define WORKER(state)       ((state)->shared && (state)->worker != -1)
                                401                 :                : #define LEADER(state)       ((state)->shared && (state)->worker == -1)
                                402                 :                : 
                                403                 :                : /*
                                404                 :                :  * NOTES about on-tape representation of tuples:
                                405                 :                :  *
                                406                 :                :  * We require the first "unsigned int" of a stored tuple to be the total size
                                407                 :                :  * on-tape of the tuple, including itself (so it is never zero; an all-zero
                                408                 :                :  * unsigned int is used to delimit runs).  The remainder of the stored tuple
                                409                 :                :  * may or may not match the in-memory representation of the tuple ---
                                410                 :                :  * any conversion needed is the job of the writetup and readtup routines.
                                411                 :                :  *
                                412                 :                :  * If state->sortopt contains TUPLESORT_RANDOMACCESS, then the stored
                                413                 :                :  * representation of the tuple must be followed by another "unsigned int" that
                                414                 :                :  * is a copy of the length --- so the total tape space used is actually
                                415                 :                :  * sizeof(unsigned int) more than the stored length value.  This allows
                                416                 :                :  * read-backwards.  When the random access flag was not specified, the
                                417                 :                :  * write/read routines may omit the extra length word.
                                418                 :                :  *
                                419                 :                :  * writetup is expected to write both length words as well as the tuple
                                420                 :                :  * data.  When readtup is called, the tape is positioned just after the
                                421                 :                :  * front length word; readtup must read the tuple data and advance past
                                422                 :                :  * the back length word (if present).
                                423                 :                :  *
                                424                 :                :  * The write/read routines can make use of the tuple description data
                                425                 :                :  * stored in the Tuplesortstate record, if needed.  They are also expected
                                426                 :                :  * to adjust state->availMem by the amount of memory space (not tape space!)
                                427                 :                :  * released or consumed.  There is no error return from either writetup
                                428                 :                :  * or readtup; they should ereport() on failure.
                                429                 :                :  *
                                430                 :                :  *
                                431                 :                :  * NOTES about memory consumption calculations:
                                432                 :                :  *
                                433                 :                :  * We count space allocated for tuples against the workMem limit, plus
                                434                 :                :  * the space used by the variable-size memtuples array.  Fixed-size space
                                435                 :                :  * is not counted; it's small enough to not be interesting.
                                436                 :                :  *
                                437                 :                :  * Note that we count actual space used (as shown by GetMemoryChunkSpace)
                                438                 :                :  * rather than the originally-requested size.  This is important since
                                439                 :                :  * palloc can add substantial overhead.  It's not a complete answer since
                                440                 :                :  * we won't count any wasted space in palloc allocation blocks, but it's
                                441                 :                :  * a lot better than what we were doing before 7.3.  As of 9.6, a
                                442                 :                :  * separate memory context is used for caller passed tuples.  Resetting
                                443                 :                :  * it at certain key increments significantly ameliorates fragmentation.
                                444                 :                :  * readtup routines use the slab allocator (they cannot use
                                445                 :                :  * the reset context because it gets deleted at the point that merging
                                446                 :                :  * begins).
                                447                 :                :  */
                                448                 :                : 
                                449                 :                : 
                                450                 :                : static void tuplesort_begin_batch(Tuplesortstate *state);
                                451                 :                : static bool consider_abort_common(Tuplesortstate *state);
                                452                 :                : static void inittapes(Tuplesortstate *state, bool mergeruns);
                                453                 :                : static void inittapestate(Tuplesortstate *state, int maxTapes);
                                454                 :                : static void selectnewtape(Tuplesortstate *state);
                                455                 :                : static void init_slab_allocator(Tuplesortstate *state, int numSlots);
                                456                 :                : static void mergeruns(Tuplesortstate *state);
                                457                 :                : static void mergeonerun(Tuplesortstate *state);
                                458                 :                : static void beginmerge(Tuplesortstate *state);
                                459                 :                : static bool mergereadnext(Tuplesortstate *state, LogicalTape *srcTape, SortTuple *stup);
                                460                 :                : static void dumptuples(Tuplesortstate *state, bool alltuples);
                                461                 :                : static void make_bounded_heap(Tuplesortstate *state);
                                462                 :                : static void sort_bounded_heap(Tuplesortstate *state);
                                463                 :                : static void tuplesort_sort_memtuples(Tuplesortstate *state);
                                464                 :                : static void tuplesort_heap_insert(Tuplesortstate *state, SortTuple *tuple);
                                465                 :                : static void tuplesort_heap_replace_top(Tuplesortstate *state, SortTuple *tuple);
                                466                 :                : static void tuplesort_heap_delete_top(Tuplesortstate *state);
                                467                 :                : static void reversedirection(Tuplesortstate *state);
                                468                 :                : static unsigned int getlen(LogicalTape *tape, bool eofOK);
                                469                 :                : static void markrunend(LogicalTape *tape);
                                470                 :                : static int  worker_get_identifier(Tuplesortstate *state);
                                471                 :                : static void worker_freeze_result_tape(Tuplesortstate *state);
                                472                 :                : static void worker_nomergeruns(Tuplesortstate *state);
                                473                 :                : static void leader_takeover_tapes(Tuplesortstate *state);
                                474                 :                : static void free_sort_tuple(Tuplesortstate *state, SortTuple *stup);
                                475                 :                : static void tuplesort_free(Tuplesortstate *state);
                                476                 :                : static void tuplesort_updatemax(Tuplesortstate *state);
                                477                 :                : 
                                478                 :                : 
                                479                 :                : /*
                                480                 :                :  * Special versions of qsort just for SortTuple objects.  qsort_tuple() sorts
                                481                 :                :  * any variant of SortTuples, using the appropriate comparetup function.
                                482                 :                :  * qsort_ssup() is specialized for the case where the comparetup function
                                483                 :                :  * reduces to ApplySortComparator(), that is single-key MinimalTuple sorts
                                484                 :                :  * and Datum sorts.
                                485                 :                :  */
                                486                 :                : 
                                487                 :                : #define ST_SORT qsort_tuple
                                488                 :                : #define ST_ELEMENT_TYPE SortTuple
                                489                 :                : #define ST_COMPARE_RUNTIME_POINTER
                                490                 :                : #define ST_COMPARE_ARG_TYPE Tuplesortstate
                                491                 :                : #define ST_CHECK_FOR_INTERRUPTS
                                492                 :                : #define ST_SCOPE static
                                493                 :                : #define ST_DECLARE
                                494                 :                : #define ST_DEFINE
                                495                 :                : #include "lib/sort_template.h"
                                496                 :                : 
                                497                 :                : #define ST_SORT qsort_ssup
                                498                 :                : #define ST_ELEMENT_TYPE SortTuple
                                499                 :                : #define ST_COMPARE(a, b, ssup) \
                                500                 :                :     ApplySortComparator((a)->datum1, (a)->isnull1, \
                                501                 :                :                         (b)->datum1, (b)->isnull1, (ssup))
                                502                 :                : #define ST_COMPARE_ARG_TYPE SortSupportData
                                503                 :                : #define ST_CHECK_FOR_INTERRUPTS
                                504                 :                : #define ST_SCOPE static
                                505                 :                : #define ST_DEFINE
                                506                 :                : #include "lib/sort_template.h"
                                507                 :                : 
                                508                 :                : /* state for radix sort */
                                509                 :                : typedef struct RadixSortInfo
                                510                 :                : {
                                511                 :                :     union
                                512                 :                :     {
                                513                 :                :         size_t      count;
                                514                 :                :         size_t      offset;
                                515                 :                :     };
                                516                 :                :     size_t      next_offset;
                                517                 :                : } RadixSortInfo;
                                518                 :                : 
                                519                 :                : /*
                                520                 :                :  * Threshold below which qsort_tuple() is generally faster than a radix sort.
                                521                 :                :  */
                                522                 :                : #define QSORT_THRESHOLD 40
                                523                 :                : 
                                524                 :                : 
                                525                 :                : /*
                                526                 :                :  *      tuplesort_begin_xxx
                                527                 :                :  *
                                528                 :                :  * Initialize for a tuple sort operation.
                                529                 :                :  *
                                530                 :                :  * After calling tuplesort_begin, the caller should call tuplesort_putXXX
                                531                 :                :  * zero or more times, then call tuplesort_performsort when all the tuples
                                532                 :                :  * have been supplied.  After performsort, retrieve the tuples in sorted
                                533                 :                :  * order by calling tuplesort_getXXX until it returns false/NULL.  (If random
                                534                 :                :  * access was requested, rescan, markpos, and restorepos can also be called.)
                                535                 :                :  * Call tuplesort_end to terminate the operation and release memory/disk space.
                                536                 :                :  *
                                537                 :                :  * Each variant of tuplesort_begin has a workMem parameter specifying the
                                538                 :                :  * maximum number of kilobytes of RAM to use before spilling data to disk.
                                539                 :                :  * (The normal value of this parameter is work_mem, but some callers use
                                540                 :                :  * other values.)  Each variant also has a sortopt which is a bitmask of
                                541                 :                :  * sort options.  See TUPLESORT_* definitions in tuplesort.h
                                542                 :                :  */
                                543                 :                : 
                                544                 :                : Tuplesortstate *
 1699 drowley@postgresql.o      545                 :CBC      174383 : tuplesort_begin_common(int workMem, SortCoordinate coordinate, int sortopt)
                                546                 :                : {
                                547                 :                :     Tuplesortstate *state;
                                548                 :                :     MemoryContext maincontext;
                                549                 :                :     MemoryContext sortcontext;
                                550                 :                :     MemoryContext oldcontext;
                                551                 :                : 
                                552                 :                :     /* See leader_takeover_tapes() remarks on random access support */
                                553   [ +  +  -  + ]:         174383 :     if (coordinate && (sortopt & TUPLESORT_RANDOMACCESS))
 3221 rhaas@postgresql.org      554         [ #  # ]:UBC           0 :         elog(ERROR, "random access disallowed under parallel sort");
                                555                 :                : 
                                556                 :                :     /*
                                557                 :                :      * Memory context surviving tuplesort_reset.  This memory context holds
                                558                 :                :      * data which is useful to keep while sorting multiple similar batches.
                                559                 :                :      */
 2427 tomas.vondra@postgre      560                 :CBC      174383 :     maincontext = AllocSetContextCreate(CurrentMemoryContext,
                                561                 :                :                                         "TupleSort main",
                                562                 :                :                                         ALLOCSET_DEFAULT_SIZES);
                                563                 :                : 
                                564                 :                :     /*
                                565                 :                :      * Create a working memory context for one sort operation.  The content of
                                566                 :                :      * this context is deleted by tuplesort_reset.
                                567                 :                :      */
                                568                 :         174383 :     sortcontext = AllocSetContextCreate(maincontext,
                                569                 :                :                                         "TupleSort sort",
                                570                 :                :                                         ALLOCSET_DEFAULT_SIZES);
                                571                 :                : 
                                572                 :                :     /*
                                573                 :                :      * Additionally a working memory context for tuples is setup in
                                574                 :                :      * tuplesort_begin_batch.
                                575                 :                :      */
                                576                 :                : 
                                577                 :                :     /*
                                578                 :                :      * Make the Tuplesortstate within the per-sortstate context.  This way, we
                                579                 :                :      * don't need a separate pfree() operation for it at shutdown.
                                580                 :                :      */
                                581                 :         174383 :     oldcontext = MemoryContextSwitchTo(maincontext);
                                582                 :                : 
  353 michael@paquier.xyz       583                 :         174383 :     state = palloc0_object(Tuplesortstate);
                                584                 :                : 
 7726 tgl@sss.pgh.pa.us         585         [ -  + ]:         174383 :     if (trace_sort)
 7726 tgl@sss.pgh.pa.us         586                 :UBC           0 :         pg_rusage_init(&state->ru_start);
                                587                 :                : 
 1585 akorotkov@postgresql      588                 :CBC      174383 :     state->base.sortopt = sortopt;
                                589                 :         174383 :     state->base.tuples = true;
                                590                 :         174383 :     state->abbrevNext = 10;
                                591                 :                : 
                                592                 :                :     /*
                                593                 :                :      * workMem is forced to be at least 64KB, the current minimum valid value
                                594                 :                :      * for the work_mem GUC.  This is a defense against parallel sort callers
                                595                 :                :      * that divide out memory among many workers in a way that leaves each
                                596                 :                :      * with very little memory.
                                597                 :                :      */
 3221 rhaas@postgresql.org      598                 :         174383 :     state->allowedMem = Max(workMem, 64) * (int64) 1024;
 1585 akorotkov@postgresql      599                 :         174383 :     state->base.sortcontext = sortcontext;
                                600                 :         174383 :     state->base.maincontext = maincontext;
                                601                 :                : 
 2427 tomas.vondra@postgre      602                 :         174383 :     state->memtupsize = INITIAL_MEMTUPSIZE;
                                603                 :         174383 :     state->memtuples = NULL;
                                604                 :                : 
                                605                 :                :     /*
                                606                 :                :      * After all of the other non-parallel-related state, we setup all of the
                                607                 :                :      * state needed for each batch.
                                608                 :                :      */
                                609                 :         174383 :     tuplesort_begin_batch(state);
                                610                 :                : 
                                611                 :                :     /*
                                612                 :                :      * Initialize parallel-related state based on coordination information
                                613                 :                :      * from caller
                                614                 :                :      */
 3221 rhaas@postgresql.org      615         [ +  + ]:         174383 :     if (!coordinate)
                                616                 :                :     {
                                617                 :                :         /* Serial sort */
                                618                 :         173817 :         state->shared = NULL;
                                619                 :         173817 :         state->worker = -1;
                                620                 :         173817 :         state->nParticipants = -1;
                                621                 :                :     }
                                622         [ +  + ]:            566 :     else if (coordinate->isWorker)
                                623                 :                :     {
                                624                 :                :         /* Parallel worker produces exactly one final run from all input */
                                625                 :            385 :         state->shared = coordinate->sharedsort;
                                626                 :            385 :         state->worker = worker_get_identifier(state);
                                627                 :            385 :         state->nParticipants = -1;
                                628                 :                :     }
                                629                 :                :     else
                                630                 :                :     {
                                631                 :                :         /* Parallel leader state only used for final merge */
                                632                 :            181 :         state->shared = coordinate->sharedsort;
                                633                 :            181 :         state->worker = -1;
                                634                 :            181 :         state->nParticipants = coordinate->nParticipants;
                                635         [ -  + ]:            181 :         Assert(state->nParticipants >= 1);
                                636                 :                :     }
                                637                 :                : 
 7580 tgl@sss.pgh.pa.us         638                 :         174383 :     MemoryContextSwitchTo(oldcontext);
                                639                 :                : 
 9904                           640                 :         174383 :     return state;
                                641                 :                : }
                                642                 :                : 
                                643                 :                : /*
                                644                 :                :  *      tuplesort_begin_batch
                                645                 :                :  *
                                646                 :                :  * Setup, or reset, all state need for processing a new set of tuples with this
                                647                 :                :  * sort state. Called both from tuplesort_begin_common (the first time sorting
                                648                 :                :  * with this sort state) and tuplesort_reset (for subsequent usages).
                                649                 :                :  */
                                650                 :                : static void
 2427 tomas.vondra@postgre      651                 :         176563 : tuplesort_begin_batch(Tuplesortstate *state)
                                652                 :                : {
                                653                 :                :     MemoryContext oldcontext;
                                654                 :                : 
 1585 akorotkov@postgresql      655                 :         176563 :     oldcontext = MemoryContextSwitchTo(state->base.maincontext);
                                656                 :                : 
                                657                 :                :     /*
                                658                 :                :      * Caller tuple (e.g. IndexTuple) memory context.
                                659                 :                :      *
                                660                 :                :      * A dedicated child context used exclusively for caller passed tuples
                                661                 :                :      * eases memory management.  Resetting at key points reduces
                                662                 :                :      * fragmentation. Note that the memtuples array of SortTuples is allocated
                                663                 :                :      * in the parent context, not this context, because there is no need to
                                664                 :                :      * free memtuples early.  For bounded sorts, tuples may be pfreed in any
                                665                 :                :      * order, so we use a regular aset.c context so that it can make use of
                                666                 :                :      * free'd memory.  When the sort is not bounded, we make use of a bump.c
                                667                 :                :      * context as this keeps allocations more compact with less wastage.
                                668                 :                :      * Allocations are also slightly more CPU efficient.
                                669                 :                :      */
  964 drowley@postgresql.o      670         [ +  + ]:         176563 :     if (TupleSortUseBumpTupleCxt(state->base.sortopt))
                                671                 :         175644 :         state->base.tuplecontext = BumpContextCreate(state->base.sortcontext,
                                672                 :                :                                                      "Caller tuples",
                                673                 :                :                                                      ALLOCSET_DEFAULT_SIZES);
                                674                 :                :     else
 1585 akorotkov@postgresql      675                 :            919 :         state->base.tuplecontext = AllocSetContextCreate(state->base.sortcontext,
                                676                 :                :                                                          "Caller tuples",
                                677                 :                :                                                          ALLOCSET_DEFAULT_SIZES);
                                678                 :                : 
                                679                 :                : 
 2427 tomas.vondra@postgre      680                 :         176563 :     state->status = TSS_INITIAL;
                                681                 :         176563 :     state->bounded = false;
                                682                 :         176563 :     state->boundUsed = false;
                                683                 :                : 
                                684                 :         176563 :     state->availMem = state->allowedMem;
                                685                 :                : 
                                686                 :         176563 :     state->tapeset = NULL;
                                687                 :                : 
                                688                 :         176563 :     state->memtupcount = 0;
                                689                 :                : 
                                690                 :         176563 :     state->growmemtuples = true;
                                691                 :         176563 :     state->slabAllocatorUsed = false;
                                692   [ +  +  +  + ]:         176563 :     if (state->memtuples != NULL && state->memtupsize != INITIAL_MEMTUPSIZE)
                                693                 :                :     {
                                694                 :             96 :         pfree(state->memtuples);
                                695                 :             96 :         state->memtuples = NULL;
                                696                 :             96 :         state->memtupsize = INITIAL_MEMTUPSIZE;
                                697                 :                :     }
                                698         [ +  + ]:         176563 :     if (state->memtuples == NULL)
                                699                 :                :     {
  103 michael@paquier.xyz       700                 :GNC      174479 :         state->memtuples = palloc_array(SortTuple, state->memtupsize);
 2427 tomas.vondra@postgre      701                 :CBC      174479 :         USEMEM(state, GetMemoryChunkSpace(state->memtuples));
                                702                 :                :     }
                                703                 :                : 
                                704                 :                :     /* workMem must be large enough for the minimal memtuples array */
                                705   [ -  +  -  - ]:         176563 :     if (LACKMEM(state))
 2427 tomas.vondra@postgre      706         [ #  # ]:UBC           0 :         elog(ERROR, "insufficient memory allowed for sort");
                                707                 :                : 
 2427 tomas.vondra@postgre      708                 :CBC      176563 :     state->currentRun = 0;
                                709                 :                : 
                                710                 :                :     /*
                                711                 :                :      * Tape variables (inputTapes, outputTapes, etc.) will be initialized by
                                712                 :                :      * inittapes(), if needed.
                                713                 :                :      */
                                714                 :                : 
 1867 heikki.linnakangas@i      715                 :         176563 :     state->result_tape = NULL;   /* flag that result tape has not been formed */
                                716                 :                : 
 2427 tomas.vondra@postgre      717                 :         176563 :     MemoryContextSwitchTo(oldcontext);
                                718                 :         176563 : }
                                719                 :                : 
                                720                 :                : /*
                                721                 :                :  * tuplesort_set_bound
                                722                 :                :  *
                                723                 :                :  *  Advise tuplesort that at most the first N result tuples are required.
                                724                 :                :  *
                                725                 :                :  * Must be called before inserting any tuples.  (Actually, we could allow it
                                726                 :                :  * as long as the sort hasn't spilled to disk, but there seems no need for
                                727                 :                :  * delayed calls at the moment.)
                                728                 :                :  *
                                729                 :                :  * This is a hint only. The tuplesort may still return more tuples than
                                730                 :                :  * requested.  Parallel leader tuplesorts will always ignore the hint.
                                731                 :                :  */
                                732                 :                : void
 7148 tgl@sss.pgh.pa.us         733                 :            822 : tuplesort_set_bound(Tuplesortstate *state, int64 bound)
                                734                 :                : {
                                735                 :                :     /* Assert we're called before loading any tuples */
 2634 alvherre@alvh.no-ip.      736   [ +  -  -  + ]:            822 :     Assert(state->status == TSS_INITIAL && state->memtupcount == 0);
                                737                 :                :     /* Assert we allow bounded sorts */
 1585 akorotkov@postgresql      738         [ -  + ]:            822 :     Assert(state->base.sortopt & TUPLESORT_ALLOWBOUNDED);
                                739                 :                :     /* Can't set the bound twice, either */
 7148 tgl@sss.pgh.pa.us         740         [ -  + ]:            822 :     Assert(!state->bounded);
                                741                 :                :     /* Also, this shouldn't be called in a parallel worker */
 3221 rhaas@postgresql.org      742   [ -  +  -  - ]:            822 :     Assert(!WORKER(state));
                                743                 :                : 
                                744                 :                :     /* Parallel leader allows but ignores hint */
 2633 tgl@sss.pgh.pa.us         745   [ -  +  -  - ]:            822 :     if (LEADER(state))
 2633 tgl@sss.pgh.pa.us         746                 :UBC           0 :         return;
                                747                 :                : 
                                748                 :                : #ifdef DEBUG_BOUNDED_SORT
                                749                 :                :     /* Honor GUC setting that disables the feature (for easy testing) */
                                750                 :                :     if (!optimize_bounded_sort)
                                751                 :                :         return;
                                752                 :                : #endif
                                753                 :                : 
                                754                 :                :     /* We want to be able to compute bound * 2, so limit the setting */
 6953 bruce@momjian.us          755         [ -  + ]:CBC         822 :     if (bound > (int64) (INT_MAX / 2))
 7148 tgl@sss.pgh.pa.us         756                 :UBC           0 :         return;
                                757                 :                : 
 7148 tgl@sss.pgh.pa.us         758                 :CBC         822 :     state->bounded = true;
                                759                 :            822 :     state->bound = (int) bound;
                                760                 :                : 
                                761                 :                :     /*
                                762                 :                :      * Bounded sorts are not an effective target for abbreviated key
                                763                 :                :      * optimization.  Disable by setting state to be consistent with no
                                764                 :                :      * abbreviation support.
                                765                 :                :      */
 1585 akorotkov@postgresql      766                 :            822 :     state->base.sortKeys->abbrev_converter = NULL;
                                767         [ +  + ]:            822 :     if (state->base.sortKeys->abbrev_full_comparator)
                                768                 :             10 :         state->base.sortKeys->comparator = state->base.sortKeys->abbrev_full_comparator;
                                769                 :                : 
                                770                 :                :     /* Not strictly necessary, but be tidy */
                                771                 :            822 :     state->base.sortKeys->abbrev_abort = NULL;
                                772                 :            822 :     state->base.sortKeys->abbrev_full_comparator = NULL;
                                773                 :                : }
                                774                 :                : 
                                775                 :                : /*
                                776                 :                :  * tuplesort_used_bound
                                777                 :                :  *
                                778                 :                :  * Allow callers to find out if the sort state was able to use a bound.
                                779                 :                :  */
                                780                 :                : bool
 2427 tomas.vondra@postgre      781                 :            327 : tuplesort_used_bound(Tuplesortstate *state)
                                782                 :                : {
                                783                 :            327 :     return state->boundUsed;
                                784                 :                : }
                                785                 :                : 
                                786                 :                : /*
                                787                 :                :  * tuplesort_free
                                788                 :                :  *
                                789                 :                :  *  Internal routine for freeing resources of tuplesort.
                                790                 :                :  */
                                791                 :                : static void
                                792                 :         176358 : tuplesort_free(Tuplesortstate *state)
                                793                 :                : {
                                794                 :                :     /* context swap probably not needed, but let's be safe */
 1585 akorotkov@postgresql      795                 :         176358 :     MemoryContext oldcontext = MemoryContextSwitchTo(state->base.sortcontext);
                                796                 :                :     int64       spaceUsed;
                                797                 :                : 
 9904 tgl@sss.pgh.pa.us         798         [ +  + ]:         176358 :     if (state->tapeset)
 7711                           799                 :            608 :         spaceUsed = LogicalTapeSetBlocks(state->tapeset);
                                800                 :                :     else
                                801                 :         175750 :         spaceUsed = (state->allowedMem - state->availMem + 1023) / 1024;
                                802                 :                : 
                                803                 :                :     /*
                                804                 :                :      * Delete temporary "tape" files, if any.
                                805                 :                :      *
                                806                 :                :      * We don't bother to destroy the individual tapes here. They will go away
                                807                 :                :      * with the sortcontext.  (In TSS_FINALMERGE state, we have closed
                                808                 :                :      * finished tapes already.)
                                809                 :                :      */
 7580                           810         [ +  + ]:         176358 :     if (state->tapeset)
                                811                 :            608 :         LogicalTapeSetClose(state->tapeset);
                                812                 :                : 
 7726                           813         [ -  + ]:         176358 :     if (trace_sort)
                                814                 :                :     {
 7711 tgl@sss.pgh.pa.us         815         [ #  # ]:UBC           0 :         if (state->tapeset)
  609 peter@eisentraut.org      816   [ #  #  #  # ]:              0 :             elog(LOG, "%s of worker %d ended, %" PRId64 " disk blocks used: %s",
                                817                 :                :                  SERIAL(state) ? "external sort" : "parallel external sort",
                                818                 :                :                  state->worker, spaceUsed, pg_rusage_show(&state->ru_start));
                                819                 :                :         else
                                820   [ #  #  #  # ]:              0 :             elog(LOG, "%s of worker %d ended, %" PRId64 " KB used: %s",
                                821                 :                :                  SERIAL(state) ? "internal sort" : "unperformed parallel sort",
                                822                 :                :                  state->worker, spaceUsed, pg_rusage_show(&state->ru_start));
                                823                 :                :     }
                                824                 :                : 
                                825                 :                :     TRACE_POSTGRESQL_SORT_DONE(state->tapeset != NULL, spaceUsed);
                                826                 :                : 
 1585 akorotkov@postgresql      827         [ +  + ]:CBC      176358 :     FREESTATE(state);
 7580 tgl@sss.pgh.pa.us         828                 :         176358 :     MemoryContextSwitchTo(oldcontext);
                                829                 :                : 
                                830                 :                :     /*
                                831                 :                :      * Free the per-sort memory context, thereby releasing all working memory.
                                832                 :                :      */
 1585 akorotkov@postgresql      833                 :         176358 :     MemoryContextReset(state->base.sortcontext);
 2427 tomas.vondra@postgre      834                 :         176358 : }
                                835                 :                : 
                                836                 :                : /*
                                837                 :                :  * tuplesort_end
                                838                 :                :  *
                                839                 :                :  *  Release resources and clean up.
                                840                 :                :  *
                                841                 :                :  * NOTE: after calling this, any pointers returned by tuplesort_getXXX are
                                842                 :                :  * pointing to garbage.  Be careful not to attempt to use or free such
                                843                 :                :  * pointers afterwards!
                                844                 :                :  */
                                845                 :                : void
                                846                 :         174178 : tuplesort_end(Tuplesortstate *state)
                                847                 :                : {
                                848                 :         174178 :     tuplesort_free(state);
                                849                 :                : 
                                850                 :                :     /*
                                851                 :                :      * Free the main memory context, including the Tuplesortstate struct
                                852                 :                :      * itself.
                                853                 :                :      */
 1585 akorotkov@postgresql      854                 :         174178 :     MemoryContextDelete(state->base.maincontext);
 2427 tomas.vondra@postgre      855                 :         174178 : }
                                856                 :                : 
                                857                 :                : /*
                                858                 :                :  * tuplesort_updatemax
                                859                 :                :  *
                                860                 :                :  *  Update maximum resource usage statistics.
                                861                 :                :  */
                                862                 :                : static void
                                863                 :           2444 : tuplesort_updatemax(Tuplesortstate *state)
                                864                 :                : {
                                865                 :                :     int64       spaceUsed;
                                866                 :                :     bool        isSpaceDisk;
                                867                 :                : 
                                868                 :                :     /*
                                869                 :                :      * Note: it might seem we should provide both memory and disk usage for a
                                870                 :                :      * disk-based sort.  However, the current code doesn't track memory space
                                871                 :                :      * accurately once we have begun to return tuples to the caller (since we
                                872                 :                :      * don't account for pfree's the caller is expected to do), so we cannot
                                873                 :                :      * rely on availMem in a disk sort.  This does not seem worth the overhead
                                874                 :                :      * to fix.  Is it worth creating an API for the memory context code to
                                875                 :                :      * tell us how much is actually used in sortcontext?
                                876                 :                :      */
                                877         [ +  + ]:           2444 :     if (state->tapeset)
                                878                 :                :     {
                                879                 :              4 :         isSpaceDisk = true;
                                880                 :              4 :         spaceUsed = LogicalTapeSetBlocks(state->tapeset) * BLCKSZ;
                                881                 :                :     }
                                882                 :                :     else
                                883                 :                :     {
                                884                 :           2440 :         isSpaceDisk = false;
                                885                 :           2440 :         spaceUsed = state->allowedMem - state->availMem;
                                886                 :                :     }
                                887                 :                : 
                                888                 :                :     /*
                                889                 :                :      * Sort evicts data to the disk when it wasn't able to fit that data into
                                890                 :                :      * main memory.  This is why we assume space used on the disk to be more
                                891                 :                :      * important for tracking resource usage than space used in memory. Note
                                892                 :                :      * that the amount of space occupied by some tupleset on the disk might be
                                893                 :                :      * less than amount of space occupied by the same tupleset in memory due
                                894                 :                :      * to more compact representation.
                                895                 :                :      */
                                896   [ +  +  -  + ]:           2444 :     if ((isSpaceDisk && !state->isMaxSpaceDisk) ||
                                897   [ +  -  +  + ]:           2440 :         (isSpaceDisk == state->isMaxSpaceDisk && spaceUsed > state->maxSpace))
                                898                 :                :     {
                                899                 :            366 :         state->maxSpace = spaceUsed;
                                900                 :            366 :         state->isMaxSpaceDisk = isSpaceDisk;
                                901                 :            366 :         state->maxSpaceStatus = state->status;
                                902                 :                :     }
                                903                 :           2444 : }
                                904                 :                : 
                                905                 :                : /*
                                906                 :                :  * tuplesort_reset
                                907                 :                :  *
                                908                 :                :  *  Reset the tuplesort.  Reset all the data in the tuplesort, but leave the
                                909                 :                :  *  meta-information in.  After tuplesort_reset, tuplesort is ready to start
                                910                 :                :  *  a new sort.  This allows avoiding recreation of tuple sort states (and
                                911                 :                :  *  save resources) when sorting multiple small batches.  We also allow the
                                912                 :                :  *  TUPLESORT_ALLOWBOUNDED flag to be set/unset here as the bounded
                                913                 :                :  *  requirements may change between rescans in Incremental Sort, and we use
                                914                 :                :  *  tuplesort_reset() to clear out the tuples ready for that new scan.
                                915                 :                :  */
                                916                 :                : void
   10 drowley@postgresql.o      917                 :GNC        2180 : tuplesort_reset(Tuplesortstate *state, bool allowbounded)
                                918                 :                : {
 2427 tomas.vondra@postgre      919                 :CBC        2180 :     tuplesort_updatemax(state);
                                920                 :           2180 :     tuplesort_free(state);
                                921                 :                : 
                                922                 :                :     /*
                                923                 :                :      * Do this before calling tuplesort_begin_batch() as it's too late to
                                924                 :                :      * change it once the tuplecontext is recreated.
                                925                 :                :      */
   10 drowley@postgresql.o      926         [ +  + ]:GNC        2180 :     if (allowbounded)
                                927                 :            140 :         state->base.sortopt |= TUPLESORT_ALLOWBOUNDED;
                                928                 :                :     else
                                929                 :           2040 :         state->base.sortopt &= ~TUPLESORT_ALLOWBOUNDED;
                                930                 :                : 
                                931                 :                :     /*
                                932                 :                :      * After we've freed up per-batch memory, re-setup all of the state common
                                933                 :                :      * to both the first batch and any subsequent batch.
                                934                 :                :      */
 2427 tomas.vondra@postgre      935                 :CBC        2180 :     tuplesort_begin_batch(state);
                                936                 :                : 
                                937                 :           2180 :     state->lastReturnedTuple = NULL;
                                938                 :           2180 :     state->slabMemoryBegin = NULL;
                                939                 :           2180 :     state->slabMemoryEnd = NULL;
                                940                 :           2180 :     state->slabFreeHead = NULL;
 7580 tgl@sss.pgh.pa.us         941                 :           2180 : }
                                942                 :                : 
                                943                 :                : /*
                                944                 :                :  * Grow the memtuples[] array, if possible within our memory constraint.  We
                                945                 :                :  * must not exceed INT_MAX tuples in memory or the caller-provided memory
                                946                 :                :  * limit.  Return true if we were able to enlarge the array, false if not.
                                947                 :                :  *
                                948                 :                :  * Normally, at each increment we double the size of the array.  When doing
                                949                 :                :  * that would exceed a limit, we attempt one last, smaller increase (and then
                                950                 :                :  * clear the growmemtuples flag so we don't try any more).  That allows us to
                                951                 :                :  * use memory as fully as permitted; sticking to the pure doubling rule could
                                952                 :                :  * result in almost half going unused.  Because availMem moves around with
                                953                 :                :  * tuple addition/removal, we need some rule to prevent making repeated small
                                954                 :                :  * increases in memtupsize, which would just be useless thrashing.  The
                                955                 :                :  * growmemtuples flag accomplishes that and also prevents useless
                                956                 :                :  * recalculations in this function.
                                957                 :                :  */
                                958                 :                : static bool
                                959                 :           5437 : grow_memtuples(Tuplesortstate *state)
                                960                 :                : {
                                961                 :                :     int         newmemtupsize;
 5063                           962                 :           5437 :     int         memtupsize = state->memtupsize;
 4895 noah@leadboat.com         963                 :           5437 :     int64       memNowUsed = state->allowedMem - state->availMem;
                                964                 :                : 
                                965                 :                :     /* Forget it if we've already maxed out memtuples, per comment above */
 5063 tgl@sss.pgh.pa.us         966         [ +  + ]:           5437 :     if (!state->growmemtuples)
                                967                 :             90 :         return false;
                                968                 :                : 
                                969                 :                :     /* Select new value of memtupsize */
                                970         [ +  + ]:           5347 :     if (memNowUsed <= state->availMem)
                                971                 :                :     {
                                972                 :                :         /*
                                973                 :                :          * We've used no more than half of allowedMem; double our usage,
                                974                 :                :          * clamping at INT_MAX tuples.
                                975                 :                :          */
 4902 noah@leadboat.com         976         [ +  - ]:           5256 :         if (memtupsize < INT_MAX / 2)
                                977                 :           5256 :             newmemtupsize = memtupsize * 2;
                                978                 :                :         else
                                979                 :                :         {
 4902 noah@leadboat.com         980                 :UBC           0 :             newmemtupsize = INT_MAX;
                                981                 :              0 :             state->growmemtuples = false;
                                982                 :                :         }
                                983                 :                :     }
                                984                 :                :     else
                                985                 :                :     {
                                986                 :                :         /*
                                987                 :                :          * This will be the last increment of memtupsize.  Abandon doubling
                                988                 :                :          * strategy and instead increase as much as we safely can.
                                989                 :                :          *
                                990                 :                :          * To stay within allowedMem, we can't increase memtupsize by more
                                991                 :                :          * than availMem / sizeof(SortTuple) elements.  In practice, we want
                                992                 :                :          * to increase it by considerably less, because we need to leave some
                                993                 :                :          * space for the tuples to which the new array slots will refer.  We
                                994                 :                :          * assume the new tuples will be about the same size as the tuples
                                995                 :                :          * we've already seen, and thus we can extrapolate from the space
                                996                 :                :          * consumption so far to estimate an appropriate new size for the
                                997                 :                :          * memtuples array.  The optimal value might be higher or lower than
                                998                 :                :          * this estimate, but it's hard to know that in advance.  We again
                                999                 :                :          * clamp at INT_MAX tuples.
                               1000                 :                :          *
                               1001                 :                :          * This calculation is safe against enlarging the array so much that
                               1002                 :                :          * LACKMEM becomes true, because the memory currently used includes
                               1003                 :                :          * the present array; thus, there would be enough allowedMem for the
                               1004                 :                :          * new array elements even if no other memory were currently used.
                               1005                 :                :          *
                               1006                 :                :          * We do the arithmetic in float8, because otherwise the product of
                               1007                 :                :          * memtupsize and allowedMem could overflow.  Any inaccuracy in the
                               1008                 :                :          * result should be insignificant; but even if we computed a
                               1009                 :                :          * completely insane result, the checks below will prevent anything
                               1010                 :                :          * really bad from happening.
                               1011                 :                :          */
                               1012                 :                :         double      grow_ratio;
                               1013                 :                : 
 5063 tgl@sss.pgh.pa.us        1014                 :CBC          91 :         grow_ratio = (double) state->allowedMem / (double) memNowUsed;
 4902 noah@leadboat.com        1015         [ +  - ]:             91 :         if (memtupsize * grow_ratio < INT_MAX)
                               1016                 :             91 :             newmemtupsize = (int) (memtupsize * grow_ratio);
                               1017                 :                :         else
 4902 noah@leadboat.com        1018                 :UBC           0 :             newmemtupsize = INT_MAX;
                               1019                 :                : 
                               1020                 :                :         /* We won't make any further enlargement attempts */
 5063 tgl@sss.pgh.pa.us        1021                 :CBC          91 :         state->growmemtuples = false;
                               1022                 :                :     }
                               1023                 :                : 
                               1024                 :                :     /* Must enlarge array by at least one element, else report failure */
                               1025         [ -  + ]:           5347 :     if (newmemtupsize <= memtupsize)
 5063 tgl@sss.pgh.pa.us        1026                 :UBC           0 :         goto noalloc;
                               1027                 :                : 
                               1028                 :                :     /*
                               1029                 :                :      * On a 32-bit machine, allowedMem could exceed MaxAllocHugeSize.  Clamp
                               1030                 :                :      * to ensure our request won't be rejected.  Note that we can easily
                               1031                 :                :      * exhaust address space before facing this outcome.  (This is presently
                               1032                 :                :      * impossible due to guc.c's MAX_KILOBYTES limitation on work_mem, but
                               1033                 :                :      * don't rely on that at this distance.)
                               1034                 :                :      */
 4902 noah@leadboat.com        1035         [ -  + ]:CBC        5347 :     if ((Size) newmemtupsize >= MaxAllocHugeSize / sizeof(SortTuple))
                               1036                 :                :     {
 4902 noah@leadboat.com        1037                 :UBC           0 :         newmemtupsize = (int) (MaxAllocHugeSize / sizeof(SortTuple));
 5063 tgl@sss.pgh.pa.us        1038                 :              0 :         state->growmemtuples = false;    /* can't grow any more */
                               1039                 :                :     }
                               1040                 :                : 
                               1041                 :                :     /*
                               1042                 :                :      * We need to be sure that we do not cause LACKMEM to become true, else
                               1043                 :                :      * the space management algorithm will go nuts.  The code above should
                               1044                 :                :      * never generate a dangerous request, but to be safe, check explicitly
                               1045                 :                :      * that the array growth fits within availMem.  (We could still cause
                               1046                 :                :      * LACKMEM if the memory chunk overhead associated with the memtuples
                               1047                 :                :      * array were to increase.  That shouldn't happen because we chose the
                               1048                 :                :      * initial array size large enough to ensure that palloc will be treating
                               1049                 :                :      * both old and new arrays as separate chunks.  But we'll check LACKMEM
                               1050                 :                :      * explicitly below just in case.)
                               1051                 :                :      */
 4895 noah@leadboat.com        1052         [ -  + ]:CBC        5347 :     if (state->availMem < (int64) ((newmemtupsize - memtupsize) * sizeof(SortTuple)))
 5063 tgl@sss.pgh.pa.us        1053                 :UBC           0 :         goto noalloc;
                               1054                 :                : 
                               1055                 :                :     /* OK, do it */
 7580 tgl@sss.pgh.pa.us        1056                 :CBC        5347 :     FREEMEM(state, GetMemoryChunkSpace(state->memtuples));
 5063                          1057                 :           5347 :     state->memtupsize = newmemtupsize;
 7580                          1058                 :           5347 :     state->memtuples = (SortTuple *)
 4902 noah@leadboat.com        1059                 :           5347 :         repalloc_huge(state->memtuples,
                               1060                 :           5347 :                       state->memtupsize * sizeof(SortTuple));
 7580 tgl@sss.pgh.pa.us        1061                 :           5347 :     USEMEM(state, GetMemoryChunkSpace(state->memtuples));
                               1062   [ -  +  -  - ]:           5347 :     if (LACKMEM(state))
 4134 tgl@sss.pgh.pa.us        1063         [ #  # ]:UBC           0 :         elog(ERROR, "unexpected out-of-memory situation in tuplesort");
 7580 tgl@sss.pgh.pa.us        1064                 :CBC        5347 :     return true;
                               1065                 :                : 
 5063 tgl@sss.pgh.pa.us        1066                 :UBC           0 : noalloc:
                               1067                 :                :     /* If for any reason we didn't realloc, shut off future attempts */
                               1068                 :              0 :     state->growmemtuples = false;
                               1069                 :              0 :     return false;
                               1070                 :                : }
                               1071                 :                : 
                               1072                 :                : /*
                               1073                 :                :  * Shared code for tuple and datum cases.
                               1074                 :                :  */
                               1075                 :                : void
  964 drowley@postgresql.o     1076                 :CBC    19534312 : tuplesort_puttuple_common(Tuplesortstate *state, SortTuple *tuple,
                               1077                 :                :                           bool useAbbrev, Size tuplen)
                               1078                 :                : {
 1585 akorotkov@postgresql     1079                 :       19534312 :     MemoryContext oldcontext = MemoryContextSwitchTo(state->base.sortcontext);
                               1080                 :                : 
 3221 rhaas@postgresql.org     1081   [ +  +  -  + ]:       19534312 :     Assert(!LEADER(state));
                               1082                 :                : 
                               1083                 :                :     /* account for the memory used for this tuple */
  964 drowley@postgresql.o     1084                 :       19534312 :     USEMEM(state, tuplen);
                               1085                 :       19534312 :     state->tupleMem += tuplen;
                               1086                 :                : 
 1585 akorotkov@postgresql     1087         [ +  + ]:       19534312 :     if (!useAbbrev)
                               1088                 :                :     {
                               1089                 :                :         /*
                               1090                 :                :          * Leave ordinary Datum representation, or NULL value.  If there is a
                               1091                 :                :          * converter it won't expect NULL values, and cost model is not
                               1092                 :                :          * required to account for NULL, so in that case we avoid calling
                               1093                 :                :          * converter and just set datum1 to zeroed representation (to be
                               1094                 :                :          * consistent, and to support cheap inequality tests for NULL
                               1095                 :                :          * abbreviated keys).
                               1096                 :                :          */
                               1097                 :                :     }
                               1098         [ +  + ]:        2901661 :     else if (!consider_abort_common(state))
                               1099                 :                :     {
                               1100                 :                :         /* Store abbreviated key representation */
                               1101                 :        2901597 :         tuple->datum1 = state->base.sortKeys->abbrev_converter(tuple->datum1,
                               1102                 :                :                                                                state->base.sortKeys);
                               1103                 :                :     }
                               1104                 :                :     else
                               1105                 :                :     {
                               1106                 :                :         /*
                               1107                 :                :          * Set state to be consistent with never trying abbreviation.
                               1108                 :                :          *
                               1109                 :                :          * Alter datum1 representation in already-copied tuples, so as to
                               1110                 :                :          * ensure a consistent representation (current tuple was just
                               1111                 :                :          * handled).  It does not matter if some dumped tuples are already
                               1112                 :                :          * sorted on tape, since serialized tuples lack abbreviated keys
                               1113                 :                :          * (TSS_BUILDRUNS state prevents control reaching here in any case).
                               1114                 :                :          */
                               1115                 :             64 :         REMOVEABBREV(state, state->memtuples, state->memtupcount);
                               1116                 :                :     }
                               1117                 :                : 
 9904 tgl@sss.pgh.pa.us        1118   [ +  +  +  - ]:       19534312 :     switch (state->status)
                               1119                 :                :     {
 9165 bruce@momjian.us         1120                 :       16624182 :         case TSS_INITIAL:
                               1121                 :                : 
                               1122                 :                :             /*
                               1123                 :                :              * Save the tuple into the unsorted array.  First, grow the array
                               1124                 :                :              * as needed.  Note that we try to grow the array when there is
                               1125                 :                :              * still one free slot remaining --- if we fail, there'll still be
                               1126                 :                :              * room to store the incoming tuple, and then we'll switch to
                               1127                 :                :              * tape-based operation.
                               1128                 :                :              */
 7580 tgl@sss.pgh.pa.us        1129         [ +  + ]:       16624182 :             if (state->memtupcount >= state->memtupsize - 1)
                               1130                 :                :             {
                               1131                 :           5437 :                 (void) grow_memtuples(state);
                               1132         [ -  + ]:           5437 :                 Assert(state->memtupcount < state->memtupsize);
                               1133                 :                :             }
                               1134                 :       16624182 :             state->memtuples[state->memtupcount++] = *tuple;
                               1135                 :                : 
                               1136                 :                :             /*
                               1137                 :                :              * Check if it's time to switch over to a bounded heapsort. We do
                               1138                 :                :              * so if the input tuple count exceeds twice the desired tuple
                               1139                 :                :              * count (this is a heuristic for where heapsort becomes cheaper
                               1140                 :                :              * than a quicksort), or if we've just filled workMem and have
                               1141                 :                :              * enough tuples to meet the bound.
                               1142                 :                :              *
                               1143                 :                :              * Note that once we enter TSS_BOUNDED state we will always try to
                               1144                 :                :              * complete the sort that way.  In the worst case, if later input
                               1145                 :                :              * tuples are larger than earlier ones, this might cause us to
                               1146                 :                :              * exceed workMem significantly.
                               1147                 :                :              */
 7148                          1148         [ +  + ]:       16624182 :             if (state->bounded &&
                               1149         [ +  + ]:          46765 :                 (state->memtupcount > state->bound * 2 ||
                               1150   [ +  +  -  +  :          46488 :                  (state->memtupcount > state->bound && LACKMEM(state))))
                                              -  - ]
                               1151                 :                :             {
                               1152         [ -  + ]:            277 :                 if (trace_sort)
 7148 tgl@sss.pgh.pa.us        1153         [ #  # ]:UBC           0 :                     elog(LOG, "switching to bounded heapsort at %d tuples: %s",
                               1154                 :                :                          state->memtupcount,
                               1155                 :                :                          pg_rusage_show(&state->ru_start));
 7148 tgl@sss.pgh.pa.us        1156                 :CBC         277 :                 make_bounded_heap(state);
 1585 akorotkov@postgresql     1157                 :            277 :                 MemoryContextSwitchTo(oldcontext);
 7148 tgl@sss.pgh.pa.us        1158                 :            277 :                 return;
                               1159                 :                :             }
                               1160                 :                : 
                               1161                 :                :             /*
                               1162                 :                :              * Done if we still fit in available memory and have array slots.
                               1163                 :                :              */
 7580                          1164   [ +  +  -  +  :       16623905 :             if (state->memtupcount < state->memtupsize && !LACKMEM(state))
                                              -  - ]
                               1165                 :                :             {
 1585 akorotkov@postgresql     1166                 :       16623815 :                 MemoryContextSwitchTo(oldcontext);
 9904 tgl@sss.pgh.pa.us        1167                 :       16623815 :                 return;
                               1168                 :                :             }
                               1169                 :                : 
                               1170                 :                :             /*
                               1171                 :                :              * Nope; time to switch to tape-based operation.
                               1172                 :                :              */
 3221 rhaas@postgresql.org     1173                 :             90 :             inittapes(state, true);
                               1174                 :                : 
                               1175                 :                :             /*
                               1176                 :                :              * Dump all tuples.
                               1177                 :                :              */
 9904 tgl@sss.pgh.pa.us        1178                 :             90 :             dumptuples(state, false);
                               1179                 :             90 :             break;
                               1180                 :                : 
 7148                          1181                 :        2139127 :         case TSS_BOUNDED:
                               1182                 :                : 
                               1183                 :                :             /*
                               1184                 :                :              * We don't want to grow the array here, so check whether the new
                               1185                 :                :              * tuple can be discarded before putting it in.  This should be a
                               1186                 :                :              * good speed optimization, too, since when there are many more
                               1187                 :                :              * input tuples than the bound, most input tuples can be discarded
                               1188                 :                :              * with just this one comparison.  Note that because we currently
                               1189                 :                :              * have the sort direction reversed, we must check for <= not >=.
                               1190                 :                :              */
                               1191         [ +  + ]:        2139127 :             if (COMPARETUP(state, tuple, &state->memtuples[0]) <= 0)
                               1192                 :                :             {
                               1193                 :                :                 /* new tuple <= top of the heap, so we can discard it */
                               1194                 :        1804573 :                 free_sort_tuple(state, tuple);
 5366 rhaas@postgresql.org     1195         [ +  + ]:        1804573 :                 CHECK_FOR_INTERRUPTS();
                               1196                 :                :             }
                               1197                 :                :             else
                               1198                 :                :             {
                               1199                 :                :                 /* discard top of heap, replacing it with the new tuple */
 7148 tgl@sss.pgh.pa.us        1200                 :         334554 :                 free_sort_tuple(state, &state->memtuples[0]);
 3347 rhaas@postgresql.org     1201                 :         334554 :                 tuplesort_heap_replace_top(state, tuple);
                               1202                 :                :             }
 7148 tgl@sss.pgh.pa.us        1203                 :        2139127 :             break;
                               1204                 :                : 
 9904                          1205                 :         771003 :         case TSS_BUILDRUNS:
                               1206                 :                : 
                               1207                 :                :             /*
                               1208                 :                :              * Save the tuple into the unsorted array (there must be space)
                               1209                 :                :              */
 3347 rhaas@postgresql.org     1210                 :         771003 :             state->memtuples[state->memtupcount++] = *tuple;
                               1211                 :                : 
                               1212                 :                :             /*
                               1213                 :                :              * If we are over the memory limit, dump all tuples.
                               1214                 :                :              */
 9904 tgl@sss.pgh.pa.us        1215                 :         771003 :             dumptuples(state, false);
                               1216                 :         771003 :             break;
                               1217                 :                : 
 9904 tgl@sss.pgh.pa.us        1218                 :UBC           0 :         default:
 8527                          1219         [ #  # ]:              0 :             elog(ERROR, "invalid tuplesort state");
                               1220                 :                :             break;
                               1221                 :                :     }
 1585 akorotkov@postgresql     1222                 :CBC     2910220 :     MemoryContextSwitchTo(oldcontext);
                               1223                 :                : }
                               1224                 :                : 
                               1225                 :                : static bool
 4331 rhaas@postgresql.org     1226                 :        2901661 : consider_abort_common(Tuplesortstate *state)
                               1227                 :                : {
 1585 akorotkov@postgresql     1228         [ -  + ]:        2901661 :     Assert(state->base.sortKeys[0].abbrev_converter != NULL);
                               1229         [ -  + ]:        2901661 :     Assert(state->base.sortKeys[0].abbrev_abort != NULL);
                               1230         [ -  + ]:        2901661 :     Assert(state->base.sortKeys[0].abbrev_full_comparator != NULL);
                               1231                 :                : 
                               1232                 :                :     /*
                               1233                 :                :      * Check effectiveness of abbreviation optimization.  Consider aborting
                               1234                 :                :      * when still within memory limit.
                               1235                 :                :      */
 4331 rhaas@postgresql.org     1236         [ +  + ]:        2901661 :     if (state->status == TSS_INITIAL &&
                               1237         [ +  + ]:        2575046 :         state->memtupcount >= state->abbrevNext)
                               1238                 :                :     {
                               1239                 :           3249 :         state->abbrevNext *= 2;
                               1240                 :                : 
                               1241                 :                :         /*
                               1242                 :                :          * Check opclass-supplied abbreviation abort routine.  It may indicate
                               1243                 :                :          * that abbreviation should not proceed.
                               1244                 :                :          */
 1585 akorotkov@postgresql     1245         [ +  + ]:           3249 :         if (!state->base.sortKeys->abbrev_abort(state->memtupcount,
                               1246                 :                :                                                 state->base.sortKeys))
 4331 rhaas@postgresql.org     1247                 :           3185 :             return false;
                               1248                 :                : 
                               1249                 :                :         /*
                               1250                 :                :          * Finally, restore authoritative comparator, and indicate that
                               1251                 :                :          * abbreviation is not in play by setting abbrev_converter to NULL
                               1252                 :                :          */
 1585 akorotkov@postgresql     1253                 :             64 :         state->base.sortKeys[0].comparator = state->base.sortKeys[0].abbrev_full_comparator;
                               1254                 :             64 :         state->base.sortKeys[0].abbrev_converter = NULL;
                               1255                 :                :         /* Not strictly necessary, but be tidy */
                               1256                 :             64 :         state->base.sortKeys[0].abbrev_abort = NULL;
                               1257                 :             64 :         state->base.sortKeys[0].abbrev_full_comparator = NULL;
                               1258                 :                : 
                               1259                 :                :         /* Give up - expect original pass-by-value representation */
 4331 rhaas@postgresql.org     1260                 :             64 :         return true;
                               1261                 :                :     }
                               1262                 :                : 
                               1263                 :        2898412 :     return false;
                               1264                 :                : }
                               1265                 :                : 
                               1266                 :                : /*
                               1267                 :                :  * All tuples have been provided; finish the sort.
                               1268                 :                :  */
                               1269                 :                : void
 9904 tgl@sss.pgh.pa.us        1270                 :         149986 : tuplesort_performsort(Tuplesortstate *state)
                               1271                 :                : {
 1585 akorotkov@postgresql     1272                 :         149986 :     MemoryContext oldcontext = MemoryContextSwitchTo(state->base.sortcontext);
                               1273                 :                : 
 7726 tgl@sss.pgh.pa.us        1274         [ -  + ]:         149986 :     if (trace_sort)
 2949 pg@bowt.ie               1275         [ #  # ]:UBC           0 :         elog(LOG, "performsort of worker %d starting: %s",
                               1276                 :                :              state->worker, pg_rusage_show(&state->ru_start));
                               1277                 :                : 
 9904 tgl@sss.pgh.pa.us        1278   [ +  +  +  - ]:CBC      149986 :     switch (state->status)
                               1279                 :                :     {
 9165 bruce@momjian.us         1280                 :         149619 :         case TSS_INITIAL:
                               1281                 :                : 
                               1282                 :                :             /*
                               1283                 :                :              * We were able to accumulate all the tuples within the allowed
                               1284                 :                :              * amount of memory, or leader to take over worker tapes
                               1285                 :                :              */
 3221 rhaas@postgresql.org     1286         [ +  + ]:         149619 :             if (SERIAL(state))
                               1287                 :                :             {
                               1288                 :                :                 /* Sort in memory and we're done */
                               1289                 :         149101 :                 tuplesort_sort_memtuples(state);
                               1290                 :         149040 :                 state->status = TSS_SORTEDINMEM;
                               1291                 :                :             }
                               1292   [ +  -  +  + ]:            518 :             else if (WORKER(state))
                               1293                 :                :             {
                               1294                 :                :                 /*
                               1295                 :                :                  * Parallel workers must still dump out tuples to tape.  No
                               1296                 :                :                  * merge is required to produce single output run, though.
                               1297                 :                :                  */
                               1298                 :            385 :                 inittapes(state, false);
                               1299                 :            385 :                 dumptuples(state, true);
                               1300                 :            385 :                 worker_nomergeruns(state);
                               1301                 :            385 :                 state->status = TSS_SORTEDONTAPE;
                               1302                 :                :             }
                               1303                 :                :             else
                               1304                 :                :             {
                               1305                 :                :                 /*
                               1306                 :                :                  * Leader will take over worker tapes and merge worker runs.
                               1307                 :                :                  * Note that mergeruns sets the correct state->status.
                               1308                 :                :                  */
                               1309                 :            133 :                 leader_takeover_tapes(state);
                               1310                 :            133 :                 mergeruns(state);
                               1311                 :                :             }
 9904 tgl@sss.pgh.pa.us        1312                 :         149558 :             state->current = 0;
                               1313                 :         149558 :             state->eof_reached = false;
 3221 rhaas@postgresql.org     1314                 :         149558 :             state->markpos_block = 0L;
 9904 tgl@sss.pgh.pa.us        1315                 :         149558 :             state->markpos_offset = 0;
                               1316                 :         149558 :             state->markpos_eof = false;
                               1317                 :         149558 :             break;
                               1318                 :                : 
 7148                          1319                 :            277 :         case TSS_BOUNDED:
                               1320                 :                : 
                               1321                 :                :             /*
                               1322                 :                :              * We were able to accumulate all the tuples required for output
                               1323                 :                :              * in memory, using a heap to eliminate excess tuples.  Now we
                               1324                 :                :              * have to transform the heap to a properly-sorted array. Note
                               1325                 :                :              * that sort_bounded_heap sets the correct state->status.
                               1326                 :                :              */
 7028                          1327                 :            277 :             sort_bounded_heap(state);
 7148                          1328                 :            277 :             state->current = 0;
                               1329                 :            277 :             state->eof_reached = false;
                               1330                 :            277 :             state->markpos_offset = 0;
                               1331                 :            277 :             state->markpos_eof = false;
                               1332                 :            277 :             break;
                               1333                 :                : 
 9904                          1334                 :             90 :         case TSS_BUILDRUNS:
                               1335                 :                : 
                               1336                 :                :             /*
                               1337                 :                :              * Finish tape-based sort.  First, flush all tuples remaining in
                               1338                 :                :              * memory out to tape; then merge until we have a single remaining
                               1339                 :                :              * run (or, if !randomAccess and !WORKER(), one run per tape).
                               1340                 :                :              * Note that mergeruns sets the correct state->status.
                               1341                 :                :              */
                               1342                 :             90 :             dumptuples(state, true);
                               1343                 :             90 :             mergeruns(state);
                               1344                 :             90 :             state->eof_reached = false;
                               1345                 :             90 :             state->markpos_block = 0L;
                               1346                 :             90 :             state->markpos_offset = 0;
                               1347                 :             90 :             state->markpos_eof = false;
                               1348                 :             90 :             break;
                               1349                 :                : 
 9904 tgl@sss.pgh.pa.us        1350                 :UBC           0 :         default:
 8527                          1351         [ #  # ]:              0 :             elog(ERROR, "invalid tuplesort state");
                               1352                 :                :             break;
                               1353                 :                :     }
                               1354                 :                : 
 7726 tgl@sss.pgh.pa.us        1355         [ -  + ]:CBC      149925 :     if (trace_sort)
                               1356                 :                :     {
 7570 tgl@sss.pgh.pa.us        1357         [ #  # ]:UBC           0 :         if (state->status == TSS_FINALMERGE)
 2949 pg@bowt.ie               1358         [ #  # ]:              0 :             elog(LOG, "performsort of worker %d done (except %d-way final merge): %s",
                               1359                 :                :                  state->worker, state->nInputTapes,
                               1360                 :                :                  pg_rusage_show(&state->ru_start));
                               1361                 :                :         else
                               1362         [ #  # ]:              0 :             elog(LOG, "performsort of worker %d done: %s",
                               1363                 :                :                  state->worker, pg_rusage_show(&state->ru_start));
                               1364                 :                :     }
                               1365                 :                : 
 7580 tgl@sss.pgh.pa.us        1366                 :CBC      149925 :     MemoryContextSwitchTo(oldcontext);
 9904                          1367                 :         149925 : }
                               1368                 :                : 
                               1369                 :                : /*
                               1370                 :                :  * Internal routine to fetch the next tuple in either forward or back
                               1371                 :                :  * direction into *stup.  Returns false if no more tuples.
                               1372                 :                :  * Returned tuple belongs to tuplesort memory context, and must not be freed
                               1373                 :                :  * by caller.  Note that fetched tuple is stored in memory that may be
                               1374                 :                :  * recycled by any future fetch.
                               1375                 :                :  */
                               1376                 :                : bool
 7580                          1377                 :       18118063 : tuplesort_gettuple_common(Tuplesortstate *state, bool forward,
                               1378                 :                :                           SortTuple *stup)
                               1379                 :                : {
                               1380                 :                :     unsigned int tuplen;
                               1381                 :                :     size_t      nmoved;
                               1382                 :                : 
 3221 rhaas@postgresql.org     1383   [ +  +  -  + ]:       18118063 :     Assert(!WORKER(state));
                               1384                 :                : 
 9904 tgl@sss.pgh.pa.us        1385   [ +  +  +  - ]:       18118063 :     switch (state->status)
                               1386                 :                :     {
                               1387                 :       15173974 :         case TSS_SORTEDINMEM:
 1585 akorotkov@postgresql     1388   [ +  +  -  + ]:       15173974 :             Assert(forward || state->base.sortopt & TUPLESORT_RANDOMACCESS);
 3708 heikki.linnakangas@i     1389         [ -  + ]:       15173974 :             Assert(!state->slabAllocatorUsed);
 9904 tgl@sss.pgh.pa.us        1390         [ +  + ]:       15173974 :             if (forward)
                               1391                 :                :             {
                               1392         [ +  + ]:       15173930 :                 if (state->current < state->memtupcount)
                               1393                 :                :                 {
 7580                          1394                 :       15025518 :                     *stup = state->memtuples[state->current++];
                               1395                 :       15025518 :                     return true;
                               1396                 :                :                 }
 9904                          1397                 :         148412 :                 state->eof_reached = true;
                               1398                 :                : 
                               1399                 :                :                 /*
                               1400                 :                :                  * Complain if caller tries to retrieve more tuples than
                               1401                 :                :                  * originally asked for in a bounded sort.  This is because
                               1402                 :                :                  * returning EOF here might be the wrong thing.
                               1403                 :                :                  */
 7148                          1404   [ +  +  -  + ]:         148412 :                 if (state->bounded && state->current >= state->bound)
 7148 tgl@sss.pgh.pa.us        1405         [ #  # ]:UBC           0 :                     elog(ERROR, "retrieved too many tuples in a bounded sort");
                               1406                 :                : 
 7580 tgl@sss.pgh.pa.us        1407                 :CBC      148412 :                 return false;
                               1408                 :                :             }
                               1409                 :                :             else
                               1410                 :                :             {
 9904                          1411         [ -  + ]:             44 :                 if (state->current <= 0)
 7580 tgl@sss.pgh.pa.us        1412                 :UBC           0 :                     return false;
                               1413                 :                : 
                               1414                 :                :                 /*
                               1415                 :                :                  * if all tuples are fetched already then we return last
                               1416                 :                :                  * tuple, else - tuple before last returned.
                               1417                 :                :                  */
 9904 tgl@sss.pgh.pa.us        1418         [ +  + ]:CBC          44 :                 if (state->eof_reached)
                               1419                 :              8 :                     state->eof_reached = false;
                               1420                 :                :                 else
                               1421                 :                :                 {
 9726 bruce@momjian.us         1422                 :             36 :                     state->current--;    /* last returned tuple */
 9904 tgl@sss.pgh.pa.us        1423         [ +  + ]:             36 :                     if (state->current <= 0)
 7580                          1424                 :              4 :                         return false;
                               1425                 :                :                 }
                               1426                 :             40 :                 *stup = state->memtuples[state->current - 1];
                               1427                 :             40 :                 return true;
                               1428                 :                :             }
                               1429                 :                :             break;
                               1430                 :                : 
 9904                          1431                 :         196999 :         case TSS_SORTEDONTAPE:
 1585 akorotkov@postgresql     1432   [ +  +  -  + ]:         196999 :             Assert(forward || state->base.sortopt & TUPLESORT_RANDOMACCESS);
 3708 heikki.linnakangas@i     1433         [ -  + ]:         196999 :             Assert(state->slabAllocatorUsed);
                               1434                 :                : 
                               1435                 :                :             /*
                               1436                 :                :              * The slot that held the tuple that we returned in previous
                               1437                 :                :              * gettuple call can now be reused.
                               1438                 :                :              */
                               1439         [ +  + ]:         196999 :             if (state->lastReturnedTuple)
                               1440                 :                :             {
                               1441   [ +  -  +  - ]:         101900 :                 RELEASE_SLAB_SLOT(state, state->lastReturnedTuple);
                               1442                 :         101900 :                 state->lastReturnedTuple = NULL;
                               1443                 :                :             }
                               1444                 :                : 
 9904 tgl@sss.pgh.pa.us        1445         [ +  + ]:         196999 :             if (forward)
                               1446                 :                :             {
                               1447         [ -  + ]:         196979 :                 if (state->eof_reached)
 7580 tgl@sss.pgh.pa.us        1448                 :UBC           0 :                     return false;
                               1449                 :                : 
 1867 heikki.linnakangas@i     1450         [ +  + ]:CBC      196979 :                 if ((tuplen = getlen(state->result_tape, true)) != 0)
                               1451                 :                :                 {
 7580 tgl@sss.pgh.pa.us        1452                 :         196960 :                     READTUP(state, stup, state->result_tape, tuplen);
                               1453                 :                : 
                               1454                 :                :                     /*
                               1455                 :                :                      * Remember the tuple we return, so that we can recycle
                               1456                 :                :                      * its memory on next call.  (This can be NULL, in the
                               1457                 :                :                      * !state->tuples case).
                               1458                 :                :                      */
 3708 heikki.linnakangas@i     1459                 :         196960 :                     state->lastReturnedTuple = stup->tuple;
                               1460                 :                : 
 7580 tgl@sss.pgh.pa.us        1461                 :         196960 :                     return true;
                               1462                 :                :                 }
                               1463                 :                :                 else
                               1464                 :                :                 {
 9904                          1465                 :             19 :                     state->eof_reached = true;
 7580                          1466                 :             19 :                     return false;
                               1467                 :                :                 }
                               1468                 :                :             }
                               1469                 :                : 
                               1470                 :                :             /*
                               1471                 :                :              * Backward.
                               1472                 :                :              *
                               1473                 :                :              * if all tuples are fetched already then we return last tuple,
                               1474                 :                :              * else - tuple before last returned.
                               1475                 :                :              */
 9904                          1476         [ +  + ]:             20 :             if (state->eof_reached)
                               1477                 :                :             {
                               1478                 :                :                 /*
                               1479                 :                :                  * Seek position is pointing just past the zero tuplen at the
                               1480                 :                :                  * end of file; back up to fetch last tuple's ending length
                               1481                 :                :                  * word.  If seek fails we must have a completely empty file.
                               1482                 :                :                  */
 1867 heikki.linnakangas@i     1483                 :              8 :                 nmoved = LogicalTapeBackspace(state->result_tape,
                               1484                 :                :                                               2 * sizeof(unsigned int));
 3628                          1485         [ -  + ]:              8 :                 if (nmoved == 0)
 7580 tgl@sss.pgh.pa.us        1486                 :UBC           0 :                     return false;
 3628 heikki.linnakangas@i     1487         [ -  + ]:CBC           8 :                 else if (nmoved != 2 * sizeof(unsigned int))
 3628 heikki.linnakangas@i     1488         [ #  # ]:UBC           0 :                     elog(ERROR, "unexpected tape position");
 9904 tgl@sss.pgh.pa.us        1489                 :CBC           8 :                 state->eof_reached = false;
                               1490                 :                :             }
                               1491                 :                :             else
                               1492                 :                :             {
                               1493                 :                :                 /*
                               1494                 :                :                  * Back up and fetch previously-returned tuple's ending length
                               1495                 :                :                  * word.  If seek fails, assume we are at start of file.
                               1496                 :                :                  */
 1867 heikki.linnakangas@i     1497                 :             12 :                 nmoved = LogicalTapeBackspace(state->result_tape,
                               1498                 :                :                                               sizeof(unsigned int));
 3628                          1499         [ -  + ]:             12 :                 if (nmoved == 0)
 7580 tgl@sss.pgh.pa.us        1500                 :UBC           0 :                     return false;
 3628 heikki.linnakangas@i     1501         [ -  + ]:CBC          12 :                 else if (nmoved != sizeof(unsigned int))
 3628 heikki.linnakangas@i     1502         [ #  # ]:UBC           0 :                     elog(ERROR, "unexpected tape position");
 1867 heikki.linnakangas@i     1503                 :CBC          12 :                 tuplen = getlen(state->result_tape, false);
                               1504                 :                : 
                               1505                 :                :                 /*
                               1506                 :                :                  * Back up to get ending length word of tuple before it.
                               1507                 :                :                  */
                               1508                 :             12 :                 nmoved = LogicalTapeBackspace(state->result_tape,
                               1509                 :                :                                               tuplen + 2 * sizeof(unsigned int));
 3628                          1510         [ +  + ]:             12 :                 if (nmoved == tuplen + sizeof(unsigned int))
                               1511                 :                :                 {
                               1512                 :                :                     /*
                               1513                 :                :                      * We backed up over the previous tuple, but there was no
                               1514                 :                :                      * ending length word before it.  That means that the prev
                               1515                 :                :                      * tuple is the first tuple in the file.  It is now the
                               1516                 :                :                      * next to read in forward direction (not obviously right,
                               1517                 :                :                      * but that is what in-memory case does).
                               1518                 :                :                      */
 7580 tgl@sss.pgh.pa.us        1519                 :              4 :                     return false;
                               1520                 :                :                 }
 3628 heikki.linnakangas@i     1521         [ -  + ]:              8 :                 else if (nmoved != tuplen + 2 * sizeof(unsigned int))
 3628 heikki.linnakangas@i     1522         [ #  # ]:UBC           0 :                     elog(ERROR, "bogus tuple length in backward scan");
                               1523                 :                :             }
                               1524                 :                : 
 1867 heikki.linnakangas@i     1525                 :CBC          16 :             tuplen = getlen(state->result_tape, false);
                               1526                 :                : 
                               1527                 :                :             /*
                               1528                 :                :              * Now we have the length of the prior tuple, back up and read it.
                               1529                 :                :              * Note: READTUP expects we are positioned after the initial
                               1530                 :                :              * length word of the tuple, so back up to that point.
                               1531                 :                :              */
                               1532                 :             16 :             nmoved = LogicalTapeBackspace(state->result_tape,
                               1533                 :                :                                           tuplen);
 3628                          1534         [ -  + ]:             16 :             if (nmoved != tuplen)
 8527 tgl@sss.pgh.pa.us        1535         [ #  # ]:UBC           0 :                 elog(ERROR, "bogus tuple length in backward scan");
 7580 tgl@sss.pgh.pa.us        1536                 :CBC          16 :             READTUP(state, stup, state->result_tape, tuplen);
                               1537                 :                : 
                               1538                 :                :             /*
                               1539                 :                :              * Remember the tuple we return, so that we can recycle its memory
                               1540                 :                :              * on next call. (This can be NULL, in the Datum case).
                               1541                 :                :              */
 3708 heikki.linnakangas@i     1542                 :             16 :             state->lastReturnedTuple = stup->tuple;
                               1543                 :                : 
 7580 tgl@sss.pgh.pa.us        1544                 :             16 :             return true;
                               1545                 :                : 
 9904                          1546                 :        2747090 :         case TSS_FINALMERGE:
                               1547         [ -  + ]:        2747090 :             Assert(forward);
                               1548                 :                :             /* We are managing memory ourselves, with the slab allocator. */
 3708 heikki.linnakangas@i     1549         [ -  + ]:        2747090 :             Assert(state->slabAllocatorUsed);
                               1550                 :                : 
                               1551                 :                :             /*
                               1552                 :                :              * The slab slot holding the tuple that we returned in previous
                               1553                 :                :              * gettuple call can now be reused.
                               1554                 :                :              */
                               1555         [ +  + ]:        2747090 :             if (state->lastReturnedTuple)
                               1556                 :                :             {
                               1557   [ +  -  +  + ]:        2676861 :                 RELEASE_SLAB_SLOT(state, state->lastReturnedTuple);
                               1558                 :        2676861 :                 state->lastReturnedTuple = NULL;
                               1559                 :                :             }
                               1560                 :                : 
                               1561                 :                :             /*
                               1562                 :                :              * This code should match the inner loop of mergeonerun().
                               1563                 :                :              */
 9891 tgl@sss.pgh.pa.us        1564         [ +  + ]:        2747090 :             if (state->memtupcount > 0)
                               1565                 :                :             {
 1867 heikki.linnakangas@i     1566                 :        2746893 :                 int         srcTapeIndex = state->memtuples[0].srctape;
                               1567                 :        2746893 :                 LogicalTape *srcTape = state->inputTapes[srcTapeIndex];
                               1568                 :                :                 SortTuple   newtup;
                               1569                 :                : 
 3708                          1570                 :        2746893 :                 *stup = state->memtuples[0];
                               1571                 :                : 
                               1572                 :                :                 /*
                               1573                 :                :                  * Remember the tuple we return, so that we can recycle its
                               1574                 :                :                  * memory on next call. (This can be NULL, in the Datum case).
                               1575                 :                :                  */
                               1576                 :        2746893 :                 state->lastReturnedTuple = stup->tuple;
                               1577                 :                : 
                               1578                 :                :                 /*
                               1579                 :                :                  * Pull next tuple from tape, and replace the returned tuple
                               1580                 :                :                  * at top of the heap with it.
                               1581                 :                :                  */
                               1582         [ +  + ]:        2746893 :                 if (!mergereadnext(state, srcTape, &newtup))
                               1583                 :                :                 {
                               1584                 :                :                     /*
                               1585                 :                :                      * If no more data, we've reached end of run on this tape.
                               1586                 :                :                      * Remove the top node from the heap.
                               1587                 :                :                      */
 3347 rhaas@postgresql.org     1588                 :            263 :                     tuplesort_heap_delete_top(state);
 1867 heikki.linnakangas@i     1589                 :            263 :                     state->nInputRuns--;
                               1590                 :                : 
                               1591                 :                :                     /*
                               1592                 :                :                      * Close the tape.  It'd go away at the end of the sort
                               1593                 :                :                      * anyway, but better to release the memory early.
                               1594                 :                :                      */
 1585 akorotkov@postgresql     1595                 :            263 :                     LogicalTapeClose(srcTape);
                               1596                 :            263 :                     return true;
                               1597                 :                :                 }
                               1598                 :        2746630 :                 newtup.srctape = srcTapeIndex;
                               1599                 :        2746630 :                 tuplesort_heap_replace_top(state, &newtup);
                               1600                 :        2746630 :                 return true;
                               1601                 :                :             }
                               1602                 :            197 :             return false;
                               1603                 :                : 
 1585 akorotkov@postgresql     1604                 :UBC           0 :         default:
                               1605         [ #  # ]:              0 :             elog(ERROR, "invalid tuplesort state");
                               1606                 :                :             return false;       /* keep compiler quiet */
                               1607                 :                :     }
                               1608                 :                : }
                               1609                 :                : 
                               1610                 :                : 
                               1611                 :                : /*
                               1612                 :                :  * Advance over N tuples in either forward or back direction,
                               1613                 :                :  * without returning any data.  N==0 is a no-op.
                               1614                 :                :  * Returns true if successful, false if ran out of tuples.
                               1615                 :                :  */
                               1616                 :                : bool
 4723 tgl@sss.pgh.pa.us        1617                 :CBC         258 : tuplesort_skiptuples(Tuplesortstate *state, int64 ntuples, bool forward)
                               1618                 :                : {
                               1619                 :                :     MemoryContext oldcontext;
                               1620                 :                : 
                               1621                 :                :     /*
                               1622                 :                :      * We don't actually support backwards skip yet, because no callers need
                               1623                 :                :      * it.  The API is designed to allow for that later, though.
                               1624                 :                :      */
                               1625         [ -  + ]:            258 :     Assert(forward);
                               1626         [ -  + ]:            258 :     Assert(ntuples >= 0);
 3221 rhaas@postgresql.org     1627   [ -  +  -  - ]:            258 :     Assert(!WORKER(state));
                               1628                 :                : 
 4723 tgl@sss.pgh.pa.us        1629      [ +  +  - ]:            258 :     switch (state->status)
                               1630                 :                :     {
                               1631                 :            242 :         case TSS_SORTEDINMEM:
                               1632         [ +  - ]:            242 :             if (state->memtupcount - state->current >= ntuples)
                               1633                 :                :             {
                               1634                 :            242 :                 state->current += ntuples;
                               1635                 :            242 :                 return true;
                               1636                 :                :             }
 4723 tgl@sss.pgh.pa.us        1637                 :UBC           0 :             state->current = state->memtupcount;
                               1638                 :              0 :             state->eof_reached = true;
                               1639                 :                : 
                               1640                 :                :             /*
                               1641                 :                :              * Complain if caller tries to retrieve more tuples than
                               1642                 :                :              * originally asked for in a bounded sort.  This is because
                               1643                 :                :              * returning EOF here might be the wrong thing.
                               1644                 :                :              */
                               1645   [ #  #  #  # ]:              0 :             if (state->bounded && state->current >= state->bound)
                               1646         [ #  # ]:              0 :                 elog(ERROR, "retrieved too many tuples in a bounded sort");
                               1647                 :                : 
                               1648                 :              0 :             return false;
                               1649                 :                : 
 4723 tgl@sss.pgh.pa.us        1650                 :CBC          16 :         case TSS_SORTEDONTAPE:
                               1651                 :                :         case TSS_FINALMERGE:
                               1652                 :                : 
                               1653                 :                :             /*
                               1654                 :                :              * We could probably optimize these cases better, but for now it's
                               1655                 :                :              * not worth the trouble.
                               1656                 :                :              */
 1585 akorotkov@postgresql     1657                 :             16 :             oldcontext = MemoryContextSwitchTo(state->base.sortcontext);
 4723 tgl@sss.pgh.pa.us        1658         [ +  + ]:         160088 :             while (ntuples-- > 0)
                               1659                 :                :             {
                               1660                 :                :                 SortTuple   stup;
                               1661                 :                : 
 3638 rhaas@postgresql.org     1662         [ -  + ]:         160072 :                 if (!tuplesort_gettuple_common(state, forward, &stup))
                               1663                 :                :                 {
 4722 tgl@sss.pgh.pa.us        1664                 :UBC           0 :                     MemoryContextSwitchTo(oldcontext);
 4723                          1665                 :              0 :                     return false;
                               1666                 :                :                 }
 4723 tgl@sss.pgh.pa.us        1667         [ -  + ]:CBC      160072 :                 CHECK_FOR_INTERRUPTS();
                               1668                 :                :             }
 4722                          1669                 :             16 :             MemoryContextSwitchTo(oldcontext);
 4723                          1670                 :             16 :             return true;
                               1671                 :                : 
 4723 tgl@sss.pgh.pa.us        1672                 :UBC           0 :         default:
                               1673         [ #  # ]:              0 :             elog(ERROR, "invalid tuplesort state");
                               1674                 :                :             return false;       /* keep compiler quiet */
                               1675                 :                :     }
                               1676                 :                : }
                               1677                 :                : 
                               1678                 :                : /*
                               1679                 :                :  * tuplesort_merge_order - report merge order we'll use for given memory
                               1680                 :                :  * (note: "merge order" just means the number of input tapes in the merge).
                               1681                 :                :  *
                               1682                 :                :  * This is exported for use by the planner.  allowedMem is in bytes.
                               1683                 :                :  */
                               1684                 :                : int
 4895 noah@leadboat.com        1685                 :CBC       11187 : tuplesort_merge_order(int64 allowedMem)
                               1686                 :                : {
                               1687                 :                :     int         mOrder;
                               1688                 :                : 
                               1689                 :                :     /*----------
                               1690                 :                :      * In the merge phase, we need buffer space for each input and output tape.
                               1691                 :                :      * Each pass in the balanced merge algorithm reads from M input tapes, and
                               1692                 :                :      * writes to N output tapes.  Each tape consumes TAPE_BUFFER_OVERHEAD bytes
                               1693                 :                :      * of memory.  In addition to that, we want MERGE_BUFFER_SIZE workspace per
                               1694                 :                :      * input tape.
                               1695                 :                :      *
                               1696                 :                :      * totalMem = M * (TAPE_BUFFER_OVERHEAD + MERGE_BUFFER_SIZE) +
                               1697                 :                :      *            N * TAPE_BUFFER_OVERHEAD
                               1698                 :                :      *
                               1699                 :                :      * Except for the last and next-to-last merge passes, where there can be
                               1700                 :                :      * fewer tapes left to process, M = N.  We choose M so that we have the
                               1701                 :                :      * desired amount of memory available for the input buffers
                               1702                 :                :      * (TAPE_BUFFER_OVERHEAD + MERGE_BUFFER_SIZE), given the total memory
                               1703                 :                :      * available for the tape buffers (allowedMem).
                               1704                 :                :      *
                               1705                 :                :      * Note: you might be thinking we need to account for the memtuples[]
                               1706                 :                :      * array in this calculation, but we effectively treat that as part of the
                               1707                 :                :      * MERGE_BUFFER_SIZE workspace.
                               1708                 :                :      *----------
                               1709                 :                :      */
 1867 heikki.linnakangas@i     1710                 :          11187 :     mOrder = allowedMem /
                               1711                 :                :         (2 * TAPE_BUFFER_OVERHEAD + MERGE_BUFFER_SIZE);
                               1712                 :                : 
                               1713                 :                :     /*
                               1714                 :                :      * Even in minimum memory, use at least a MINORDER merge.  On the other
                               1715                 :                :      * hand, even when we have lots of memory, do not use more than a MAXORDER
                               1716                 :                :      * merge.  Tapes are pretty cheap, but they're not entirely free.  Each
                               1717                 :                :      * additional tape reduces the amount of memory available to build runs,
                               1718                 :                :      * which in turn can cause the same sort to need more runs, which makes
                               1719                 :                :      * merging slower even if it can still be done in a single pass.  Also,
                               1720                 :                :      * high order merges are quite slow due to CPU cache effects; it can be
                               1721                 :                :      * faster to pay the I/O cost of a multi-pass merge than to perform a
                               1722                 :                :      * single merge pass across many hundreds of tapes.
                               1723                 :                :      */
 7580 tgl@sss.pgh.pa.us        1724                 :          11187 :     mOrder = Max(mOrder, MINORDER);
 3665 rhaas@postgresql.org     1725                 :          11187 :     mOrder = Min(mOrder, MAXORDER);
                               1726                 :                : 
 7580 tgl@sss.pgh.pa.us        1727                 :          11187 :     return mOrder;
                               1728                 :                : }
                               1729                 :                : 
                               1730                 :                : /*
                               1731                 :                :  * Helper function to calculate how much memory to allocate for the read buffer
                               1732                 :                :  * of each input tape in a merge pass.
                               1733                 :                :  *
                               1734                 :                :  * 'avail_mem' is the amount of memory available for the buffers of all the
                               1735                 :                :  *      tapes, both input and output.
                               1736                 :                :  * 'nInputTapes' and 'nInputRuns' are the number of input tapes and runs.
                               1737                 :                :  * 'maxOutputTapes' is the max. number of output tapes we should produce.
                               1738                 :                :  */
                               1739                 :                : static int64
 1867 heikki.linnakangas@i     1740                 :            263 : merge_read_buffer_size(int64 avail_mem, int nInputTapes, int nInputRuns,
                               1741                 :                :                        int maxOutputTapes)
                               1742                 :                : {
                               1743                 :                :     int         nOutputRuns;
                               1744                 :                :     int         nOutputTapes;
                               1745                 :                : 
                               1746                 :                :     /*
                               1747                 :                :      * How many output tapes will we produce in this pass?
                               1748                 :                :      *
                               1749                 :                :      * This is nInputRuns / nInputTapes, rounded up.
                               1750                 :                :      */
                               1751                 :            263 :     nOutputRuns = (nInputRuns + nInputTapes - 1) / nInputTapes;
                               1752                 :                : 
                               1753                 :            263 :     nOutputTapes = Min(nOutputRuns, maxOutputTapes);
                               1754                 :                : 
                               1755                 :                :     /*
                               1756                 :                :      * Each output tape consumes TAPE_BUFFER_OVERHEAD bytes of memory.  All
                               1757                 :                :      * remaining memory is divided evenly between the input tapes.
                               1758                 :                :      *
                               1759                 :                :      * This also follows from the formula in tuplesort_merge_order, but here
                               1760                 :                :      * we derive the input buffer size from the amount of memory available,
                               1761                 :                :      * and M and N.
                               1762                 :                :      */
                               1763                 :            263 :     return Max((avail_mem - TAPE_BUFFER_OVERHEAD * nOutputTapes) / nInputTapes, 0);
                               1764                 :                : }
                               1765                 :                : 
                               1766                 :                : /*
                               1767                 :                :  * inittapes - initialize for tape sorting.
                               1768                 :                :  *
                               1769                 :                :  * This is called only if we have found we won't sort in memory.
                               1770                 :                :  */
                               1771                 :                : static void
 3221 rhaas@postgresql.org     1772                 :            475 : inittapes(Tuplesortstate *state, bool mergeruns)
                               1773                 :                : {
                               1774   [ +  +  -  + ]:            475 :     Assert(!LEADER(state));
                               1775                 :                : 
                               1776         [ +  + ]:            475 :     if (mergeruns)
                               1777                 :                :     {
                               1778                 :                :         /* Compute number of input tapes to use when merging */
 1867 heikki.linnakangas@i     1779                 :             90 :         state->maxTapes = tuplesort_merge_order(state->allowedMem);
                               1780                 :                :     }
                               1781                 :                :     else
                               1782                 :                :     {
                               1783                 :                :         /* Workers can sometimes produce single run, output without merge */
 3221 rhaas@postgresql.org     1784   [ +  -  -  + ]:            385 :         Assert(WORKER(state));
 1867 heikki.linnakangas@i     1785                 :            385 :         state->maxTapes = MINORDER;
                               1786                 :                :     }
                               1787                 :                : 
 7726 tgl@sss.pgh.pa.us        1788         [ -  + ]:            475 :     if (trace_sort)
 2949 pg@bowt.ie               1789         [ #  # ]:UBC           0 :         elog(LOG, "worker %d switching to external sort with %d tapes: %s",
                               1790                 :                :              state->worker, state->maxTapes, pg_rusage_show(&state->ru_start));
                               1791                 :                : 
                               1792                 :                :     /* Create the tape set */
 1867 heikki.linnakangas@i     1793                 :CBC         475 :     inittapestate(state, state->maxTapes);
 3221 rhaas@postgresql.org     1794                 :            475 :     state->tapeset =
 1867 heikki.linnakangas@i     1795                 :            475 :         LogicalTapeSetCreate(false,
 3221 rhaas@postgresql.org     1796         [ +  + ]:            475 :                              state->shared ? &state->shared->fileset : NULL,
                               1797                 :                :                              state->worker);
                               1798                 :                : 
 3347                          1799                 :            475 :     state->currentRun = 0;
                               1800                 :                : 
                               1801                 :                :     /*
                               1802                 :                :      * Initialize logical tape arrays.
                               1803                 :                :      */
 1867 heikki.linnakangas@i     1804                 :            475 :     state->inputTapes = NULL;
                               1805                 :            475 :     state->nInputTapes = 0;
                               1806                 :            475 :     state->nInputRuns = 0;
                               1807                 :                : 
  103 michael@paquier.xyz      1808                 :GNC         475 :     state->outputTapes = palloc0_array(LogicalTape *, state->maxTapes);
 1867 heikki.linnakangas@i     1809                 :CBC         475 :     state->nOutputTapes = 0;
                               1810                 :            475 :     state->nOutputRuns = 0;
                               1811                 :                : 
 9904 tgl@sss.pgh.pa.us        1812                 :            475 :     state->status = TSS_BUILDRUNS;
                               1813                 :                : 
 1867 heikki.linnakangas@i     1814                 :            475 :     selectnewtape(state);
 9904 tgl@sss.pgh.pa.us        1815                 :            475 : }
                               1816                 :                : 
                               1817                 :                : /*
                               1818                 :                :  * inittapestate - initialize generic tape management state
                               1819                 :                :  */
                               1820                 :                : static void
 3221 rhaas@postgresql.org     1821                 :            608 : inittapestate(Tuplesortstate *state, int maxTapes)
                               1822                 :                : {
                               1823                 :                :     int64       tapeSpace;
                               1824                 :                : 
                               1825                 :                :     /*
                               1826                 :                :      * Decrease availMem to reflect the space needed for tape buffers; but
                               1827                 :                :      * don't decrease it to the point that we have no room for tuples. (That
                               1828                 :                :      * case is only likely to occur if sorting pass-by-value Datums; in all
                               1829                 :                :      * other scenarios the memtuples[] array is unlikely to occupy more than
                               1830                 :                :      * half of allowedMem.  In the pass-by-value case it's not important to
                               1831                 :                :      * account for tuple space, so we don't care if LACKMEM becomes
                               1832                 :                :      * inaccurate.)
                               1833                 :                :      */
                               1834                 :            608 :     tapeSpace = (int64) maxTapes * TAPE_BUFFER_OVERHEAD;
                               1835                 :                : 
                               1836         [ +  + ]:            608 :     if (tapeSpace + GetMemoryChunkSpace(state->memtuples) < state->allowedMem)
                               1837                 :            530 :         USEMEM(state, tapeSpace);
                               1838                 :                : 
                               1839                 :                :     /*
                               1840                 :                :      * Make sure that the temp file(s) underlying the tape set are created in
                               1841                 :                :      * suitable temp tablespaces.  For parallel sorts, this should have been
                               1842                 :                :      * called already, but it doesn't matter if it is called a second time.
                               1843                 :                :      */
                               1844                 :            608 :     PrepareTempTablespaces();
                               1845                 :            608 : }
                               1846                 :                : 
                               1847                 :                : /*
                               1848                 :                :  * selectnewtape -- select next tape to output to.
                               1849                 :                :  *
                               1850                 :                :  * This is called after finishing a run when we know another run
                               1851                 :                :  * must be started.  This is used both when building the initial
                               1852                 :                :  * runs, and during merge passes.
                               1853                 :                :  */
                               1854                 :                : static void
 9904 tgl@sss.pgh.pa.us        1855                 :           1310 : selectnewtape(Tuplesortstate *state)
                               1856                 :                : {
                               1857                 :                :     /*
                               1858                 :                :      * At the beginning of each merge pass, nOutputTapes and nOutputRuns are
                               1859                 :                :      * both zero.  On each call, we create a new output tape to hold the next
                               1860                 :                :      * run, until maxTapes is reached.  After that, we assign new runs to the
                               1861                 :                :      * existing tapes in a round robin fashion.
                               1862                 :                :      */
 1860 heikki.linnakangas@i     1863         [ +  + ]:           1310 :     if (state->nOutputTapes < state->maxTapes)
                               1864                 :                :     {
                               1865                 :                :         /* Create a new tape to hold the next run */
 1867                          1866         [ -  + ]:            882 :         Assert(state->outputTapes[state->nOutputRuns] == NULL);
                               1867         [ -  + ]:            882 :         Assert(state->nOutputRuns == state->nOutputTapes);
                               1868                 :            882 :         state->destTape = LogicalTapeCreate(state->tapeset);
 1860                          1869                 :            882 :         state->outputTapes[state->nOutputTapes] = state->destTape;
 1867                          1870                 :            882 :         state->nOutputTapes++;
                               1871                 :            882 :         state->nOutputRuns++;
                               1872                 :                :     }
                               1873                 :                :     else
                               1874                 :                :     {
                               1875                 :                :         /*
                               1876                 :                :          * We have reached the max number of tapes.  Append to an existing
                               1877                 :                :          * tape.
                               1878                 :                :          */
                               1879                 :            428 :         state->destTape = state->outputTapes[state->nOutputRuns % state->nOutputTapes];
                               1880                 :            428 :         state->nOutputRuns++;
                               1881                 :                :     }
 9904 tgl@sss.pgh.pa.us        1882                 :           1310 : }
                               1883                 :                : 
                               1884                 :                : /*
                               1885                 :                :  * Initialize the slab allocation arena, for the given number of slots.
                               1886                 :                :  */
                               1887                 :                : static void
 3708 heikki.linnakangas@i     1888                 :            223 : init_slab_allocator(Tuplesortstate *state, int numSlots)
                               1889                 :                : {
                               1890         [ +  + ]:            223 :     if (numSlots > 0)
                               1891                 :                :     {
                               1892                 :                :         char       *p;
                               1893                 :                :         int         i;
                               1894                 :                : 
                               1895                 :            207 :         state->slabMemoryBegin = palloc(numSlots * SLAB_SLOT_SIZE);
                               1896                 :            207 :         state->slabMemoryEnd = state->slabMemoryBegin +
                               1897                 :            207 :             numSlots * SLAB_SLOT_SIZE;
                               1898                 :            207 :         state->slabFreeHead = (SlabSlot *) state->slabMemoryBegin;
                               1899                 :            207 :         USEMEM(state, numSlots * SLAB_SLOT_SIZE);
                               1900                 :                : 
                               1901                 :            207 :         p = state->slabMemoryBegin;
                               1902         [ +  + ]:            811 :         for (i = 0; i < numSlots - 1; i++)
                               1903                 :                :         {
                               1904                 :            604 :             ((SlabSlot *) p)->nextfree = (SlabSlot *) (p + SLAB_SLOT_SIZE);
                               1905                 :            604 :             p += SLAB_SLOT_SIZE;
                               1906                 :                :         }
                               1907                 :            207 :         ((SlabSlot *) p)->nextfree = NULL;
                               1908                 :                :     }
                               1909                 :                :     else
                               1910                 :                :     {
                               1911                 :             16 :         state->slabMemoryBegin = state->slabMemoryEnd = NULL;
                               1912                 :             16 :         state->slabFreeHead = NULL;
                               1913                 :                :     }
                               1914                 :            223 :     state->slabAllocatorUsed = true;
                               1915                 :            223 : }
                               1916                 :                : 
                               1917                 :                : /*
                               1918                 :                :  * mergeruns -- merge all the completed initial runs.
                               1919                 :                :  *
                               1920                 :                :  * This implements the Balanced k-Way Merge Algorithm.  All input data has
                               1921                 :                :  * already been written to initial runs on tape (see dumptuples).
                               1922                 :                :  */
                               1923                 :                : static void
 9904 tgl@sss.pgh.pa.us        1924                 :            223 : mergeruns(Tuplesortstate *state)
                               1925                 :                : {
                               1926                 :                :     int         tapenum;
                               1927                 :                : 
                               1928         [ -  + ]:            223 :     Assert(state->status == TSS_BUILDRUNS);
 9891                          1929         [ -  + ]:            223 :     Assert(state->memtupcount == 0);
                               1930                 :                : 
 1585 akorotkov@postgresql     1931   [ +  +  +  + ]:            223 :     if (state->base.sortKeys != NULL && state->base.sortKeys->abbrev_converter != NULL)
                               1932                 :                :     {
                               1933                 :                :         /*
                               1934                 :                :          * If there are multiple runs to be merged, when we go to read back
                               1935                 :                :          * tuples from disk, abbreviated keys will not have been stored, and
                               1936                 :                :          * we don't care to regenerate them.  Disable abbreviation from this
                               1937                 :                :          * point on.
                               1938                 :                :          */
                               1939                 :             19 :         state->base.sortKeys->abbrev_converter = NULL;
                               1940                 :             19 :         state->base.sortKeys->comparator = state->base.sortKeys->abbrev_full_comparator;
                               1941                 :                : 
                               1942                 :                :         /* Not strictly necessary, but be tidy */
                               1943                 :             19 :         state->base.sortKeys->abbrev_abort = NULL;
                               1944                 :             19 :         state->base.sortKeys->abbrev_full_comparator = NULL;
                               1945                 :                :     }
                               1946                 :                : 
                               1947                 :                :     /*
                               1948                 :                :      * Reset tuple memory.  We've freed all the tuples that we previously
                               1949                 :                :      * allocated.  We will use the slab allocator from now on.
                               1950                 :                :      */
                               1951                 :            223 :     MemoryContextResetOnly(state->base.tuplecontext);
                               1952                 :                : 
                               1953                 :                :     /*
                               1954                 :                :      * We no longer need a large memtuples array.  (We will allocate a smaller
                               1955                 :                :      * one for the heap later.)
                               1956                 :                :      */
 3708 heikki.linnakangas@i     1957                 :            223 :     FREEMEM(state, GetMemoryChunkSpace(state->memtuples));
                               1958                 :            223 :     pfree(state->memtuples);
                               1959                 :            223 :     state->memtuples = NULL;
                               1960                 :                : 
                               1961                 :                :     /*
                               1962                 :                :      * Initialize the slab allocator.  We need one slab slot per input tape,
                               1963                 :                :      * for the tuples in the heap, plus one to hold the tuple last returned
                               1964                 :                :      * from tuplesort_gettuple.  (If we're sorting pass-by-val Datums,
                               1965                 :                :      * however, we don't need to do allocate anything.)
                               1966                 :                :      *
                               1967                 :                :      * In a multi-pass merge, we could shrink this allocation for the last
                               1968                 :                :      * merge pass, if it has fewer tapes than previous passes, but we don't
                               1969                 :                :      * bother.
                               1970                 :                :      *
                               1971                 :                :      * From this point on, we no longer use the USEMEM()/LACKMEM() mechanism
                               1972                 :                :      * to track memory usage of individual tuples.
                               1973                 :                :      */
 1585 akorotkov@postgresql     1974         [ +  + ]:            223 :     if (state->base.tuples)
 1867 heikki.linnakangas@i     1975                 :            207 :         init_slab_allocator(state, state->nOutputTapes + 1);
                               1976                 :                :     else
 3708                          1977                 :             16 :         init_slab_allocator(state, 0);
                               1978                 :                : 
                               1979                 :                :     /*
                               1980                 :                :      * Allocate a new 'memtuples' array, for the heap.  It will hold one tuple
                               1981                 :                :      * from each input tape.
                               1982                 :                :      *
                               1983                 :                :      * We could shrink this, too, between passes in a multi-pass merge, but we
                               1984                 :                :      * don't bother.  (The initial input tapes are still in outputTapes.  The
                               1985                 :                :      * number of input tapes will not increase between passes.)
                               1986                 :                :      */
 1867                          1987                 :            223 :     state->memtupsize = state->nOutputTapes;
 1585 akorotkov@postgresql     1988                 :            446 :     state->memtuples = (SortTuple *) MemoryContextAlloc(state->base.maincontext,
 1867 heikki.linnakangas@i     1989                 :            223 :                                                         state->nOutputTapes * sizeof(SortTuple));
 3642                          1990                 :            223 :     USEMEM(state, GetMemoryChunkSpace(state->memtuples));
                               1991                 :                : 
                               1992                 :                :     /*
                               1993                 :                :      * Use all the remaining memory we have available for tape buffers among
                               1994                 :                :      * all the input tapes.  At the beginning of each merge pass, we will
                               1995                 :                :      * divide this memory between the input and output tapes in the pass.
                               1996                 :                :      */
 1867                          1997                 :            223 :     state->tape_buffer_mem = state->availMem;
 1860                          1998                 :            223 :     USEMEM(state, state->tape_buffer_mem);
 3699                          1999         [ -  + ]:            223 :     if (trace_sort)
 1867 heikki.linnakangas@i     2000         [ #  # ]:UBC           0 :         elog(LOG, "worker %d using %zu KB of memory for tape buffers",
                               2001                 :                :              state->worker, state->tape_buffer_mem / 1024);
                               2002                 :                : 
                               2003                 :                :     for (;;)
                               2004                 :                :     {
                               2005                 :                :         /*
                               2006                 :                :          * On the first iteration, or if we have read all the runs from the
                               2007                 :                :          * input tapes in a multi-pass merge, it's time to start a new pass.
                               2008                 :                :          * Rewind all the output tapes, and make them inputs for the next
                               2009                 :                :          * pass.
                               2010                 :                :          */
 1867 heikki.linnakangas@i     2011         [ +  + ]:CBC         355 :         if (state->nInputRuns == 0)
                               2012                 :                :         {
                               2013                 :                :             int64       input_buffer_size;
                               2014                 :                : 
                               2015                 :                :             /* Close the old, emptied, input tapes */
                               2016         [ +  + ]:            263 :             if (state->nInputTapes > 0)
                               2017                 :                :             {
                               2018         [ +  + ]:            280 :                 for (tapenum = 0; tapenum < state->nInputTapes; tapenum++)
                               2019                 :            240 :                     LogicalTapeClose(state->inputTapes[tapenum]);
                               2020                 :             40 :                 pfree(state->inputTapes);
                               2021                 :                :             }
                               2022                 :                : 
                               2023                 :                :             /* Previous pass's outputs become next pass's inputs. */
                               2024                 :            263 :             state->inputTapes = state->outputTapes;
                               2025                 :            263 :             state->nInputTapes = state->nOutputTapes;
                               2026                 :            263 :             state->nInputRuns = state->nOutputRuns;
                               2027                 :                : 
                               2028                 :                :             /*
                               2029                 :                :              * Reset output tape variables.  The actual LogicalTapes will be
                               2030                 :                :              * created as needed, here we only allocate the array to hold
                               2031                 :                :              * them.
                               2032                 :                :              */
  103 michael@paquier.xyz      2033                 :GNC         263 :             state->outputTapes = palloc0_array(LogicalTape *, state->nInputTapes);
 1867 heikki.linnakangas@i     2034                 :CBC         263 :             state->nOutputTapes = 0;
                               2035                 :            263 :             state->nOutputRuns = 0;
                               2036                 :                : 
                               2037                 :                :             /*
                               2038                 :                :              * Redistribute the memory allocated for tape buffers, among the
                               2039                 :                :              * new input and output tapes.
                               2040                 :                :              */
                               2041                 :            263 :             input_buffer_size = merge_read_buffer_size(state->tape_buffer_mem,
                               2042                 :                :                                                        state->nInputTapes,
                               2043                 :                :                                                        state->nInputRuns,
                               2044                 :                :                                                        state->maxTapes);
                               2045                 :                : 
                               2046         [ -  + ]:            263 :             if (trace_sort)
 1867 heikki.linnakangas@i     2047         [ #  # ]:UBC           0 :                 elog(LOG, "starting merge pass of %d input runs on %d tapes, " INT64_FORMAT " KB of memory for each input tape: %s",
                               2048                 :                :                      state->nInputRuns, state->nInputTapes, input_buffer_size / 1024,
                               2049                 :                :                      pg_rusage_show(&state->ru_start));
                               2050                 :                : 
                               2051                 :                :             /* Prepare the new input tapes for merge pass. */
 1867 heikki.linnakangas@i     2052         [ +  + ]:CBC        1035 :             for (tapenum = 0; tapenum < state->nInputTapes; tapenum++)
                               2053                 :            772 :                 LogicalTapeRewindForRead(state->inputTapes[tapenum], input_buffer_size);
                               2054                 :                : 
                               2055                 :                :             /*
                               2056                 :                :              * If there's just one run left on each input tape, then only one
                               2057                 :                :              * merge pass remains.  If we don't have to produce a materialized
                               2058                 :                :              * sorted tape, we can stop at this point and do the final merge
                               2059                 :                :              * on-the-fly.
                               2060                 :                :              */
 1585 akorotkov@postgresql     2061         [ +  + ]:            263 :             if ((state->base.sortopt & TUPLESORT_RANDOMACCESS) == 0
 1699 drowley@postgresql.o     2062         [ +  + ]:            245 :                 && state->nInputRuns <= state->nInputTapes
 1867 heikki.linnakangas@i     2063   [ +  +  +  - ]:            209 :                 && !WORKER(state))
                               2064                 :                :             {
                               2065                 :                :                 /* Tell logtape.c we won't be writing anymore */
 7571 tgl@sss.pgh.pa.us        2066                 :            209 :                 LogicalTapeSetForgetFreeSpace(state->tapeset);
                               2067                 :                :                 /* Initialize for the final merge pass */
 3708 heikki.linnakangas@i     2068                 :            209 :                 beginmerge(state);
 9904 tgl@sss.pgh.pa.us        2069                 :            209 :                 state->status = TSS_FINALMERGE;
                               2070                 :            209 :                 return;
                               2071                 :                :             }
                               2072                 :                :         }
                               2073                 :                : 
                               2074                 :                :         /* Select an output tape */
 1867 heikki.linnakangas@i     2075                 :            146 :         selectnewtape(state);
                               2076                 :                : 
                               2077                 :                :         /* Merge one run from each input tape. */
                               2078                 :            146 :         mergeonerun(state);
                               2079                 :                : 
                               2080                 :                :         /*
                               2081                 :                :          * If the input tapes are empty, and we output only one output run,
                               2082                 :                :          * we're done.  The current output tape contains the final result.
                               2083                 :                :          */
                               2084   [ +  +  +  + ]:            146 :         if (state->nInputRuns == 0 && state->nOutputRuns <= 1)
                               2085                 :             14 :             break;
                               2086                 :                :     }
                               2087                 :                : 
                               2088                 :                :     /*
                               2089                 :                :      * Done.  The result is on a single run on a single tape.
                               2090                 :                :      */
                               2091                 :             14 :     state->result_tape = state->outputTapes[0];
 3221 rhaas@postgresql.org     2092   [ -  +  -  - ]:             14 :     if (!WORKER(state))
 1867 heikki.linnakangas@i     2093                 :             14 :         LogicalTapeFreeze(state->result_tape, NULL);
                               2094                 :                :     else
 3221 rhaas@postgresql.org     2095                 :UBC           0 :         worker_freeze_result_tape(state);
 9904 tgl@sss.pgh.pa.us        2096                 :CBC          14 :     state->status = TSS_SORTEDONTAPE;
                               2097                 :                : 
                               2098                 :                :     /* Close all the now-empty input tapes, to release their read buffers. */
 1867 heikki.linnakangas@i     2099         [ +  + ]:             62 :     for (tapenum = 0; tapenum < state->nInputTapes; tapenum++)
                               2100                 :             48 :         LogicalTapeClose(state->inputTapes[tapenum]);
                               2101                 :                : }
                               2102                 :                : 
                               2103                 :                : /*
                               2104                 :                :  * Merge one run from each input tape.
                               2105                 :                :  */
                               2106                 :                : static void
 9904 tgl@sss.pgh.pa.us        2107                 :            146 : mergeonerun(Tuplesortstate *state)
                               2108                 :                : {
                               2109                 :                :     int         srcTapeIndex;
                               2110                 :                :     LogicalTape *srcTape;
                               2111                 :                : 
                               2112                 :                :     /*
                               2113                 :                :      * Start the merge by loading one tuple from each active source tape into
                               2114                 :                :      * the heap.
                               2115                 :                :      */
 3708 heikki.linnakangas@i     2116                 :            146 :     beginmerge(state);
                               2117                 :                : 
 1549 drowley@postgresql.o     2118         [ -  + ]:            146 :     Assert(state->slabAllocatorUsed);
                               2119                 :                : 
                               2120                 :                :     /*
                               2121                 :                :      * Execute merge by repeatedly extracting lowest tuple in heap, writing it
                               2122                 :                :      * out, and replacing it with next tuple from same tape (if there is
                               2123                 :                :      * another one).
                               2124                 :                :      */
 9891 tgl@sss.pgh.pa.us        2125         [ +  + ]:         980650 :     while (state->memtupcount > 0)
                               2126                 :                :     {
                               2127                 :                :         SortTuple   stup;
                               2128                 :                : 
                               2129                 :                :         /* write the tuple to destTape */
 1867 heikki.linnakangas@i     2130                 :         980504 :         srcTapeIndex = state->memtuples[0].srctape;
                               2131                 :         980504 :         srcTape = state->inputTapes[srcTapeIndex];
                               2132                 :         980504 :         WRITETUP(state, state->destTape, &state->memtuples[0]);
                               2133                 :                : 
                               2134                 :                :         /* recycle the slot of the tuple we just wrote out, for the next read */
 3603 tgl@sss.pgh.pa.us        2135         [ +  + ]:         980504 :         if (state->memtuples[0].tuple)
                               2136   [ +  -  +  - ]:         890416 :             RELEASE_SLAB_SLOT(state, state->memtuples[0].tuple);
                               2137                 :                : 
                               2138                 :                :         /*
                               2139                 :                :          * pull next tuple from the tape, and replace the written-out tuple in
                               2140                 :                :          * the heap with it.
                               2141                 :                :          */
 3708 heikki.linnakangas@i     2142         [ +  + ]:         980504 :         if (mergereadnext(state, srcTape, &stup))
                               2143                 :                :         {
 1867                          2144                 :         979788 :             stup.srctape = srcTapeIndex;
 3347 rhaas@postgresql.org     2145                 :         979788 :             tuplesort_heap_replace_top(state, &stup);
                               2146                 :                :         }
                               2147                 :                :         else
                               2148                 :                :         {
                               2149                 :            716 :             tuplesort_heap_delete_top(state);
 1867 heikki.linnakangas@i     2150                 :            716 :             state->nInputRuns--;
                               2151                 :                :         }
                               2152                 :                :     }
                               2153                 :                : 
                               2154                 :                :     /*
                               2155                 :                :      * When the heap empties, we're done.  Write an end-of-run marker on the
                               2156                 :                :      * output tape.
                               2157                 :                :      */
                               2158                 :            146 :     markrunend(state->destTape);
 9904 tgl@sss.pgh.pa.us        2159                 :            146 : }
                               2160                 :                : 
                               2161                 :                : /*
                               2162                 :                :  * beginmerge - initialize for a merge pass
                               2163                 :                :  *
                               2164                 :                :  * Fill the merge heap with the first tuple from each input tape.
                               2165                 :                :  */
                               2166                 :                : static void
 3708 heikki.linnakangas@i     2167                 :            355 : beginmerge(Tuplesortstate *state)
                               2168                 :                : {
                               2169                 :                :     int         activeTapes;
                               2170                 :                :     int         srcTapeIndex;
                               2171                 :                : 
                               2172                 :                :     /* Heap should be empty here */
 9891 tgl@sss.pgh.pa.us        2173         [ -  + ]:            355 :     Assert(state->memtupcount == 0);
                               2174                 :                : 
 1867 heikki.linnakangas@i     2175                 :            355 :     activeTapes = Min(state->nInputTapes, state->nInputRuns);
                               2176                 :                : 
                               2177         [ +  + ]:           1555 :     for (srcTapeIndex = 0; srcTapeIndex < activeTapes; srcTapeIndex++)
                               2178                 :                :     {
                               2179                 :                :         SortTuple   tup;
                               2180                 :                : 
                               2181         [ +  + ]:           1200 :         if (mergereadnext(state, state->inputTapes[srcTapeIndex], &tup))
                               2182                 :                :         {
                               2183                 :            999 :             tup.srctape = srcTapeIndex;
 3347 rhaas@postgresql.org     2184                 :            999 :             tuplesort_heap_insert(state, &tup);
                               2185                 :                :         }
                               2186                 :                :     }
 3908                          2187                 :            355 : }
                               2188                 :                : 
                               2189                 :                : /*
                               2190                 :                :  * mergereadnext - read next tuple from one merge input tape
                               2191                 :                :  *
                               2192                 :                :  * Returns false on EOF.
                               2193                 :                :  */
                               2194                 :                : static bool
 1867 heikki.linnakangas@i     2195                 :        3728597 : mergereadnext(Tuplesortstate *state, LogicalTape *srcTape, SortTuple *stup)
                               2196                 :                : {
                               2197                 :                :     unsigned int tuplen;
                               2198                 :                : 
                               2199                 :                :     /* read next tuple, if any */
                               2200         [ +  + ]:        3728597 :     if ((tuplen = getlen(srcTape, true)) == 0)
 3708                          2201                 :           1180 :         return false;
                               2202                 :        3727417 :     READTUP(state, stup, srcTape, tuplen);
                               2203                 :                : 
                               2204                 :        3727417 :     return true;
                               2205                 :                : }
                               2206                 :                : 
                               2207                 :                : /*
                               2208                 :                :  * dumptuples - remove tuples from memtuples and write initial run to tape
                               2209                 :                :  *
                               2210                 :                :  * When alltuples = true, dump everything currently in memory.  (This case is
                               2211                 :                :  * only used at end of input data.)
                               2212                 :                :  */
                               2213                 :                : static void
 9904 tgl@sss.pgh.pa.us        2214                 :         771568 : dumptuples(Tuplesortstate *state, bool alltuples)
                               2215                 :                : {
                               2216                 :                :     int         memtupwrite;
                               2217                 :                :     int         i;
                               2218                 :                : 
                               2219                 :                :     /*
                               2220                 :                :      * Nothing to do if we still fit in available memory and have array slots,
                               2221                 :                :      * unless this is the final call during initial run generation.
                               2222                 :                :      */
 3347 rhaas@postgresql.org     2223   [ +  +  +  +  :         771568 :     if (state->memtupcount < state->memtupsize && !LACKMEM(state) &&
                                              -  + ]
                               2224         [ +  + ]:         770879 :         !alltuples)
                               2225                 :         770404 :         return;
                               2226                 :                : 
                               2227                 :                :     /*
                               2228                 :                :      * Final call might require no sorting, in rare cases where we just so
                               2229                 :                :      * happen to have previously LACKMEM()'d at the point where exactly all
                               2230                 :                :      * remaining tuples are loaded into memory, just before input was
                               2231                 :                :      * exhausted.  In general, short final runs are quite possible, but avoid
                               2232                 :                :      * creating a completely empty run.  In a worker, though, we must produce
                               2233                 :                :      * at least one tape, even if it's empty.
                               2234                 :                :      */
 1867 heikki.linnakangas@i     2235   [ +  +  -  + ]:           1164 :     if (state->memtupcount == 0 && state->currentRun > 0)
 1867 heikki.linnakangas@i     2236                 :UBC           0 :         return;
                               2237                 :                : 
 3886 rhaas@postgresql.org     2238         [ -  + ]:CBC        1164 :     Assert(state->status == TSS_BUILDRUNS);
                               2239                 :                : 
                               2240                 :                :     /*
                               2241                 :                :      * It seems unlikely that this limit will ever be exceeded, but take no
                               2242                 :                :      * chances
                               2243                 :                :      */
                               2244         [ -  + ]:           1164 :     if (state->currentRun == INT_MAX)
 3886 rhaas@postgresql.org     2245         [ #  # ]:UBC           0 :         ereport(ERROR,
                               2246                 :                :                 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
                               2247                 :                :                  errmsg("cannot have more than %d runs for an external sort",
                               2248                 :                :                         INT_MAX)));
                               2249                 :                : 
 1867 heikki.linnakangas@i     2250         [ +  + ]:CBC        1164 :     if (state->currentRun > 0)
                               2251                 :            689 :         selectnewtape(state);
                               2252                 :                : 
 3886 rhaas@postgresql.org     2253                 :           1164 :     state->currentRun++;
                               2254                 :                : 
                               2255         [ -  + ]:           1164 :     if (trace_sort)
 2949 pg@bowt.ie               2256         [ #  # ]:UBC           0 :         elog(LOG, "worker %d starting quicksort of run %d: %s",
                               2257                 :                :              state->worker, state->currentRun,
                               2258                 :                :              pg_rusage_show(&state->ru_start));
                               2259                 :                : 
                               2260                 :                :     /*
                               2261                 :                :      * Sort all tuples accumulated within the allowed amount of memory for
                               2262                 :                :      * this run.
                               2263                 :                :      */
 3886 rhaas@postgresql.org     2264                 :CBC        1164 :     tuplesort_sort_memtuples(state);
                               2265                 :                : 
                               2266         [ -  + ]:           1164 :     if (trace_sort)
 2949 pg@bowt.ie               2267         [ #  # ]:UBC           0 :         elog(LOG, "worker %d finished quicksort of run %d: %s",
                               2268                 :                :              state->worker, state->currentRun,
                               2269                 :                :              pg_rusage_show(&state->ru_start));
                               2270                 :                : 
 3886 rhaas@postgresql.org     2271                 :CBC        1164 :     memtupwrite = state->memtupcount;
                               2272         [ +  + ]:        3088225 :     for (i = 0; i < memtupwrite; i++)
                               2273                 :                :     {
 1549 drowley@postgresql.o     2274                 :        3087061 :         SortTuple  *stup = &state->memtuples[i];
                               2275                 :                : 
                               2276                 :        3087061 :         WRITETUP(state, state->destTape, stup);
                               2277                 :                :     }
                               2278                 :                : 
                               2279                 :           1164 :     state->memtupcount = 0;
                               2280                 :                : 
                               2281                 :                :     /*
                               2282                 :                :      * Reset tuple memory.  We've freed all of the tuples that we previously
                               2283                 :                :      * allocated.  It's important to avoid fragmentation when there is a stark
                               2284                 :                :      * change in the sizes of incoming tuples.  In bounded sorts,
                               2285                 :                :      * fragmentation due to AllocSetFree's bucketing by size class might be
                               2286                 :                :      * particularly bad if this step wasn't taken.
                               2287                 :                :      */
 1585 akorotkov@postgresql     2288                 :           1164 :     MemoryContextReset(state->base.tuplecontext);
                               2289                 :                : 
                               2290                 :                :     /*
                               2291                 :                :      * Now update the memory accounting to subtract the memory used by the
                               2292                 :                :      * tuple.
                               2293                 :                :      */
  964 drowley@postgresql.o     2294                 :           1164 :     FREEMEM(state, state->tupleMem);
                               2295                 :           1164 :     state->tupleMem = 0;
                               2296                 :                : 
 1867 heikki.linnakangas@i     2297                 :           1164 :     markrunend(state->destTape);
                               2298                 :                : 
 3886 rhaas@postgresql.org     2299         [ -  + ]:           1164 :     if (trace_sort)
 2949 pg@bowt.ie               2300         [ #  # ]:UBC           0 :         elog(LOG, "worker %d finished writing run %d to tape %d: %s",
                               2301                 :                :              state->worker, state->currentRun, (state->currentRun - 1) % state->nOutputTapes + 1,
                               2302                 :                :              pg_rusage_show(&state->ru_start));
                               2303                 :                : }
                               2304                 :                : 
                               2305                 :                : /*
                               2306                 :                :  * tuplesort_rescan     - rewind and replay the scan
                               2307                 :                :  */
                               2308                 :                : void
 9904 tgl@sss.pgh.pa.us        2309                 :CBC          38 : tuplesort_rescan(Tuplesortstate *state)
                               2310                 :                : {
 1585 akorotkov@postgresql     2311                 :             38 :     MemoryContext oldcontext = MemoryContextSwitchTo(state->base.sortcontext);
                               2312                 :                : 
                               2313         [ -  + ]:             38 :     Assert(state->base.sortopt & TUPLESORT_RANDOMACCESS);
                               2314                 :                : 
 9904 tgl@sss.pgh.pa.us        2315      [ +  +  - ]:             38 :     switch (state->status)
                               2316                 :                :     {
                               2317                 :             33 :         case TSS_SORTEDINMEM:
                               2318                 :             33 :             state->current = 0;
                               2319                 :             33 :             state->eof_reached = false;
                               2320                 :             33 :             state->markpos_offset = 0;
                               2321                 :             33 :             state->markpos_eof = false;
                               2322                 :             33 :             break;
                               2323                 :              5 :         case TSS_SORTEDONTAPE:
 1867 heikki.linnakangas@i     2324                 :              5 :             LogicalTapeRewindForRead(state->result_tape, 0);
 9904 tgl@sss.pgh.pa.us        2325                 :              5 :             state->eof_reached = false;
                               2326                 :              5 :             state->markpos_block = 0L;
                               2327                 :              5 :             state->markpos_offset = 0;
                               2328                 :              5 :             state->markpos_eof = false;
                               2329                 :              5 :             break;
 9904 tgl@sss.pgh.pa.us        2330                 :UBC           0 :         default:
 8527                          2331         [ #  # ]:              0 :             elog(ERROR, "invalid tuplesort state");
                               2332                 :                :             break;
                               2333                 :                :     }
                               2334                 :                : 
 7580 tgl@sss.pgh.pa.us        2335                 :CBC          38 :     MemoryContextSwitchTo(oldcontext);
 9904                          2336                 :             38 : }
                               2337                 :                : 
                               2338                 :                : /*
                               2339                 :                :  * tuplesort_markpos    - saves current position in the merged sort file
                               2340                 :                :  */
                               2341                 :                : void
                               2342                 :         356480 : tuplesort_markpos(Tuplesortstate *state)
                               2343                 :                : {
 1585 akorotkov@postgresql     2344                 :         356480 :     MemoryContext oldcontext = MemoryContextSwitchTo(state->base.sortcontext);
                               2345                 :                : 
                               2346         [ -  + ]:         356480 :     Assert(state->base.sortopt & TUPLESORT_RANDOMACCESS);
                               2347                 :                : 
 9904 tgl@sss.pgh.pa.us        2348      [ +  +  - ]:         356480 :     switch (state->status)
                               2349                 :                :     {
                               2350                 :         350608 :         case TSS_SORTEDINMEM:
                               2351                 :         350608 :             state->markpos_offset = state->current;
                               2352                 :         350608 :             state->markpos_eof = state->eof_reached;
                               2353                 :         350608 :             break;
                               2354                 :           5872 :         case TSS_SORTEDONTAPE:
 1867 heikki.linnakangas@i     2355                 :           5872 :             LogicalTapeTell(state->result_tape,
                               2356                 :                :                             &state->markpos_block,
                               2357                 :                :                             &state->markpos_offset);
 9904 tgl@sss.pgh.pa.us        2358                 :           5872 :             state->markpos_eof = state->eof_reached;
                               2359                 :           5872 :             break;
 9904 tgl@sss.pgh.pa.us        2360                 :UBC           0 :         default:
 8527                          2361         [ #  # ]:              0 :             elog(ERROR, "invalid tuplesort state");
                               2362                 :                :             break;
                               2363                 :                :     }
                               2364                 :                : 
 7580 tgl@sss.pgh.pa.us        2365                 :CBC      356480 :     MemoryContextSwitchTo(oldcontext);
 9904                          2366                 :         356480 : }
                               2367                 :                : 
                               2368                 :                : /*
                               2369                 :                :  * tuplesort_restorepos - restores current position in merged sort file to
                               2370                 :                :  *                        last saved position
                               2371                 :                :  */
                               2372                 :                : void
                               2373                 :          28324 : tuplesort_restorepos(Tuplesortstate *state)
                               2374                 :                : {
 1585 akorotkov@postgresql     2375                 :          28324 :     MemoryContext oldcontext = MemoryContextSwitchTo(state->base.sortcontext);
                               2376                 :                : 
                               2377         [ -  + ]:          28324 :     Assert(state->base.sortopt & TUPLESORT_RANDOMACCESS);
                               2378                 :                : 
 9904 tgl@sss.pgh.pa.us        2379      [ +  +  - ]:          28324 :     switch (state->status)
                               2380                 :                :     {
                               2381                 :          24196 :         case TSS_SORTEDINMEM:
                               2382                 :          24196 :             state->current = state->markpos_offset;
                               2383                 :          24196 :             state->eof_reached = state->markpos_eof;
                               2384                 :          24196 :             break;
                               2385                 :           4128 :         case TSS_SORTEDONTAPE:
 1867 heikki.linnakangas@i     2386                 :           4128 :             LogicalTapeSeek(state->result_tape,
                               2387                 :                :                             state->markpos_block,
                               2388                 :                :                             state->markpos_offset);
 9904 tgl@sss.pgh.pa.us        2389                 :           4128 :             state->eof_reached = state->markpos_eof;
                               2390                 :           4128 :             break;
 9904 tgl@sss.pgh.pa.us        2391                 :UBC           0 :         default:
 8527                          2392         [ #  # ]:              0 :             elog(ERROR, "invalid tuplesort state");
                               2393                 :                :             break;
                               2394                 :                :     }
                               2395                 :                : 
 7580 tgl@sss.pgh.pa.us        2396                 :CBC       28324 :     MemoryContextSwitchTo(oldcontext);
 9904                          2397                 :          28324 : }
                               2398                 :                : 
                               2399                 :                : /*
                               2400                 :                :  * tuplesort_get_stats - extract summary statistics
                               2401                 :                :  *
                               2402                 :                :  * This can be called after tuplesort_performsort() finishes to obtain
                               2403                 :                :  * printable summary information about how the sort was performed.
                               2404                 :                :  */
                               2405                 :                : void
 6319                          2406                 :            264 : tuplesort_get_stats(Tuplesortstate *state,
                               2407                 :                :                     TuplesortInstrumentation *stats)
                               2408                 :                : {
                               2409                 :                :     /*
                               2410                 :                :      * Note: it might seem we should provide both memory and disk usage for a
                               2411                 :                :      * disk-based sort.  However, the current code doesn't track memory space
                               2412                 :                :      * accurately once we have begun to return tuples to the caller (since we
                               2413                 :                :      * don't account for pfree's the caller is expected to do), so we cannot
                               2414                 :                :      * rely on availMem in a disk sort.  This does not seem worth the overhead
                               2415                 :                :      * to fix.  Is it worth creating an API for the memory context code to
                               2416                 :                :      * tell us how much is actually used in sortcontext?
                               2417                 :                :      */
 2427 tomas.vondra@postgre     2418                 :            264 :     tuplesort_updatemax(state);
                               2419                 :                : 
                               2420         [ +  + ]:            264 :     if (state->isMaxSpaceDisk)
 3378 rhaas@postgresql.org     2421                 :              4 :         stats->spaceType = SORT_SPACE_TYPE_DISK;
                               2422                 :                :     else
                               2423                 :            260 :         stats->spaceType = SORT_SPACE_TYPE_MEMORY;
 2427 tomas.vondra@postgre     2424                 :            264 :     stats->spaceUsed = (state->maxSpace + 1023) / 1024;
                               2425                 :                : 
                               2426   [ +  -  +  - ]:            264 :     switch (state->maxSpaceStatus)
                               2427                 :                :     {
 7148 tgl@sss.pgh.pa.us        2428                 :            260 :         case TSS_SORTEDINMEM:
                               2429         [ +  + ]:            260 :             if (state->boundUsed)
 3378 rhaas@postgresql.org     2430                 :             28 :                 stats->sortMethod = SORT_TYPE_TOP_N_HEAPSORT;
                               2431                 :                :             else
                               2432                 :            232 :                 stats->sortMethod = SORT_TYPE_QUICKSORT;
 7148 tgl@sss.pgh.pa.us        2433                 :            260 :             break;
 7148 tgl@sss.pgh.pa.us        2434                 :UBC           0 :         case TSS_SORTEDONTAPE:
 3378 rhaas@postgresql.org     2435                 :              0 :             stats->sortMethod = SORT_TYPE_EXTERNAL_SORT;
 7148 tgl@sss.pgh.pa.us        2436                 :              0 :             break;
 7148 tgl@sss.pgh.pa.us        2437                 :CBC           4 :         case TSS_FINALMERGE:
 3378 rhaas@postgresql.org     2438                 :              4 :             stats->sortMethod = SORT_TYPE_EXTERNAL_MERGE;
 7148 tgl@sss.pgh.pa.us        2439                 :              4 :             break;
 7148 tgl@sss.pgh.pa.us        2440                 :UBC           0 :         default:
 3378 rhaas@postgresql.org     2441                 :              0 :             stats->sortMethod = SORT_TYPE_STILL_IN_PROGRESS;
 7148 tgl@sss.pgh.pa.us        2442                 :              0 :             break;
                               2443                 :                :     }
 7148 tgl@sss.pgh.pa.us        2444                 :CBC         264 : }
                               2445                 :                : 
                               2446                 :                : /*
                               2447                 :                :  * Convert TuplesortMethod to a string.
                               2448                 :                :  */
                               2449                 :                : const char *
 3378 rhaas@postgresql.org     2450                 :            196 : tuplesort_method_name(TuplesortMethod m)
                               2451                 :                : {
                               2452   [ -  +  +  -  :            196 :     switch (m)
                                              +  - ]
                               2453                 :                :     {
 3378 rhaas@postgresql.org     2454                 :UBC           0 :         case SORT_TYPE_STILL_IN_PROGRESS:
                               2455                 :              0 :             return "still in progress";
 3378 rhaas@postgresql.org     2456                 :CBC          28 :         case SORT_TYPE_TOP_N_HEAPSORT:
                               2457                 :             28 :             return "top-N heapsort";
                               2458                 :            164 :         case SORT_TYPE_QUICKSORT:
                               2459                 :            164 :             return "quicksort";
 3378 rhaas@postgresql.org     2460                 :UBC           0 :         case SORT_TYPE_EXTERNAL_SORT:
                               2461                 :              0 :             return "external sort";
 3378 rhaas@postgresql.org     2462                 :CBC           4 :         case SORT_TYPE_EXTERNAL_MERGE:
                               2463                 :              4 :             return "external merge";
                               2464                 :                :     }
                               2465                 :                : 
 3378 rhaas@postgresql.org     2466                 :UBC           0 :     return "unknown";
                               2467                 :                : }
                               2468                 :                : 
                               2469                 :                : /*
                               2470                 :                :  * Convert TuplesortSpaceType to a string.
                               2471                 :                :  */
                               2472                 :                : const char *
 3378 rhaas@postgresql.org     2473                 :CBC         172 : tuplesort_space_type_name(TuplesortSpaceType t)
                               2474                 :                : {
                               2475   [ +  +  -  + ]:            172 :     Assert(t == SORT_SPACE_TYPE_DISK || t == SORT_SPACE_TYPE_MEMORY);
                               2476         [ +  + ]:            172 :     return t == SORT_SPACE_TYPE_DISK ? "Disk" : "Memory";
                               2477                 :                : }
                               2478                 :                : 
                               2479                 :                : 
                               2480                 :                : /*
                               2481                 :                :  * Heap manipulation routines, per Knuth's Algorithm 5.2.3H.
                               2482                 :                :  */
                               2483                 :                : 
                               2484                 :                : /*
                               2485                 :                :  * Convert the existing unordered array of SortTuples to a bounded heap,
                               2486                 :                :  * discarding all but the smallest "state->bound" tuples.
                               2487                 :                :  *
                               2488                 :                :  * When working with a bounded heap, we want to keep the largest entry
                               2489                 :                :  * at the root (array entry zero), instead of the smallest as in the normal
                               2490                 :                :  * sort case.  This allows us to discard the largest entry cheaply.
                               2491                 :                :  * Therefore, we temporarily reverse the sort direction.
                               2492                 :                :  */
                               2493                 :                : static void
 7148 tgl@sss.pgh.pa.us        2494                 :            277 : make_bounded_heap(Tuplesortstate *state)
                               2495                 :                : {
 6953 bruce@momjian.us         2496                 :            277 :     int         tupcount = state->memtupcount;
                               2497                 :                :     int         i;
                               2498                 :                : 
 7148 tgl@sss.pgh.pa.us        2499         [ -  + ]:            277 :     Assert(state->status == TSS_INITIAL);
                               2500         [ -  + ]:            277 :     Assert(state->bounded);
                               2501         [ -  + ]:            277 :     Assert(tupcount >= state->bound);
 3221 rhaas@postgresql.org     2502         [ -  + ]:            277 :     Assert(SERIAL(state));
                               2503                 :                : 
                               2504                 :                :     /* Reverse sort direction so largest entry will be at root */
 4404                          2505                 :            277 :     reversedirection(state);
                               2506                 :                : 
 7148 tgl@sss.pgh.pa.us        2507                 :            277 :     state->memtupcount = 0;      /* make the heap empty */
 6953 bruce@momjian.us         2508         [ +  + ]:          34464 :     for (i = 0; i < tupcount; i++)
                               2509                 :                :     {
 3730 heikki.linnakangas@i     2510         [ +  + ]:          34187 :         if (state->memtupcount < state->bound)
                               2511                 :                :         {
                               2512                 :                :             /* Insert next tuple into heap */
                               2513                 :                :             /* Must copy source tuple to avoid possible overwrite */
 6953 bruce@momjian.us         2514                 :          16955 :             SortTuple   stup = state->memtuples[i];
                               2515                 :                : 
 3347 rhaas@postgresql.org     2516                 :          16955 :             tuplesort_heap_insert(state, &stup);
                               2517                 :                :         }
                               2518                 :                :         else
                               2519                 :                :         {
                               2520                 :                :             /*
                               2521                 :                :              * The heap is full.  Replace the largest entry with the new
                               2522                 :                :              * tuple, or just discard it, if it's larger than anything already
                               2523                 :                :              * in the heap.
                               2524                 :                :              */
 3730 heikki.linnakangas@i     2525         [ +  + ]:          17232 :             if (COMPARETUP(state, &state->memtuples[i], &state->memtuples[0]) <= 0)
                               2526                 :                :             {
                               2527                 :           7682 :                 free_sort_tuple(state, &state->memtuples[i]);
                               2528         [ -  + ]:           7682 :                 CHECK_FOR_INTERRUPTS();
                               2529                 :                :             }
                               2530                 :                :             else
 3347 rhaas@postgresql.org     2531                 :           9550 :                 tuplesort_heap_replace_top(state, &state->memtuples[i]);
                               2532                 :                :         }
                               2533                 :                :     }
                               2534                 :                : 
 7148 tgl@sss.pgh.pa.us        2535         [ -  + ]:            277 :     Assert(state->memtupcount == state->bound);
                               2536                 :            277 :     state->status = TSS_BOUNDED;
                               2537                 :            277 : }
                               2538                 :                : 
                               2539                 :                : /*
                               2540                 :                :  * Convert the bounded heap to a properly-sorted array
                               2541                 :                :  */
                               2542                 :                : static void
                               2543                 :            277 : sort_bounded_heap(Tuplesortstate *state)
                               2544                 :                : {
 6953 bruce@momjian.us         2545                 :            277 :     int         tupcount = state->memtupcount;
                               2546                 :                : 
 7148 tgl@sss.pgh.pa.us        2547         [ -  + ]:            277 :     Assert(state->status == TSS_BOUNDED);
                               2548         [ -  + ]:            277 :     Assert(state->bounded);
                               2549         [ -  + ]:            277 :     Assert(tupcount == state->bound);
 3221 rhaas@postgresql.org     2550         [ -  + ]:            277 :     Assert(SERIAL(state));
                               2551                 :                : 
                               2552                 :                :     /*
                               2553                 :                :      * We can unheapify in place because each delete-top call will remove the
                               2554                 :                :      * largest entry, which we can promptly store in the newly freed slot at
                               2555                 :                :      * the end.  Once we're down to a single-entry heap, we're done.
                               2556                 :                :      */
 7148 tgl@sss.pgh.pa.us        2557         [ +  + ]:          16955 :     while (state->memtupcount > 1)
                               2558                 :                :     {
 6953 bruce@momjian.us         2559                 :          16678 :         SortTuple   stup = state->memtuples[0];
                               2560                 :                : 
                               2561                 :                :         /* this sifts-up the next-largest entry and decreases memtupcount */
 3347 rhaas@postgresql.org     2562                 :          16678 :         tuplesort_heap_delete_top(state);
 7148 tgl@sss.pgh.pa.us        2563                 :          16678 :         state->memtuples[state->memtupcount] = stup;
                               2564                 :                :     }
                               2565                 :            277 :     state->memtupcount = tupcount;
                               2566                 :                : 
                               2567                 :                :     /*
                               2568                 :                :      * Reverse sort direction back to the original state.  This is not
                               2569                 :                :      * actually necessary but seems like a good idea for tidiness.
                               2570                 :                :      */
 4404 rhaas@postgresql.org     2571                 :            277 :     reversedirection(state);
                               2572                 :                : 
 7148 tgl@sss.pgh.pa.us        2573                 :            277 :     state->status = TSS_SORTEDINMEM;
                               2574                 :            277 :     state->boundUsed = true;
                               2575                 :            277 : }
                               2576                 :                : 
                               2577                 :                : 
                               2578                 :                : /* radix sort routines */
                               2579                 :                : 
                               2580                 :                : /*
                               2581                 :                :  * Retrieve byte from datum, indexed by 'level': 0 for MSB, 7 for LSB
                               2582                 :                :  */
                               2583                 :                : static inline uint8
  287 john.naylor@postgres     2584                 :       26973145 : current_byte(Datum key, int level)
                               2585                 :                : {
                               2586                 :       26973145 :     int         shift = (sizeof(Datum) - 1 - level) * BITS_PER_BYTE;
                               2587                 :                : 
                               2588                 :       26973145 :     return (key >> shift) & 0xFF;
                               2589                 :                : }
                               2590                 :                : 
                               2591                 :                : /*
                               2592                 :                :  * Normalize datum such that unsigned comparison is order-preserving,
                               2593                 :                :  * taking ASC/DESC into account as well.
                               2594                 :                :  */
                               2595                 :                : static inline Datum
                               2596                 :       27021112 : normalize_datum(Datum orig, SortSupport ssup)
                               2597                 :                : {
                               2598                 :                :     Datum       norm_datum1;
                               2599                 :                : 
  110 john.naylor@postgres     2600         [ +  + ]:GNC    27021112 :     if (ssup->comparator == ssup_datum_int64_cmp)
  213 john.naylor@postgres     2601                 :CBC     1081392 :         norm_datum1 = orig + (Int64GetDatum(PG_INT64_MAX)) + 1;
  110 john.naylor@postgres     2602         [ +  + ]:GNC    25939720 :     else if (ssup->comparator == ssup_datum_uint64_cmp)
                               2603                 :        6959991 :         norm_datum1 = orig;
                               2604                 :                :     else
                               2605                 :                :     {
                               2606                 :                :         /*
                               2607                 :                :          * Truncate to uint32. For the int32 case, we don't need to do this,
                               2608                 :                :          * but it forces the upper half of the datum to be zero regardless of
                               2609                 :                :          * sign.
                               2610                 :                :          */
                               2611                 :       18979729 :         uint32      u32 = DatumGetUInt32(orig);
                               2612                 :                : 
                               2613         [ +  + ]:       18979729 :         if (ssup->comparator == ssup_datum_int32_cmp)
                               2614                 :        7795024 :             norm_datum1 = UInt32GetDatum(u32 + ((uint32) PG_INT32_MAX) + 1);
                               2615                 :                :         else
                               2616                 :                :         {
                               2617                 :       11184705 :             norm_datum1 = UInt32GetDatum(u32);
                               2618         [ -  + ]:       11184705 :             Assert(ssup->comparator == ssup_datum_uint32_cmp);
                               2619                 :                :         }
                               2620                 :                :     }
                               2621                 :                : 
  287 john.naylor@postgres     2622         [ +  + ]:CBC    27021112 :     if (ssup->ssup_reverse)
                               2623                 :         788276 :         norm_datum1 = ~norm_datum1;
                               2624                 :                : 
                               2625                 :       27021112 :     return norm_datum1;
                               2626                 :                : }
                               2627                 :                : 
                               2628                 :                : /*
                               2629                 :                :  * radix_sort_recursive
                               2630                 :                :  *
                               2631                 :                :  * Radix sort by (pass-by-value) datum1, diverting to qsort_tuple()
                               2632                 :                :  * for tiebreaks.
                               2633                 :                :  *
                               2634                 :                :  * This is a modification of ska_byte_sort() from
                               2635                 :                :  * https://github.com/skarupke/ska_sort
                               2636                 :                :  * The original copyright notice follows:
                               2637                 :                :  *
                               2638                 :                :  * Copyright Malte Skarupke 2016.
                               2639                 :                :  * Distributed under the Boost Software License, Version 1.0.
                               2640                 :                :  *
                               2641                 :                :  * Boost Software License - Version 1.0 - August 17th, 2003
                               2642                 :                :  *
                               2643                 :                :  * Permission is hereby granted, free of charge, to any person or organization
                               2644                 :                :  * obtaining a copy of the software and accompanying documentation covered by
                               2645                 :                :  * this license (the "Software") to use, reproduce, display, distribute,
                               2646                 :                :  * execute, and transmit the Software, and to prepare derivative works of the
                               2647                 :                :  * Software, and to permit third-parties to whom the Software is furnished to
                               2648                 :                :  * do so, all subject to the following:
                               2649                 :                :  *
                               2650                 :                :  * The copyright notices in the Software and this entire statement, including
                               2651                 :                :  * the above license grant, this restriction and the following disclaimer,
                               2652                 :                :  * must be included in all copies of the Software, in whole or in part, and
                               2653                 :                :  * all derivative works of the Software, unless such copies or derivative
                               2654                 :                :  * works are solely in the form of machine-executable object code generated by
                               2655                 :                :  * a source language processor.
                               2656                 :                :  *
                               2657                 :                :  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
                               2658                 :                :  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
                               2659                 :                :  * FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
                               2660                 :                :  * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
                               2661                 :                :  * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
                               2662                 :                :  * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
                               2663                 :                :  * DEALINGS IN THE SOFTWARE.
                               2664                 :                :  */
                               2665                 :                : static void
                               2666                 :          47967 : radix_sort_recursive(SortTuple *begin, size_t n_elems, int level, Tuplesortstate *state)
                               2667                 :                : {
                               2668                 :          47967 :     RadixSortInfo partitions[256] = {0};
                               2669                 :                :     uint8       remaining_partitions[256];
                               2670                 :          47967 :     size_t      total = 0;
                               2671                 :          47967 :     int         num_partitions = 0;
                               2672                 :                :     int         num_remaining;
                               2673                 :          47967 :     SortSupport ssup = &state->base.sortKeys[0];
                               2674                 :                :     Datum       ref_datum;
  241                          2675                 :          47967 :     Datum       common_upper_bits = 0;
  287                          2676                 :          47967 :     size_t      start_offset = 0;
                               2677                 :          47967 :     SortTuple  *partition_begin = begin;
                               2678                 :                :     int         next_level;
                               2679                 :                : 
                               2680                 :                :     /* count number of occurrences of each byte */
  241                          2681                 :          47967 :     ref_datum = normalize_datum(begin[0].datum1, ssup);
  287                          2682         [ +  + ]:       27021112 :     for (SortTuple *st = begin; st < begin + n_elems; st++)
                               2683                 :                :     {
                               2684                 :                :         Datum       this_datum;
                               2685                 :                :         uint8       this_partition;
                               2686                 :                : 
  241                          2687                 :       26973145 :         this_datum = normalize_datum(st->datum1, ssup);
                               2688                 :                :         /* accumulate bits different from the reference datum */
                               2689                 :       26973145 :         common_upper_bits |= ref_datum ^ this_datum;
                               2690                 :                : 
                               2691                 :                :         /* extract the byte for this level from the normalized datum */
                               2692                 :       26973145 :         this_partition = current_byte(this_datum, level);
                               2693                 :                : 
                               2694                 :                :         /* save it for the permutation step */
  287                          2695                 :       26973145 :         st->curbyte = this_partition;
                               2696                 :                : 
                               2697                 :       26973145 :         partitions[this_partition].count++;
                               2698                 :                : 
                               2699         [ +  + ]:       26973145 :         CHECK_FOR_INTERRUPTS();
                               2700                 :                :     }
                               2701                 :                : 
                               2702                 :                :     /* compute partition offsets */
                               2703         [ +  + ]:       12327519 :     for (int i = 0; i < 256; i++)
                               2704                 :                :     {
                               2705                 :       12279552 :         size_t      count = partitions[i].count;
                               2706                 :                : 
                               2707         [ +  + ]:       12279552 :         if (count != 0)
                               2708                 :                :         {
                               2709                 :        2644029 :             partitions[i].offset = total;
                               2710                 :        2644029 :             total += count;
                               2711                 :        2644029 :             remaining_partitions[num_partitions] = i;
                               2712                 :        2644029 :             num_partitions++;
                               2713                 :                :         }
                               2714                 :       12279552 :         partitions[i].next_offset = total;
                               2715                 :                :     }
                               2716                 :                : 
                               2717                 :                :     /*
                               2718                 :                :      * Swap tuples to correct partition.
                               2719                 :                :      *
                               2720                 :                :      * In traditional American flag sort, a swap sends the current element to
                               2721                 :                :      * the correct partition, but the array pointer only advances if the
                               2722                 :                :      * partner of the swap happens to be an element that belongs in the
                               2723                 :                :      * current partition. That only requires one pass through the array, but
                               2724                 :                :      * the disadvantage is we don't know if the pointer can advance until the
                               2725                 :                :      * swap completes. Here lies the most interesting innovation from the
                               2726                 :                :      * upstream ska_byte_sort: After initiating the swap, we immediately
                               2727                 :                :      * proceed to the next element. This makes better use of CPU pipelining,
                               2728                 :                :      * but also means that we will often need multiple iterations of this
                               2729                 :                :      * loop. ska_byte_sort() maintains a separate list of which partitions
                               2730                 :                :      * haven't finished, which is updated every loop iteration. Here we simply
                               2731                 :                :      * check each partition during every iteration.
                               2732                 :                :      *
                               2733                 :                :      * If we started with a single partition, there is nothing to do. If a
                               2734                 :                :      * previous loop iteration results in only one partition that hasn't been
                               2735                 :                :      * counted as sorted, we know it's actually sorted and can exit the loop.
                               2736                 :                :      */
                               2737                 :          47967 :     num_remaining = num_partitions;
                               2738         [ +  + ]:         197724 :     while (num_remaining > 1)
                               2739                 :                :     {
                               2740                 :                :         /* start the count over */
                               2741                 :         149757 :         num_remaining = num_partitions;
                               2742                 :                : 
                               2743         [ +  + ]:       11679246 :         for (int i = 0; i < num_partitions; i++)
                               2744                 :                :         {
                               2745                 :       11529489 :             uint8       idx = remaining_partitions[i];
                               2746                 :                : 
                               2747                 :       11529489 :             for (SortTuple *st = begin + partitions[idx].offset;
                               2748         [ +  + ]:       28998871 :                  st < begin + partitions[idx].next_offset;
                               2749                 :       17469382 :                  st++)
                               2750                 :                :             {
                               2751                 :       17469382 :                 size_t      offset = partitions[st->curbyte].offset++;
                               2752                 :                :                 SortTuple   tmp;
                               2753                 :                : 
                               2754                 :                :                 /* swap current tuple with destination position */
                               2755         [ -  + ]:       17469382 :                 Assert(offset < n_elems);
                               2756                 :       17469382 :                 tmp = *st;
                               2757                 :       17469382 :                 *st = begin[offset];
                               2758                 :       17469382 :                 begin[offset] = tmp;
                               2759                 :                : 
                               2760         [ +  + ]:       17469382 :                 CHECK_FOR_INTERRUPTS();
                               2761                 :                :             };
                               2762                 :                : 
                               2763                 :                :             /* Is this partition sorted? */
                               2764         [ +  + ]:       11529489 :             if (partitions[idx].offset == partitions[idx].next_offset)
                               2765                 :        8884855 :                 num_remaining--;
                               2766                 :                :         }
                               2767                 :                :     }
                               2768                 :                : 
                               2769                 :                :     /* recurse */
                               2770                 :                : 
  241                          2771         [ +  + ]:          47967 :     if (num_partitions == 1)
                               2772                 :                :     {
                               2773                 :                :         /*
                               2774                 :                :          * There is only one distinct byte at the current level. It can happen
                               2775                 :                :          * that some subsequent bytes are also the same for all input values,
                               2776                 :                :          * such as the upper bytes of small integers. To skip unproductive
                               2777                 :                :          * passes for that case, we compute the level where the input has more
                               2778                 :                :          * than one distinct byte, so that the next recursion can start there.
                               2779                 :                :          */
                               2780         [ +  + ]:           9462 :         if (common_upper_bits == 0)
                               2781                 :           1039 :             next_level = sizeof(Datum);
                               2782                 :                :         else
                               2783                 :                :         {
                               2784                 :                :             int         diffpos;
                               2785                 :                : 
                               2786                 :                :             /*
                               2787                 :                :              * The upper bits of common_upper_bits are zero where all datums
                               2788                 :                :              * have the same bits.
                               2789                 :                :              */
                               2790                 :           8423 :             diffpos = pg_leftmost_one_pos64(DatumGetUInt64(common_upper_bits));
                               2791                 :           8423 :             next_level = sizeof(Datum) - 1 - (diffpos / BITS_PER_BYTE);
                               2792                 :                :         }
                               2793                 :                :     }
                               2794                 :                :     else
                               2795                 :          38505 :         next_level = level + 1;
                               2796                 :                : 
  213                          2797         [ -  + ]:          47967 :     Assert(next_level > level);
                               2798                 :                : 
  287                          2799                 :          47967 :     for (uint8 *rp = remaining_partitions;
                               2800         [ +  + ]:        2691996 :          rp < remaining_partitions + num_partitions;
                               2801                 :        2644029 :          rp++)
                               2802                 :                :     {
                               2803                 :        2644029 :         size_t      end_offset = partitions[*rp].next_offset;
                               2804                 :        2644029 :         SortTuple  *partition_end = begin + end_offset;
                               2805                 :        2644029 :         size_t      num_elements = end_offset - start_offset;
                               2806                 :                : 
                               2807         [ +  + ]:        2644029 :         if (num_elements > 1)
                               2808                 :                :         {
  241                          2809         [ +  + ]:         871480 :             if (next_level < sizeof(Datum))
                               2810                 :                :             {
  287                          2811         [ +  + ]:         683697 :                 if (num_elements < QSORT_THRESHOLD)
                               2812                 :                :                 {
                               2813                 :         641367 :                     qsort_tuple(partition_begin,
                               2814                 :                :                                 num_elements,
                               2815                 :                :                                 state->base.comparetup,
                               2816                 :                :                                 state);
                               2817                 :                :                 }
                               2818                 :                :                 else
                               2819                 :                :                 {
                               2820                 :          42330 :                     radix_sort_recursive(partition_begin,
                               2821                 :                :                                          num_elements,
                               2822                 :                :                                          next_level,
                               2823                 :                :                                          state);
                               2824                 :                :                 }
                               2825                 :                :             }
                               2826         [ +  + ]:         187783 :             else if (state->base.onlyKey == NULL)
                               2827                 :                :             {
                               2828                 :                :                 /*
                               2829                 :                :                  * We've finished radix sort on all bytes of the pass-by-value
                               2830                 :                :                  * datum (possibly abbreviated), now sort using the tiebreak
                               2831                 :                :                  * comparator.
                               2832                 :                :                  */
                               2833                 :          93703 :                 qsort_tuple(partition_begin,
                               2834                 :                :                             num_elements,
                               2835                 :                :                             state->base.comparetup_tiebreak,
                               2836                 :                :                             state);
                               2837                 :                :             }
                               2838                 :                :         }
                               2839                 :                : 
                               2840                 :        2644029 :         start_offset = end_offset;
                               2841                 :        2644029 :         partition_begin = partition_end;
                               2842                 :                :     }
                               2843                 :          47967 : }
                               2844                 :                : 
                               2845                 :                : /*
                               2846                 :                :  * Entry point for radix_sort_recursive
                               2847                 :                :  *
                               2848                 :                :  * Partition tuples by isnull1, then sort both partitions, using
                               2849                 :                :  * radix sort on the NOT NULL partition if it's large enough.
                               2850                 :                :  */
                               2851                 :                : static void
                               2852                 :           7667 : radix_sort_tuple(SortTuple *data, size_t n, Tuplesortstate *state)
                               2853                 :                : {
                               2854                 :           7667 :     bool        nulls_first = state->base.sortKeys[0].ssup_nulls_first;
                               2855                 :                :     SortTuple  *null_start;
                               2856                 :                :     SortTuple  *not_null_start;
                               2857                 :           7667 :     size_t      d1 = 0,
                               2858                 :                :                 d2,
                               2859                 :                :                 null_count,
                               2860                 :                :                 not_null_count;
                               2861                 :                : 
                               2862                 :                :     /*
                               2863                 :                :      * Find the first NOT NULL if NULLS FIRST, or first NULL if NULLS LAST.
                               2864                 :                :      * This also serves as a quick check for the common case where all tuples
                               2865                 :                :      * are NOT NULL in the first sort key with the default order ASC NULLS
                               2866                 :                :      * LAST.
                               2867                 :                :      */
                               2868   [ +  +  +  + ]:       13533818 :     while (d1 < n && data[d1].isnull1 == nulls_first)
                               2869                 :                :     {
                               2870                 :       13526151 :         d1++;
                               2871         [ +  + ]:       13526151 :         CHECK_FOR_INTERRUPTS();
                               2872                 :                :     }
                               2873                 :                : 
                               2874                 :                :     /*
                               2875                 :                :      * If we have more than one tuple left after the quick check, partition
                               2876                 :                :      * the remainder using branchless cyclic permutation, based on
                               2877                 :                :      * https://orlp.net/blog/branchless-lomuto-partitioning/
                               2878                 :                :      */
                               2879         [ -  + ]:           7667 :     Assert(n > 0);
                               2880         [ +  + ]:           7667 :     if (d1 < n - 1)
                               2881                 :                :     {
                               2882                 :            740 :         size_t      i = d1,
                               2883                 :            740 :                     j = d1;
                               2884                 :            740 :         SortTuple   tmp = data[d1]; /* create gap at front */
                               2885                 :                : 
                               2886         [ +  + ]:         435552 :         while (j < n - 1)
                               2887                 :                :         {
                               2888                 :                :             /* gap is at j, move i's element to gap */
                               2889                 :         434812 :             data[j] = data[i];
                               2890                 :                :             /* advance j to the first unknown element */
                               2891                 :         434812 :             j += 1;
                               2892                 :                :             /* move the first unknown element back to i */
                               2893                 :         434812 :             data[i] = data[j];
                               2894                 :                :             /* advance i if this element belongs in the left partition */
                               2895                 :         434812 :             i += (data[i].isnull1 == nulls_first);
                               2896                 :                : 
                               2897         [ -  + ]:         434812 :             CHECK_FOR_INTERRUPTS();
                               2898                 :                :         }
                               2899                 :                : 
                               2900                 :                :         /* place gap between left and right partitions */
                               2901                 :            740 :         data[j] = data[i];
                               2902                 :                :         /* restore the saved element */
                               2903                 :            740 :         data[i] = tmp;
                               2904                 :                :         /* assign it to the correct partition */
                               2905                 :            740 :         i += (data[i].isnull1 == nulls_first);
                               2906                 :                : 
                               2907                 :                :         /* d1 is now the number of elements in the left partition */
                               2908                 :            740 :         d1 = i;
                               2909                 :                :     }
                               2910                 :                : 
                               2911                 :           7667 :     d2 = n - d1;
                               2912                 :                : 
                               2913                 :                :     /* set pointers and counts for each partition */
                               2914         [ +  + ]:           7667 :     if (nulls_first)
                               2915                 :                :     {
                               2916                 :            631 :         null_start = data;
                               2917                 :            631 :         null_count = d1;
                               2918                 :            631 :         not_null_start = data + d1;
                               2919                 :            631 :         not_null_count = d2;
                               2920                 :                :     }
                               2921                 :                :     else
                               2922                 :                :     {
                               2923                 :           7036 :         not_null_start = data;
                               2924                 :           7036 :         not_null_count = d1;
                               2925                 :           7036 :         null_start = data + d1;
                               2926                 :           7036 :         null_count = d2;
                               2927                 :                :     }
                               2928                 :                : 
                               2929                 :           7667 :     for (SortTuple *st = null_start;
                               2930         [ +  + ]:          11560 :          st < null_start + null_count;
                               2931                 :           3893 :          st++)
                               2932         [ -  + ]:           3893 :         Assert(st->isnull1 == true);
                               2933                 :           7667 :     for (SortTuple *st = not_null_start;
                               2934         [ +  + ]:       13965481 :          st < not_null_start + not_null_count;
                               2935                 :       13957814 :          st++)
                               2936         [ -  + ]:       13957814 :         Assert(st->isnull1 == false);
                               2937                 :                : 
                               2938                 :                :     /*
                               2939                 :                :      * Sort the NULL partition using tiebreak comparator, if necessary.
                               2940                 :                :      */
                               2941   [ +  +  +  + ]:           7667 :     if (state->base.onlyKey == NULL && null_count > 1)
                               2942                 :                :     {
                               2943                 :            111 :         qsort_tuple(null_start,
                               2944                 :                :                     null_count,
                               2945                 :                :                     state->base.comparetup_tiebreak,
                               2946                 :                :                     state);
                               2947                 :                :     }
                               2948                 :                : 
                               2949                 :                :     /*
                               2950                 :                :      * Sort the NOT NULL partition, using radix sort if large enough,
                               2951                 :                :      * otherwise fall back to quicksort.
                               2952                 :                :      */
                               2953         [ +  + ]:           7667 :     if (not_null_count < QSORT_THRESHOLD)
                               2954                 :                :     {
                               2955                 :             18 :         qsort_tuple(not_null_start,
                               2956                 :                :                     not_null_count,
                               2957                 :                :                     state->base.comparetup,
                               2958                 :                :                     state);
                               2959                 :                :     }
                               2960                 :                :     else
                               2961                 :                :     {
                               2962                 :           7649 :         bool        presorted = true;
                               2963                 :                : 
                               2964                 :           7649 :         for (SortTuple *st = not_null_start + 1;
                               2965         [ +  + ]:        5140665 :              st < not_null_start + not_null_count;
                               2966                 :        5133016 :              st++)
                               2967                 :                :         {
                               2968         [ +  + ]:        5138653 :             if (COMPARETUP(state, st - 1, st) > 0)
                               2969                 :                :             {
                               2970                 :           5637 :                 presorted = false;
                               2971                 :           5637 :                 break;
                               2972                 :                :             }
                               2973                 :                : 
                               2974         [ -  + ]:        5133016 :             CHECK_FOR_INTERRUPTS();
                               2975                 :                :         }
                               2976                 :                : 
                               2977         [ +  + ]:           7649 :         if (presorted)
                               2978                 :           2012 :             return;
                               2979                 :                :         else
                               2980                 :                :         {
                               2981                 :           5637 :             radix_sort_recursive(not_null_start,
                               2982                 :                :                                  not_null_count,
                               2983                 :                :                                  0,
                               2984                 :                :                                  state);
                               2985                 :                :         }
                               2986                 :                :     }
                               2987                 :                : }
                               2988                 :                : 
                               2989                 :                : /* Verify in-memory sort using standard comparator. */
                               2990                 :                : static void
                               2991                 :           7667 : verify_memtuples_sorted(Tuplesortstate *state)
                               2992                 :                : {
                               2993                 :                : #ifdef USE_ASSERT_CHECKING
                               2994                 :           7667 :     for (SortTuple *st = state->memtuples + 1;
                               2995         [ +  + ]:       13961707 :          st < state->memtuples + state->memtupcount;
                               2996                 :       13954040 :          st++)
                               2997         [ -  + ]:       13954040 :         Assert(COMPARETUP(state, st - 1, st) <= 0);
                               2998                 :                : #endif
                               2999                 :           7667 : }
                               3000                 :                : 
                               3001                 :                : /*
                               3002                 :                :  * Sort all memtuples using specialized routines.
                               3003                 :                :  *
                               3004                 :                :  * Quicksort or radix sort is used for small in-memory sorts,
                               3005                 :                :  * and external sort runs.
                               3006                 :                :  */
                               3007                 :                : static void
 3886 rhaas@postgresql.org     3008                 :         150265 : tuplesort_sort_memtuples(Tuplesortstate *state)
                               3009                 :                : {
 3221                          3010   [ +  +  -  + ]:         150265 :     Assert(!LEADER(state));
                               3011                 :                : 
 3886                          3012         [ +  + ]:         150265 :     if (state->memtupcount > 1)
                               3013                 :                :     {
                               3014                 :                :         /*
                               3015                 :                :          * Do we have the leading column's value or abbreviation in datum1?
                               3016                 :                :          */
 1585 akorotkov@postgresql     3017   [ +  +  +  + ]:          44977 :         if (state->base.haveDatum1 && state->base.sortKeys)
                               3018                 :                :         {
  287 john.naylor@postgres     3019                 :          44894 :             SortSupport ssup = &state->base.sortKeys[0];
                               3020                 :                : 
                               3021                 :                :             /* Does it compare as an integer? */
                               3022         [ +  + ]:          44894 :             if (state->memtupcount >= QSORT_THRESHOLD &&
  110 john.naylor@postgres     3023         [ +  + ]:GNC        8786 :                 (ssup->comparator == ssup_datum_uint64_cmp ||
                               3024         [ +  + ]:           8219 :                  ssup->comparator == ssup_datum_int64_cmp ||
                               3025         [ +  + ]:           8037 :                  ssup->comparator == ssup_datum_uint32_cmp ||
  287 john.naylor@postgres     3026         [ +  + ]:CBC        4367 :                  ssup->comparator == ssup_datum_int32_cmp))
                               3027                 :                :             {
                               3028                 :           7667 :                 radix_sort_tuple(state->memtuples,
                               3029                 :           7667 :                                  state->memtupcount,
                               3030                 :                :                                  state);
                               3031                 :           7667 :                 verify_memtuples_sorted(state);
 1699 tmunro@postgresql.or     3032                 :           7667 :                 return;
                               3033                 :                :             }
                               3034                 :                :         }
                               3035                 :                : 
                               3036                 :                :         /* Can we use the single-key sort function? */
 1585 akorotkov@postgresql     3037         [ +  + ]:          37310 :         if (state->base.onlyKey != NULL)
                               3038                 :                :         {
 3886 rhaas@postgresql.org     3039                 :          26756 :             qsort_ssup(state->memtuples, state->memtupcount,
 1585 akorotkov@postgresql     3040                 :          26756 :                        state->base.onlyKey);
                               3041                 :                :         }
                               3042                 :                :         else
                               3043                 :                :         {
 3886 rhaas@postgresql.org     3044                 :          10554 :             qsort_tuple(state->memtuples,
                               3045                 :          10554 :                         state->memtupcount,
                               3046                 :                :                         state->base.comparetup,
                               3047                 :                :                         state);
                               3048                 :                :         }
                               3049                 :                :     }
                               3050                 :                : }
                               3051                 :                : 
                               3052                 :                : /*
                               3053                 :                :  * Insert a new tuple into an empty or existing heap, maintaining the
                               3054                 :                :  * heap invariant.  Caller is responsible for ensuring there's room.
                               3055                 :                :  *
                               3056                 :                :  * Note: For some callers, tuple points to a memtuples[] entry above the
                               3057                 :                :  * end of the heap.  This is safe as long as it's not immediately adjacent
                               3058                 :                :  * to the end of the heap (ie, in the [memtupcount] array entry) --- if it
                               3059                 :                :  * is, it might get overwritten before being moved into the heap!
                               3060                 :                :  */
                               3061                 :                : static void
 3347                          3062                 :          17954 : tuplesort_heap_insert(Tuplesortstate *state, SortTuple *tuple)
                               3063                 :                : {
                               3064                 :                :     SortTuple  *memtuples;
                               3065                 :                :     int         j;
                               3066                 :                : 
 9891 tgl@sss.pgh.pa.us        3067                 :          17954 :     memtuples = state->memtuples;
 7580                          3068         [ -  + ]:          17954 :     Assert(state->memtupcount < state->memtupsize);
                               3069                 :                : 
 5366 rhaas@postgresql.org     3070         [ +  + ]:          17954 :     CHECK_FOR_INTERRUPTS();
                               3071                 :                : 
                               3072                 :                :     /*
                               3073                 :                :      * Sift-up the new entry, per Knuth 5.2.3 exercise 16. Note that Knuth is
                               3074                 :                :      * using 1-based array indexes, not 0-based.
                               3075                 :                :      */
 9891 tgl@sss.pgh.pa.us        3076                 :          17954 :     j = state->memtupcount++;
                               3077         [ +  + ]:          47713 :     while (j > 0)
                               3078                 :                :     {
 9726 bruce@momjian.us         3079                 :          43442 :         int         i = (j - 1) >> 1;
                               3080                 :                : 
 3347 rhaas@postgresql.org     3081         [ +  + ]:          43442 :         if (COMPARETUP(state, tuple, &memtuples[i]) >= 0)
 9904 tgl@sss.pgh.pa.us        3082                 :          13683 :             break;
 9891                          3083                 :          29759 :         memtuples[j] = memtuples[i];
 9904                          3084                 :          29759 :         j = i;
                               3085                 :                :     }
 7580                          3086                 :          17954 :     memtuples[j] = *tuple;
 9904                          3087                 :          17954 : }
                               3088                 :                : 
                               3089                 :                : /*
                               3090                 :                :  * Remove the tuple at state->memtuples[0] from the heap.  Decrement
                               3091                 :                :  * memtupcount, and sift up to maintain the heap invariant.
                               3092                 :                :  *
                               3093                 :                :  * The caller has already free'd the tuple the top node points to,
                               3094                 :                :  * if necessary.
                               3095                 :                :  */
                               3096                 :                : static void
 3347 rhaas@postgresql.org     3097                 :          17657 : tuplesort_heap_delete_top(Tuplesortstate *state)
                               3098                 :                : {
 7580 tgl@sss.pgh.pa.us        3099                 :          17657 :     SortTuple  *memtuples = state->memtuples;
                               3100                 :                :     SortTuple  *tuple;
                               3101                 :                : 
 9891                          3102         [ +  + ]:          17657 :     if (--state->memtupcount <= 0)
 9904                          3103                 :            260 :         return;
                               3104                 :                : 
                               3105                 :                :     /*
                               3106                 :                :      * Remove the last tuple in the heap, and re-insert it, by replacing the
                               3107                 :                :      * current top node with it.
                               3108                 :                :      */
 3730 heikki.linnakangas@i     3109                 :          17397 :     tuple = &memtuples[state->memtupcount];
 3347 rhaas@postgresql.org     3110                 :          17397 :     tuplesort_heap_replace_top(state, tuple);
                               3111                 :                : }
                               3112                 :                : 
                               3113                 :                : /*
                               3114                 :                :  * Replace the tuple at state->memtuples[0] with a new tuple.  Sift up to
                               3115                 :                :  * maintain the heap invariant.
                               3116                 :                :  *
                               3117                 :                :  * This corresponds to Knuth's "sift-up" algorithm (Algorithm 5.2.3H,
                               3118                 :                :  * Heapsort, steps H3-H8).
                               3119                 :                :  */
                               3120                 :                : static void
                               3121                 :        4087919 : tuplesort_heap_replace_top(Tuplesortstate *state, SortTuple *tuple)
                               3122                 :                : {
 3730 heikki.linnakangas@i     3123                 :        4087919 :     SortTuple  *memtuples = state->memtuples;
                               3124                 :                :     unsigned int i,
                               3125                 :                :                 n;
                               3126                 :                : 
                               3127         [ -  + ]:        4087919 :     Assert(state->memtupcount >= 1);
                               3128                 :                : 
 5366 rhaas@postgresql.org     3129         [ +  + ]:        4087919 :     CHECK_FOR_INTERRUPTS();
                               3130                 :                : 
                               3131                 :                :     /*
                               3132                 :                :      * state->memtupcount is "int", but we use "unsigned int" for i, j, n.
                               3133                 :                :      * This prevents overflow in the "2 * i + 1" calculation, since at the top
                               3134                 :                :      * of the loop we must have i < n <= INT_MAX <= UINT_MAX/2.
                               3135                 :                :      */
 9891 tgl@sss.pgh.pa.us        3136                 :        4087919 :     n = state->memtupcount;
 9904                          3137                 :        4087919 :     i = 0;                      /* i is where the "hole" is */
                               3138                 :                :     for (;;)
 9891                          3139                 :        1362538 :     {
 3426                          3140                 :        5450457 :         unsigned int j = 2 * i + 1;
                               3141                 :                : 
 9904                          3142         [ +  + ]:        5450457 :         if (j >= n)
                               3143                 :        1009351 :             break;
 9726 bruce@momjian.us         3144   [ +  +  +  + ]:        6077108 :         if (j + 1 < n &&
 3347 rhaas@postgresql.org     3145                 :        1636002 :             COMPARETUP(state, &memtuples[j], &memtuples[j + 1]) > 0)
 9904 tgl@sss.pgh.pa.us        3146                 :         661702 :             j++;
 3347 rhaas@postgresql.org     3147         [ +  + ]:        4441106 :         if (COMPARETUP(state, tuple, &memtuples[j]) <= 0)
 9904 tgl@sss.pgh.pa.us        3148                 :        3078568 :             break;
 9891                          3149                 :        1362538 :         memtuples[i] = memtuples[j];
 9904                          3150                 :        1362538 :         i = j;
                               3151                 :                :     }
 7580                          3152                 :        4087919 :     memtuples[i] = *tuple;
 9904                          3153                 :        4087919 : }
                               3154                 :                : 
                               3155                 :                : /*
                               3156                 :                :  * Function to reverse the sort direction from its current state
                               3157                 :                :  *
                               3158                 :                :  * It is not safe to call this when performing hash tuplesorts
                               3159                 :                :  */
                               3160                 :                : static void
 4404 rhaas@postgresql.org     3161                 :            554 : reversedirection(Tuplesortstate *state)
                               3162                 :                : {
 1585 akorotkov@postgresql     3163                 :            554 :     SortSupport sortKey = state->base.sortKeys;
                               3164                 :                :     int         nkey;
                               3165                 :                : 
                               3166         [ +  + ]:           1340 :     for (nkey = 0; nkey < state->base.nKeys; nkey++, sortKey++)
                               3167                 :                :     {
 4404 rhaas@postgresql.org     3168                 :            786 :         sortKey->ssup_reverse = !sortKey->ssup_reverse;
                               3169                 :            786 :         sortKey->ssup_nulls_first = !sortKey->ssup_nulls_first;
                               3170                 :                :     }
                               3171                 :            554 : }
                               3172                 :                : 
                               3173                 :                : 
                               3174                 :                : /*
                               3175                 :                :  * Tape interface routines
                               3176                 :                :  */
                               3177                 :                : 
                               3178                 :                : static unsigned int
 1867 heikki.linnakangas@i     3179                 :        3925604 : getlen(LogicalTape *tape, bool eofOK)
                               3180                 :                : {
                               3181                 :                :     unsigned int len;
                               3182                 :                : 
                               3183         [ -  + ]:        3925604 :     if (LogicalTapeRead(tape,
                               3184                 :                :                         &len, sizeof(len)) != sizeof(len))
 8527 tgl@sss.pgh.pa.us        3185         [ #  # ]:UBC           0 :         elog(ERROR, "unexpected end of tape");
 9904 tgl@sss.pgh.pa.us        3186   [ +  +  -  + ]:CBC     3925604 :     if (len == 0 && !eofOK)
 8527 tgl@sss.pgh.pa.us        3187         [ #  # ]:UBC           0 :         elog(ERROR, "unexpected end of data");
 9904 tgl@sss.pgh.pa.us        3188                 :CBC     3925604 :     return len;
                               3189                 :                : }
                               3190                 :                : 
                               3191                 :                : static void
 1867 heikki.linnakangas@i     3192                 :           1310 : markrunend(LogicalTape *tape)
                               3193                 :                : {
 9726 bruce@momjian.us         3194                 :           1310 :     unsigned int len = 0;
                               3195                 :                : 
 1429 peter@eisentraut.org     3196                 :           1310 :     LogicalTapeWrite(tape, &len, sizeof(len));
 9904 tgl@sss.pgh.pa.us        3197                 :           1310 : }
                               3198                 :                : 
                               3199                 :                : /*
                               3200                 :                :  * Get memory for tuple from within READTUP() routine.
                               3201                 :                :  *
                               3202                 :                :  * We use next free slot from the slab allocator, or palloc() if the tuple
                               3203                 :                :  * is too large for that.
                               3204                 :                :  */
                               3205                 :                : void *
 1585 akorotkov@postgresql     3206                 :        3669209 : tuplesort_readtup_alloc(Tuplesortstate *state, Size tuplen)
                               3207                 :                : {
                               3208                 :                :     SlabSlot   *buf;
                               3209                 :                : 
                               3210                 :                :     /*
                               3211                 :                :      * We pre-allocate enough slots in the slab arena that we should never run
                               3212                 :                :      * out.
                               3213                 :                :      */
 3708 heikki.linnakangas@i     3214         [ -  + ]:        3669209 :     Assert(state->slabFreeHead);
                               3215                 :                : 
                               3216   [ +  +  -  + ]:        3669209 :     if (tuplen > SLAB_SLOT_SIZE || !state->slabFreeHead)
 1585 akorotkov@postgresql     3217                 :              5 :         return MemoryContextAlloc(state->base.sortcontext, tuplen);
                               3218                 :                :     else
                               3219                 :                :     {
 3708 heikki.linnakangas@i     3220                 :        3669204 :         buf = state->slabFreeHead;
                               3221                 :                :         /* Reuse this slot */
                               3222                 :        3669204 :         state->slabFreeHead = buf->nextfree;
                               3223                 :                : 
                               3224                 :        3669204 :         return buf;
                               3225                 :                :     }
                               3226                 :                : }
                               3227                 :                : 
                               3228                 :                : 
                               3229                 :                : /*
                               3230                 :                :  * Parallel sort routines
                               3231                 :                :  */
                               3232                 :                : 
                               3233                 :                : /*
                               3234                 :                :  * tuplesort_estimate_shared - estimate required shared memory allocation
                               3235                 :                :  *
                               3236                 :                :  * nWorkers is an estimate of the number of workers (it's the number that
                               3237                 :                :  * will be requested).
                               3238                 :                :  */
                               3239                 :                : Size
 3221 rhaas@postgresql.org     3240                 :            134 : tuplesort_estimate_shared(int nWorkers)
                               3241                 :                : {
                               3242                 :                :     Size        tapesSize;
                               3243                 :                : 
                               3244         [ -  + ]:            134 :     Assert(nWorkers > 0);
                               3245                 :                : 
                               3246                 :                :     /* Make sure that BufFile shared state is MAXALIGN'd */
                               3247                 :            134 :     tapesSize = mul_size(sizeof(TapeShare), nWorkers);
                               3248                 :            134 :     tapesSize = MAXALIGN(add_size(tapesSize, offsetof(Sharedsort, tapes)));
                               3249                 :                : 
                               3250                 :            134 :     return tapesSize;
                               3251                 :                : }
                               3252                 :                : 
                               3253                 :                : /*
                               3254                 :                :  * tuplesort_initialize_shared - initialize shared tuplesort state
                               3255                 :                :  *
                               3256                 :                :  * Must be called from leader process before workers are launched, to
                               3257                 :                :  * establish state needed up-front for worker tuplesortstates.  nWorkers
                               3258                 :                :  * should match the argument passed to tuplesort_estimate_shared().
                               3259                 :                :  */
                               3260                 :                : void
                               3261                 :            182 : tuplesort_initialize_shared(Sharedsort *shared, int nWorkers, dsm_segment *seg)
                               3262                 :                : {
                               3263                 :                :     int         i;
                               3264                 :                : 
                               3265         [ -  + ]:            182 :     Assert(nWorkers > 0);
                               3266                 :                : 
   67 nathan@postgresql.or     3267                 :GNC         182 :     pg_atomic_init_u32(&shared->currentWorker, 0);
                               3268                 :            182 :     pg_atomic_init_u32(&shared->workersFinished, 0);
 3221 rhaas@postgresql.org     3269                 :CBC         182 :     SharedFileSetInit(&shared->fileset, seg);
                               3270                 :            182 :     shared->nTapes = nWorkers;
                               3271         [ +  + ]:            571 :     for (i = 0; i < nWorkers; i++)
                               3272                 :                :     {
                               3273                 :            389 :         shared->tapes[i].firstblocknumber = 0L;
                               3274                 :                :     }
                               3275                 :            182 : }
                               3276                 :                : 
                               3277                 :                : /*
                               3278                 :                :  * tuplesort_attach_shared - attach to shared tuplesort state
                               3279                 :                :  *
                               3280                 :                :  * Must be called by all worker processes.
                               3281                 :                :  */
                               3282                 :                : void
                               3283                 :            204 : tuplesort_attach_shared(Sharedsort *shared, dsm_segment *seg)
                               3284                 :                : {
                               3285                 :                :     /* Attach to SharedFileSet */
                               3286                 :            204 :     SharedFileSetAttach(&shared->fileset, seg);
                               3287                 :            204 : }
                               3288                 :                : 
                               3289                 :                : /*
                               3290                 :                :  * worker_get_identifier - Assign and return ordinal identifier for worker
                               3291                 :                :  *
                               3292                 :                :  * The order in which these are assigned is not well defined, and should not
                               3293                 :                :  * matter; worker numbers across parallel sort participants need only be
                               3294                 :                :  * distinct and gapless.  logtape.c requires this.
                               3295                 :                :  *
                               3296                 :                :  * Note that the identifiers assigned from here have no relation to
                               3297                 :                :  * ParallelWorkerNumber number, to avoid making any assumption about
                               3298                 :                :  * caller's requirements.  However, we do follow the ParallelWorkerNumber
                               3299                 :                :  * convention of representing a non-worker with worker number -1.  This
                               3300                 :                :  * includes the leader, as well as serial Tuplesort processes.
                               3301                 :                :  */
                               3302                 :                : static int
                               3303                 :            385 : worker_get_identifier(Tuplesortstate *state)
                               3304                 :                : {
                               3305   [ +  -  -  + ]:            385 :     Assert(WORKER(state));
                               3306                 :                : 
   67 nathan@postgresql.or     3307                 :GNC         385 :     return pg_atomic_fetch_add_u32(&state->shared->currentWorker, 1);
                               3308                 :                : }
                               3309                 :                : 
                               3310                 :                : /*
                               3311                 :                :  * worker_freeze_result_tape - freeze worker's result tape for leader
                               3312                 :                :  *
                               3313                 :                :  * This is called by workers just after the result tape has been determined,
                               3314                 :                :  * instead of calling LogicalTapeFreeze() directly.  They do so because
                               3315                 :                :  * workers require a few additional steps over similar serial
                               3316                 :                :  * TSS_SORTEDONTAPE external sort cases, which also happen here.  The extra
                               3317                 :                :  * steps are around freeing now unneeded resources, and representing to
                               3318                 :                :  * leader that worker's input run is available for its merge.
                               3319                 :                :  *
                               3320                 :                :  * There should only be one final output run for each worker, which consists
                               3321                 :                :  * of all tuples that were originally input into worker.
                               3322                 :                :  */
                               3323                 :                : static void
 3221 rhaas@postgresql.org     3324                 :CBC         385 : worker_freeze_result_tape(Tuplesortstate *state)
                               3325                 :                : {
                               3326                 :            385 :     Sharedsort *shared = state->shared;
                               3327                 :                :     TapeShare   output;
                               3328                 :                : 
                               3329   [ +  -  -  + ]:            385 :     Assert(WORKER(state));
 1867 heikki.linnakangas@i     3330         [ -  + ]:            385 :     Assert(state->result_tape != NULL);
 3221 rhaas@postgresql.org     3331         [ -  + ]:            385 :     Assert(state->memtupcount == 0);
                               3332                 :                : 
                               3333                 :                :     /*
                               3334                 :                :      * Free most remaining memory, in case caller is sensitive to our holding
                               3335                 :                :      * on to it.  memtuples may not be a tiny merge heap at this point.
                               3336                 :                :      */
                               3337                 :            385 :     pfree(state->memtuples);
                               3338                 :                :     /* Be tidy */
                               3339                 :            385 :     state->memtuples = NULL;
                               3340                 :            385 :     state->memtupsize = 0;
                               3341                 :                : 
                               3342                 :                :     /*
                               3343                 :                :      * Parallel worker requires result tape metadata, which is to be stored in
                               3344                 :                :      * shared memory for leader
                               3345                 :                :      */
 1867 heikki.linnakangas@i     3346                 :            385 :     LogicalTapeFreeze(state->result_tape, &output);
                               3347                 :                : 
                               3348                 :                :     /* Store properties of output tape, and update finished worker count */
 3221 rhaas@postgresql.org     3349                 :            385 :     shared->tapes[state->worker] = output;
   67 nathan@postgresql.or     3350                 :GNC         385 :     pg_atomic_fetch_add_u32(&shared->workersFinished, 1);
 3221 rhaas@postgresql.org     3351                 :CBC         385 : }
                               3352                 :                : 
                               3353                 :                : /*
                               3354                 :                :  * worker_nomergeruns - dump memtuples in worker, without merging
                               3355                 :                :  *
                               3356                 :                :  * This called as an alternative to mergeruns() with a worker when no
                               3357                 :                :  * merging is required.
                               3358                 :                :  */
                               3359                 :                : static void
                               3360                 :            385 : worker_nomergeruns(Tuplesortstate *state)
                               3361                 :                : {
                               3362   [ +  -  -  + ]:            385 :     Assert(WORKER(state));
 1867 heikki.linnakangas@i     3363         [ -  + ]:            385 :     Assert(state->result_tape == NULL);
                               3364         [ -  + ]:            385 :     Assert(state->nOutputRuns == 1);
                               3365                 :                : 
                               3366                 :            385 :     state->result_tape = state->destTape;
 3221 rhaas@postgresql.org     3367                 :            385 :     worker_freeze_result_tape(state);
                               3368                 :            385 : }
                               3369                 :                : 
                               3370                 :                : /*
                               3371                 :                :  * leader_takeover_tapes - create tapeset for leader from worker tapes
                               3372                 :                :  *
                               3373                 :                :  * So far, leader Tuplesortstate has performed no actual sorting.  By now, all
                               3374                 :                :  * sorting has occurred in workers, all of which must have already returned
                               3375                 :                :  * from tuplesort_performsort().
                               3376                 :                :  *
                               3377                 :                :  * When this returns, leader process is left in a state that is virtually
                               3378                 :                :  * indistinguishable from it having generated runs as a serial external sort
                               3379                 :                :  * might have.
                               3380                 :                :  */
                               3381                 :                : static void
                               3382                 :            133 : leader_takeover_tapes(Tuplesortstate *state)
                               3383                 :                : {
                               3384                 :            133 :     Sharedsort *shared = state->shared;
                               3385                 :            133 :     int         nParticipants = state->nParticipants;
                               3386                 :                :     int         workersFinished;
                               3387                 :                :     int         j;
                               3388                 :                : 
                               3389   [ +  -  -  + ]:            133 :     Assert(LEADER(state));
                               3390         [ -  + ]:            133 :     Assert(nParticipants >= 1);
                               3391                 :                : 
   67 nathan@postgresql.or     3392                 :GNC         133 :     workersFinished = pg_atomic_read_membarrier_u32(&shared->workersFinished);
                               3393                 :                : 
 3221 rhaas@postgresql.org     3394         [ -  + ]:CBC         133 :     if (nParticipants != workersFinished)
 3221 rhaas@postgresql.org     3395         [ #  # ]:UBC           0 :         elog(ERROR, "cannot take over tapes before all workers finish");
                               3396                 :                : 
                               3397                 :                :     /*
                               3398                 :                :      * Create the tapeset from worker tapes, including a leader-owned tape at
                               3399                 :                :      * the end.  Parallel workers are far more expensive than logical tapes,
                               3400                 :                :      * so the number of tapes allocated here should never be excessive.
                               3401                 :                :      */
 1867 heikki.linnakangas@i     3402                 :CBC         133 :     inittapestate(state, nParticipants);
                               3403                 :            133 :     state->tapeset = LogicalTapeSetCreate(false, &shared->fileset, -1);
                               3404                 :                : 
                               3405                 :                :     /*
                               3406                 :                :      * Set currentRun to reflect the number of runs we will merge (it's not
                               3407                 :                :      * used for anything, this is just pro forma)
                               3408                 :                :      */
 3221 rhaas@postgresql.org     3409                 :            133 :     state->currentRun = nParticipants;
                               3410                 :                : 
                               3411                 :                :     /*
                               3412                 :                :      * Initialize the state to look the same as after building the initial
                               3413                 :                :      * runs.
                               3414                 :                :      *
                               3415                 :                :      * There will always be exactly 1 run per worker, and exactly one input
                               3416                 :                :      * tape per run, because workers always output exactly 1 run, even when
                               3417                 :                :      * there were no input tuples for workers to sort.
                               3418                 :                :      */
 1867 heikki.linnakangas@i     3419                 :            133 :     state->inputTapes = NULL;
                               3420                 :            133 :     state->nInputTapes = 0;
                               3421                 :            133 :     state->nInputRuns = 0;
                               3422                 :                : 
  103 michael@paquier.xyz      3423                 :GNC         133 :     state->outputTapes = palloc0_array(LogicalTape *, nParticipants);
 1867 heikki.linnakangas@i     3424                 :CBC         133 :     state->nOutputTapes = nParticipants;
                               3425                 :            133 :     state->nOutputRuns = nParticipants;
                               3426                 :                : 
                               3427         [ +  + ]:            422 :     for (j = 0; j < nParticipants; j++)
                               3428                 :                :     {
                               3429                 :            289 :         state->outputTapes[j] = LogicalTapeImport(state->tapeset, j, &shared->tapes[j]);
                               3430                 :                :     }
                               3431                 :                : 
 3221 rhaas@postgresql.org     3432                 :            133 :     state->status = TSS_BUILDRUNS;
                               3433                 :            133 : }
                               3434                 :                : 
                               3435                 :                : /*
                               3436                 :                :  * Convenience routine to free a tuple previously loaded into sort memory
                               3437                 :                :  */
                               3438                 :                : static void
 7148 tgl@sss.pgh.pa.us        3439                 :        2146809 : free_sort_tuple(Tuplesortstate *state, SortTuple *stup)
                               3440                 :                : {
 1964 drowley@postgresql.o     3441         [ +  + ]:        2146809 :     if (stup->tuple)
                               3442                 :                :     {
                               3443                 :        2047563 :         FREEMEM(state, GetMemoryChunkSpace(stup->tuple));
                               3444                 :        2047563 :         pfree(stup->tuple);
                               3445                 :        2047563 :         stup->tuple = NULL;
                               3446                 :                :     }
 7148 tgl@sss.pgh.pa.us        3447                 :        2146809 : }
                               3448                 :                : 
                               3449                 :                : int
  110 john.naylor@postgres     3450                 :GNC     4775931 : ssup_datum_uint64_cmp(Datum x, Datum y, SortSupport ssup)
                               3451                 :                : {
 1701 john.naylor@postgres     3452         [ +  + ]:CBC     4775931 :     if (x < y)
                               3453                 :        2034237 :         return -1;
                               3454         [ +  + ]:        2741694 :     else if (x > y)
                               3455                 :         682271 :         return 1;
                               3456                 :                :     else
                               3457                 :        2059423 :         return 0;
                               3458                 :                : }
                               3459                 :                : 
                               3460                 :                : int
  110 john.naylor@postgres     3461                 :GNC     3344197 : ssup_datum_int64_cmp(Datum x, Datum y, SortSupport ssup)
                               3462                 :                : {
 1662 drowley@postgresql.o     3463                 :CBC     3344197 :     int64       xx = DatumGetInt64(x);
                               3464                 :        3344197 :     int64       yy = DatumGetInt64(y);
                               3465                 :                : 
 1701 john.naylor@postgres     3466         [ +  + ]:        3344197 :     if (xx < yy)
                               3467                 :        2799151 :         return -1;
                               3468         [ +  + ]:         545046 :     else if (xx > yy)
                               3469                 :         246643 :         return 1;
                               3470                 :                :     else
                               3471                 :         298403 :         return 0;
                               3472                 :                : }
                               3473                 :                : 
                               3474                 :                : int
  110 john.naylor@postgres     3475                 :GNC   148881954 : ssup_datum_uint32_cmp(Datum x, Datum y, SortSupport ssup)
                               3476                 :                : {
                               3477                 :      148881954 :     uint32      xx = DatumGetUInt32(x);
                               3478                 :      148881954 :     uint32      yy = DatumGetUInt32(y);
                               3479                 :                : 
                               3480         [ +  + ]:      148881954 :     if (xx < yy)
                               3481                 :       36242710 :         return -1;
                               3482         [ +  + ]:      112639244 :     else if (xx > yy)
                               3483                 :       33811846 :         return 1;
                               3484                 :                :     else
                               3485                 :       78827398 :         return 0;
                               3486                 :                : }
                               3487                 :                : 
                               3488                 :                : int
 1701 john.naylor@postgres     3489                 :CBC   192863355 : ssup_datum_int32_cmp(Datum x, Datum y, SortSupport ssup)
                               3490                 :                : {
 1662 drowley@postgresql.o     3491                 :      192863355 :     int32       xx = DatumGetInt32(x);
                               3492                 :      192863355 :     int32       yy = DatumGetInt32(y);
                               3493                 :                : 
 1701 john.naylor@postgres     3494         [ +  + ]:      192863355 :     if (xx < yy)
                               3495                 :       41298905 :         return -1;
                               3496         [ +  + ]:      151564450 :     else if (xx > yy)
                               3497                 :       34784225 :         return 1;
                               3498                 :                :     else
                               3499                 :      116780225 :         return 0;
                               3500                 :                : }
        

Generated by: LCOV version 2.0-1