Branch data 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 *
545 : 175535 : 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 [ + + - + ]: 175535 : if (coordinate && (sortopt & TUPLESORT_RANDOMACCESS))
554 [ # # ]: 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 : : */
560 : 175535 : 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 : 175535 : 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 : 175535 : oldcontext = MemoryContextSwitchTo(maincontext);
582 : :
583 : 175535 : state = palloc0_object(Tuplesortstate);
584 : :
585 [ - + ]: 175535 : if (trace_sort)
586 : 0 : pg_rusage_init(&state->ru_start);
587 : :
588 : 175535 : state->base.sortopt = sortopt;
589 : 175535 : state->base.tuples = true;
590 : 175535 : 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 : : */
598 : 175535 : state->allowedMem = Max(workMem, 64) * (int64) 1024;
599 : 175535 : state->base.sortcontext = sortcontext;
600 : 175535 : state->base.maincontext = maincontext;
601 : :
602 : 175535 : state->memtupsize = INITIAL_MEMTUPSIZE;
603 : 175535 : 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 : 175535 : tuplesort_begin_batch(state);
610 : :
611 : : /*
612 : : * Initialize parallel-related state based on coordination information
613 : : * from caller
614 : : */
615 [ + + ]: 175535 : if (!coordinate)
616 : : {
617 : : /* Serial sort */
618 : 174969 : state->shared = NULL;
619 : 174969 : state->worker = -1;
620 : 174969 : 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 : : Assert(state->nParticipants >= 1);
636 : : }
637 : :
638 : 175535 : MemoryContextSwitchTo(oldcontext);
639 : :
640 : 175535 : 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
651 : 177734 : tuplesort_begin_batch(Tuplesortstate *state)
652 : : {
653 : : MemoryContext oldcontext;
654 : :
655 : 177734 : 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 : : */
670 [ + + ]: 177734 : if (TupleSortUseBumpTupleCxt(state->base.sortopt))
671 : 176814 : state->base.tuplecontext = BumpContextCreate(state->base.sortcontext,
672 : : "Caller tuples",
673 : : ALLOCSET_DEFAULT_SIZES);
674 : : else
675 : 920 : state->base.tuplecontext = AllocSetContextCreate(state->base.sortcontext,
676 : : "Caller tuples",
677 : : ALLOCSET_DEFAULT_SIZES);
678 : :
679 : :
680 : 177734 : state->status = TSS_INITIAL;
681 : 177734 : state->bounded = false;
682 : 177734 : state->boundUsed = false;
683 : :
684 : 177734 : state->availMem = state->allowedMem;
685 : :
686 : 177734 : state->tapeset = NULL;
687 : :
688 : 177734 : state->memtupcount = 0;
689 : :
690 : 177734 : state->growmemtuples = true;
691 : 177734 : state->slabAllocatorUsed = false;
692 [ + + + + ]: 177734 : if (state->memtuples != NULL && state->memtupsize != INITIAL_MEMTUPSIZE)
693 : : {
694 : 98 : pfree(state->memtuples);
695 : 98 : state->memtuples = NULL;
696 : 98 : state->memtupsize = INITIAL_MEMTUPSIZE;
697 : : }
698 [ + + ]: 177734 : if (state->memtuples == NULL)
699 : : {
700 : 175633 : state->memtuples = palloc_array(SortTuple, state->memtupsize);
701 : 175633 : USEMEM(state, GetMemoryChunkSpace(state->memtuples));
702 : : }
703 : :
704 : : /* workMem must be large enough for the minimal memtuples array */
705 [ - + - - ]: 177734 : if (LACKMEM(state))
706 [ # # ]: 0 : elog(ERROR, "insufficient memory allowed for sort");
707 : :
708 : 177734 : state->currentRun = 0;
709 : :
710 : : /*
711 : : * Tape variables (inputTapes, outputTapes, etc.) will be initialized by
712 : : * inittapes(), if needed.
713 : : */
714 : :
715 : 177734 : state->result_tape = NULL; /* flag that result tape has not been formed */
716 : :
717 : 177734 : MemoryContextSwitchTo(oldcontext);
718 : 177734 : }
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
733 : 823 : tuplesort_set_bound(Tuplesortstate *state, int64 bound)
734 : : {
735 : : /* Assert we're called before loading any tuples */
736 : : Assert(state->status == TSS_INITIAL && state->memtupcount == 0);
737 : : /* Assert we allow bounded sorts */
738 : : Assert(state->base.sortopt & TUPLESORT_ALLOWBOUNDED);
739 : : /* Can't set the bound twice, either */
740 : : Assert(!state->bounded);
741 : : /* Also, this shouldn't be called in a parallel worker */
742 : : Assert(!WORKER(state));
743 : :
744 : : /* Parallel leader allows but ignores hint */
745 [ - + - - ]: 823 : if (LEADER(state))
746 : 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 */
755 [ - + ]: 823 : if (bound > (int64) (INT_MAX / 2))
756 : 0 : return;
757 : :
758 : 823 : state->bounded = true;
759 : 823 : 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 : : */
766 : 823 : state->base.sortKeys->abbrev_converter = NULL;
767 [ + + ]: 823 : 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 : 823 : state->base.sortKeys->abbrev_abort = NULL;
772 : 823 : 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
781 : 329 : tuplesort_used_bound(Tuplesortstate *state)
782 : : {
783 : 329 : return state->boundUsed;
784 : : }
785 : :
786 : : /*
787 : : * tuplesort_free
788 : : *
789 : : * Internal routine for freeing resources of tuplesort.
790 : : */
791 : : static void
792 : 177530 : tuplesort_free(Tuplesortstate *state)
793 : : {
794 : : /* context swap probably not needed, but let's be safe */
795 : 177530 : MemoryContext oldcontext = MemoryContextSwitchTo(state->base.sortcontext);
796 : : int64 spaceUsed;
797 : :
798 [ + + ]: 177530 : if (state->tapeset)
799 : 608 : spaceUsed = LogicalTapeSetBlocks(state->tapeset);
800 : : else
801 : 176922 : 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 : : */
810 [ + + ]: 177530 : if (state->tapeset)
811 : 608 : LogicalTapeSetClose(state->tapeset);
812 : :
813 [ - + ]: 177530 : if (trace_sort)
814 : : {
815 [ # # ]: 0 : if (state->tapeset)
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 : :
827 [ + + ]: 177530 : FREESTATE(state);
828 : 177530 : MemoryContextSwitchTo(oldcontext);
829 : :
830 : : /*
831 : : * Free the per-sort memory context, thereby releasing all working memory.
832 : : */
833 : 177530 : MemoryContextReset(state->base.sortcontext);
834 : 177530 : }
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 : 175331 : tuplesort_end(Tuplesortstate *state)
847 : : {
848 : 175331 : tuplesort_free(state);
849 : :
850 : : /*
851 : : * Free the main memory context, including the Tuplesortstate struct
852 : : * itself.
853 : : */
854 : 175331 : MemoryContextDelete(state->base.maincontext);
855 : 175331 : }
856 : :
857 : : /*
858 : : * tuplesort_updatemax
859 : : *
860 : : * Update maximum resource usage statistics.
861 : : */
862 : : static void
863 : 2463 : 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 [ + + ]: 2463 : if (state->tapeset)
878 : : {
879 : 4 : isSpaceDisk = true;
880 : 4 : spaceUsed = LogicalTapeSetBlocks(state->tapeset) * BLCKSZ;
881 : : }
882 : : else
883 : : {
884 : 2459 : isSpaceDisk = false;
885 : 2459 : 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 [ + + - + ]: 2463 : if ((isSpaceDisk && !state->isMaxSpaceDisk) ||
897 [ + - + + ]: 2459 : (isSpaceDisk == state->isMaxSpaceDisk && spaceUsed > state->maxSpace))
898 : : {
899 : 368 : state->maxSpace = spaceUsed;
900 : 368 : state->isMaxSpaceDisk = isSpaceDisk;
901 : 368 : state->maxSpaceStatus = state->status;
902 : : }
903 : 2463 : }
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
917 : 2199 : tuplesort_reset(Tuplesortstate *state, bool allowbounded)
918 : : {
919 : 2199 : tuplesort_updatemax(state);
920 : 2199 : 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 : : */
926 [ + + ]: 2199 : if (allowbounded)
927 : 140 : state->base.sortopt |= TUPLESORT_ALLOWBOUNDED;
928 : : else
929 : 2059 : 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 : : */
935 : 2199 : tuplesort_begin_batch(state);
936 : :
937 : 2199 : state->lastReturnedTuple = NULL;
938 : 2199 : state->slabMemoryBegin = NULL;
939 : 2199 : state->slabMemoryEnd = NULL;
940 : 2199 : state->slabFreeHead = NULL;
941 : 2199 : }
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 : 5423 : grow_memtuples(Tuplesortstate *state)
960 : : {
961 : : int newmemtupsize;
962 : 5423 : int memtupsize = state->memtupsize;
963 : 5423 : int64 memNowUsed = state->allowedMem - state->availMem;
964 : :
965 : : /* Forget it if we've already maxed out memtuples, per comment above */
966 [ + + ]: 5423 : if (!state->growmemtuples)
967 : 90 : return false;
968 : :
969 : : /* Select new value of memtupsize */
970 [ + + ]: 5333 : 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 : : */
976 [ + - ]: 5239 : if (memtupsize < INT_MAX / 2)
977 : 5239 : newmemtupsize = memtupsize * 2;
978 : : else
979 : : {
980 : 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 : :
1014 : 94 : grow_ratio = (double) state->allowedMem / (double) memNowUsed;
1015 [ + - ]: 94 : if (memtupsize * grow_ratio < INT_MAX)
1016 : 94 : newmemtupsize = (int) (memtupsize * grow_ratio);
1017 : : else
1018 : 0 : newmemtupsize = INT_MAX;
1019 : :
1020 : : /* We won't make any further enlargement attempts */
1021 : 94 : state->growmemtuples = false;
1022 : : }
1023 : :
1024 : : /* Must enlarge array by at least one element, else report failure */
1025 [ - + ]: 5333 : if (newmemtupsize <= memtupsize)
1026 : 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 : : */
1035 [ - + ]: 5333 : if ((Size) newmemtupsize >= MaxAllocHugeSize / sizeof(SortTuple))
1036 : : {
1037 : 0 : newmemtupsize = (int) (MaxAllocHugeSize / sizeof(SortTuple));
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 : : */
1052 [ - + ]: 5333 : if (state->availMem < (int64) ((newmemtupsize - memtupsize) * sizeof(SortTuple)))
1053 : 0 : goto noalloc;
1054 : :
1055 : : /* OK, do it */
1056 : 5333 : FREEMEM(state, GetMemoryChunkSpace(state->memtuples));
1057 : 5333 : state->memtupsize = newmemtupsize;
1058 : 5333 : state->memtuples = (SortTuple *)
1059 : 5333 : repalloc_huge(state->memtuples,
1060 : 5333 : state->memtupsize * sizeof(SortTuple));
1061 : 5333 : USEMEM(state, GetMemoryChunkSpace(state->memtuples));
1062 [ - + - - ]: 5333 : if (LACKMEM(state))
1063 [ # # ]: 0 : elog(ERROR, "unexpected out-of-memory situation in tuplesort");
1064 : 5333 : return true;
1065 : :
1066 : 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
1076 : 19603643 : tuplesort_puttuple_common(Tuplesortstate *state, SortTuple *tuple,
1077 : : bool useAbbrev, Size tuplen)
1078 : : {
1079 : 19603643 : MemoryContext oldcontext = MemoryContextSwitchTo(state->base.sortcontext);
1080 : :
1081 : : Assert(!LEADER(state));
1082 : :
1083 : : /* account for the memory used for this tuple */
1084 : 19603643 : USEMEM(state, tuplen);
1085 : 19603643 : state->tupleMem += tuplen;
1086 : :
1087 [ + + ]: 19603643 : 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 [ + + ]: 2901621 : else if (!consider_abort_common(state))
1099 : : {
1100 : : /* Store abbreviated key representation */
1101 : 2901557 : 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 : :
1118 [ + + + - ]: 19603643 : switch (state->status)
1119 : : {
1120 : 16684493 : 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 : : */
1129 [ + + ]: 16684493 : if (state->memtupcount >= state->memtupsize - 1)
1130 : : {
1131 : 5423 : (void) grow_memtuples(state);
1132 : : Assert(state->memtupcount < state->memtupsize);
1133 : : }
1134 : 16684493 : 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 : : */
1148 [ + + ]: 16684493 : if (state->bounded &&
1149 [ + + ]: 37682 : (state->memtupcount > state->bound * 2 ||
1150 [ + + - + : 37413 : (state->memtupcount > state->bound && LACKMEM(state))))
- - ]
1151 : : {
1152 [ - + ]: 269 : if (trace_sort)
1153 [ # # ]: 0 : elog(LOG, "switching to bounded heapsort at %d tuples: %s",
1154 : : state->memtupcount,
1155 : : pg_rusage_show(&state->ru_start));
1156 : 269 : make_bounded_heap(state);
1157 : 269 : MemoryContextSwitchTo(oldcontext);
1158 : 269 : return;
1159 : : }
1160 : :
1161 : : /*
1162 : : * Done if we still fit in available memory and have array slots.
1163 : : */
1164 [ + + - + : 16684224 : if (state->memtupcount < state->memtupsize && !LACKMEM(state))
- - ]
1165 : : {
1166 : 16684134 : MemoryContextSwitchTo(oldcontext);
1167 : 16684134 : return;
1168 : : }
1169 : :
1170 : : /*
1171 : : * Nope; time to switch to tape-based operation.
1172 : : */
1173 : 90 : inittapes(state, true);
1174 : :
1175 : : /*
1176 : : * Dump all tuples.
1177 : : */
1178 : 90 : dumptuples(state, false);
1179 : 90 : break;
1180 : :
1181 : 2148217 : 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 [ + + ]: 2148217 : if (COMPARETUP(state, tuple, &state->memtuples[0]) <= 0)
1192 : : {
1193 : : /* new tuple <= top of the heap, so we can discard it */
1194 : 1813052 : free_sort_tuple(state, tuple);
1195 [ - + ]: 1813052 : CHECK_FOR_INTERRUPTS();
1196 : : }
1197 : : else
1198 : : {
1199 : : /* discard top of heap, replacing it with the new tuple */
1200 : 335165 : free_sort_tuple(state, &state->memtuples[0]);
1201 : 335165 : tuplesort_heap_replace_top(state, tuple);
1202 : : }
1203 : 2148217 : break;
1204 : :
1205 : 770933 : case TSS_BUILDRUNS:
1206 : :
1207 : : /*
1208 : : * Save the tuple into the unsorted array (there must be space)
1209 : : */
1210 : 770933 : state->memtuples[state->memtupcount++] = *tuple;
1211 : :
1212 : : /*
1213 : : * If we are over the memory limit, dump all tuples.
1214 : : */
1215 : 770933 : dumptuples(state, false);
1216 : 770933 : break;
1217 : :
1218 : 0 : default:
1219 [ # # ]: 0 : elog(ERROR, "invalid tuplesort state");
1220 : : break;
1221 : : }
1222 : 2919240 : MemoryContextSwitchTo(oldcontext);
1223 : : }
1224 : :
1225 : : static bool
1226 : 2901621 : consider_abort_common(Tuplesortstate *state)
1227 : : {
1228 : : Assert(state->base.sortKeys[0].abbrev_converter != NULL);
1229 : : Assert(state->base.sortKeys[0].abbrev_abort != NULL);
1230 : : 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 : : */
1236 [ + + ]: 2901621 : if (state->status == TSS_INITIAL &&
1237 [ + + ]: 2575016 : 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 : : */
1245 [ + + ]: 3249 : if (!state->base.sortKeys->abbrev_abort(state->memtupcount,
1246 : : state->base.sortKeys))
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 : : */
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 */
1260 : 64 : return true;
1261 : : }
1262 : :
1263 : 2898372 : return false;
1264 : : }
1265 : :
1266 : : /*
1267 : : * All tuples have been provided; finish the sort.
1268 : : */
1269 : : void
1270 : 150765 : tuplesort_performsort(Tuplesortstate *state)
1271 : : {
1272 : 150765 : MemoryContext oldcontext = MemoryContextSwitchTo(state->base.sortcontext);
1273 : :
1274 [ - + ]: 150765 : if (trace_sort)
1275 [ # # ]: 0 : elog(LOG, "performsort of worker %d starting: %s",
1276 : : state->worker, pg_rusage_show(&state->ru_start));
1277 : :
1278 [ + + + - ]: 150765 : switch (state->status)
1279 : : {
1280 : 150406 : 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 : : */
1286 [ + + ]: 150406 : if (SERIAL(state))
1287 : : {
1288 : : /* Sort in memory and we're done */
1289 : 149888 : tuplesort_sort_memtuples(state);
1290 : 149827 : 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 : : }
1312 : 150345 : state->current = 0;
1313 : 150345 : state->eof_reached = false;
1314 : 150345 : state->markpos_block = 0L;
1315 : 150345 : state->markpos_offset = 0;
1316 : 150345 : state->markpos_eof = false;
1317 : 150345 : break;
1318 : :
1319 : 269 : 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 : : */
1327 : 269 : sort_bounded_heap(state);
1328 : 269 : state->current = 0;
1329 : 269 : state->eof_reached = false;
1330 : 269 : state->markpos_offset = 0;
1331 : 269 : state->markpos_eof = false;
1332 : 269 : break;
1333 : :
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 : :
1350 : 0 : default:
1351 [ # # ]: 0 : elog(ERROR, "invalid tuplesort state");
1352 : : break;
1353 : : }
1354 : :
1355 [ - + ]: 150704 : if (trace_sort)
1356 : : {
1357 [ # # ]: 0 : if (state->status == TSS_FINALMERGE)
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 : :
1366 : 150704 : MemoryContextSwitchTo(oldcontext);
1367 : 150704 : }
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
1377 : 18184031 : tuplesort_gettuple_common(Tuplesortstate *state, bool forward,
1378 : : SortTuple *stup)
1379 : : {
1380 : : unsigned int tuplen;
1381 : : size_t nmoved;
1382 : :
1383 : : Assert(!WORKER(state));
1384 : :
1385 [ + + + - ]: 18184031 : switch (state->status)
1386 : : {
1387 : 15243104 : case TSS_SORTEDINMEM:
1388 : : Assert(forward || state->base.sortopt & TUPLESORT_RANDOMACCESS);
1389 : : Assert(!state->slabAllocatorUsed);
1390 [ + + ]: 15243104 : if (forward)
1391 : : {
1392 [ + + ]: 15243060 : if (state->current < state->memtupcount)
1393 : : {
1394 : 15093917 : *stup = state->memtuples[state->current++];
1395 : 15093917 : return true;
1396 : : }
1397 : 149143 : 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 : : */
1404 [ + + - + ]: 149143 : if (state->bounded && state->current >= state->bound)
1405 [ # # ]: 0 : elog(ERROR, "retrieved too many tuples in a bounded sort");
1406 : :
1407 : 149143 : return false;
1408 : : }
1409 : : else
1410 : : {
1411 [ - + ]: 44 : if (state->current <= 0)
1412 : 0 : return false;
1413 : :
1414 : : /*
1415 : : * if all tuples are fetched already then we return last
1416 : : * tuple, else - tuple before last returned.
1417 : : */
1418 [ + + ]: 44 : if (state->eof_reached)
1419 : 8 : state->eof_reached = false;
1420 : : else
1421 : : {
1422 : 36 : state->current--; /* last returned tuple */
1423 [ + + ]: 36 : if (state->current <= 0)
1424 : 4 : return false;
1425 : : }
1426 : 40 : *stup = state->memtuples[state->current - 1];
1427 : 40 : return true;
1428 : : }
1429 : : break;
1430 : :
1431 : 196999 : case TSS_SORTEDONTAPE:
1432 : : Assert(forward || state->base.sortopt & TUPLESORT_RANDOMACCESS);
1433 : : 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 : :
1445 [ + + ]: 196999 : if (forward)
1446 : : {
1447 [ - + ]: 196979 : if (state->eof_reached)
1448 : 0 : return false;
1449 : :
1450 [ + + ]: 196979 : if ((tuplen = getlen(state->result_tape, true)) != 0)
1451 : : {
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 : : */
1459 : 196960 : state->lastReturnedTuple = stup->tuple;
1460 : :
1461 : 196960 : return true;
1462 : : }
1463 : : else
1464 : : {
1465 : 19 : state->eof_reached = true;
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 : : */
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 : : */
1483 : 8 : nmoved = LogicalTapeBackspace(state->result_tape,
1484 : : 2 * sizeof(unsigned int));
1485 [ - + ]: 8 : if (nmoved == 0)
1486 : 0 : return false;
1487 [ - + ]: 8 : else if (nmoved != 2 * sizeof(unsigned int))
1488 [ # # ]: 0 : elog(ERROR, "unexpected tape position");
1489 : 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 : : */
1497 : 12 : nmoved = LogicalTapeBackspace(state->result_tape,
1498 : : sizeof(unsigned int));
1499 [ - + ]: 12 : if (nmoved == 0)
1500 : 0 : return false;
1501 [ - + ]: 12 : else if (nmoved != sizeof(unsigned int))
1502 [ # # ]: 0 : elog(ERROR, "unexpected tape position");
1503 : 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));
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 : : */
1519 : 4 : return false;
1520 : : }
1521 [ - + ]: 8 : else if (nmoved != tuplen + 2 * sizeof(unsigned int))
1522 [ # # ]: 0 : elog(ERROR, "bogus tuple length in backward scan");
1523 : : }
1524 : :
1525 : 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);
1534 [ - + ]: 16 : if (nmoved != tuplen)
1535 [ # # ]: 0 : elog(ERROR, "bogus tuple length in backward scan");
1536 : 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 : : */
1542 : 16 : state->lastReturnedTuple = stup->tuple;
1543 : :
1544 : 16 : return true;
1545 : :
1546 : 2743928 : case TSS_FINALMERGE:
1547 : : Assert(forward);
1548 : : /* We are managing memory ourselves, with the slab allocator. */
1549 : : 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 [ + + ]: 2743928 : if (state->lastReturnedTuple)
1556 : : {
1557 [ + - + + ]: 2673699 : RELEASE_SLAB_SLOT(state, state->lastReturnedTuple);
1558 : 2673699 : state->lastReturnedTuple = NULL;
1559 : : }
1560 : :
1561 : : /*
1562 : : * This code should match the inner loop of mergeonerun().
1563 : : */
1564 [ + + ]: 2743928 : if (state->memtupcount > 0)
1565 : : {
1566 : 2743731 : int srcTapeIndex = state->memtuples[0].srctape;
1567 : 2743731 : LogicalTape *srcTape = state->inputTapes[srcTapeIndex];
1568 : : SortTuple newtup;
1569 : :
1570 : 2743731 : *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 : 2743731 : 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 [ + + ]: 2743731 : 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 : : */
1588 : 251 : tuplesort_heap_delete_top(state);
1589 : 251 : 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 : : */
1595 : 251 : LogicalTapeClose(srcTape);
1596 : 251 : return true;
1597 : : }
1598 : 2743480 : newtup.srctape = srcTapeIndex;
1599 : 2743480 : tuplesort_heap_replace_top(state, &newtup);
1600 : 2743480 : return true;
1601 : : }
1602 : 197 : return false;
1603 : :
1604 : 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
1617 : 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 : : Assert(forward);
1626 : : Assert(ntuples >= 0);
1627 : : Assert(!WORKER(state));
1628 : :
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 : : }
1637 : 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 : :
1650 : 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 : : */
1657 : 16 : oldcontext = MemoryContextSwitchTo(state->base.sortcontext);
1658 [ + + ]: 160088 : while (ntuples-- > 0)
1659 : : {
1660 : : SortTuple stup;
1661 : :
1662 [ - + ]: 160072 : if (!tuplesort_gettuple_common(state, forward, &stup))
1663 : : {
1664 : 0 : MemoryContextSwitchTo(oldcontext);
1665 : 0 : return false;
1666 : : }
1667 [ - + ]: 160072 : CHECK_FOR_INTERRUPTS();
1668 : : }
1669 : 16 : MemoryContextSwitchTo(oldcontext);
1670 : 16 : return true;
1671 : :
1672 : 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
1685 : 11379 : 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 : : */
1710 : 11379 : 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 : : */
1724 : 11379 : mOrder = Max(mOrder, MINORDER);
1725 : 11379 : mOrder = Min(mOrder, MAXORDER);
1726 : :
1727 : 11379 : 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
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
1772 : 475 : inittapes(Tuplesortstate *state, bool mergeruns)
1773 : : {
1774 : : Assert(!LEADER(state));
1775 : :
1776 [ + + ]: 475 : if (mergeruns)
1777 : : {
1778 : : /* Compute number of input tapes to use when merging */
1779 : 90 : state->maxTapes = tuplesort_merge_order(state->allowedMem);
1780 : : }
1781 : : else
1782 : : {
1783 : : /* Workers can sometimes produce single run, output without merge */
1784 : : Assert(WORKER(state));
1785 : 385 : state->maxTapes = MINORDER;
1786 : : }
1787 : :
1788 [ - + ]: 475 : if (trace_sort)
1789 [ # # ]: 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 */
1793 : 475 : inittapestate(state, state->maxTapes);
1794 : 475 : state->tapeset =
1795 : 475 : LogicalTapeSetCreate(false,
1796 [ + + ]: 475 : state->shared ? &state->shared->fileset : NULL,
1797 : : state->worker);
1798 : :
1799 : 475 : state->currentRun = 0;
1800 : :
1801 : : /*
1802 : : * Initialize logical tape arrays.
1803 : : */
1804 : 475 : state->inputTapes = NULL;
1805 : 475 : state->nInputTapes = 0;
1806 : 475 : state->nInputRuns = 0;
1807 : :
1808 : 475 : state->outputTapes = palloc0_array(LogicalTape *, state->maxTapes);
1809 : 475 : state->nOutputTapes = 0;
1810 : 475 : state->nOutputRuns = 0;
1811 : :
1812 : 475 : state->status = TSS_BUILDRUNS;
1813 : :
1814 : 475 : selectnewtape(state);
1815 : 475 : }
1816 : :
1817 : : /*
1818 : : * inittapestate - initialize generic tape management state
1819 : : */
1820 : : static void
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
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 : : */
1863 [ + + ]: 1310 : if (state->nOutputTapes < state->maxTapes)
1864 : : {
1865 : : /* Create a new tape to hold the next run */
1866 : : Assert(state->outputTapes[state->nOutputRuns] == NULL);
1867 : : Assert(state->nOutputRuns == state->nOutputTapes);
1868 : 882 : state->destTape = LogicalTapeCreate(state->tapeset);
1869 : 882 : state->outputTapes[state->nOutputTapes] = state->destTape;
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 : : }
1882 : 1310 : }
1883 : :
1884 : : /*
1885 : : * Initialize the slab allocation arena, for the given number of slots.
1886 : : */
1887 : : static void
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
1924 : 223 : mergeruns(Tuplesortstate *state)
1925 : : {
1926 : : int tapenum;
1927 : :
1928 : : Assert(state->status == TSS_BUILDRUNS);
1929 : : Assert(state->memtupcount == 0);
1930 : :
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 : : */
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 : : */
1974 [ + + ]: 223 : if (state->base.tuples)
1975 : 207 : init_slab_allocator(state, state->nOutputTapes + 1);
1976 : : else
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 : : */
1987 : 223 : state->memtupsize = state->nOutputTapes;
1988 : 446 : state->memtuples = (SortTuple *) MemoryContextAlloc(state->base.maincontext,
1989 : 223 : state->nOutputTapes * sizeof(SortTuple));
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 : : */
1997 : 223 : state->tape_buffer_mem = state->availMem;
1998 : 223 : USEMEM(state, state->tape_buffer_mem);
1999 [ - + ]: 223 : if (trace_sort)
2000 [ # # ]: 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 : : */
2011 [ + + ]: 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 : : */
2033 : 263 : state->outputTapes = palloc0_array(LogicalTape *, state->nInputTapes);
2034 : 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)
2047 [ # # ]: 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. */
2052 [ + + ]: 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 : : */
2061 [ + + ]: 263 : if ((state->base.sortopt & TUPLESORT_RANDOMACCESS) == 0
2062 [ + + ]: 245 : && state->nInputRuns <= state->nInputTapes
2063 [ + + + - ]: 209 : && !WORKER(state))
2064 : : {
2065 : : /* Tell logtape.c we won't be writing anymore */
2066 : 209 : LogicalTapeSetForgetFreeSpace(state->tapeset);
2067 : : /* Initialize for the final merge pass */
2068 : 209 : beginmerge(state);
2069 : 209 : state->status = TSS_FINALMERGE;
2070 : 209 : return;
2071 : : }
2072 : : }
2073 : :
2074 : : /* Select an output tape */
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];
2092 [ - + - - ]: 14 : if (!WORKER(state))
2093 : 14 : LogicalTapeFreeze(state->result_tape, NULL);
2094 : : else
2095 : 0 : worker_freeze_result_tape(state);
2096 : 14 : state->status = TSS_SORTEDONTAPE;
2097 : :
2098 : : /* Close all the now-empty input tapes, to release their read buffers. */
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
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 : : */
2116 : 146 : beginmerge(state);
2117 : :
2118 : : 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 : : */
2125 [ + + ]: 980650 : while (state->memtupcount > 0)
2126 : : {
2127 : : SortTuple stup;
2128 : :
2129 : : /* write the tuple to destTape */
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 */
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 : : */
2142 [ + + ]: 980504 : if (mergereadnext(state, srcTape, &stup))
2143 : : {
2144 : 979788 : stup.srctape = srcTapeIndex;
2145 : 979788 : tuplesort_heap_replace_top(state, &stup);
2146 : : }
2147 : : else
2148 : : {
2149 : 716 : tuplesort_heap_delete_top(state);
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);
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
2167 : 355 : beginmerge(Tuplesortstate *state)
2168 : : {
2169 : : int activeTapes;
2170 : : int srcTapeIndex;
2171 : :
2172 : : /* Heap should be empty here */
2173 : : Assert(state->memtupcount == 0);
2174 : :
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 : 987 : tup.srctape = srcTapeIndex;
2184 : 987 : tuplesort_heap_insert(state, &tup);
2185 : : }
2186 : : }
2187 : 355 : }
2188 : :
2189 : : /*
2190 : : * mergereadnext - read next tuple from one merge input tape
2191 : : *
2192 : : * Returns false on EOF.
2193 : : */
2194 : : static bool
2195 : 3725435 : mergereadnext(Tuplesortstate *state, LogicalTape *srcTape, SortTuple *stup)
2196 : : {
2197 : : unsigned int tuplen;
2198 : :
2199 : : /* read next tuple, if any */
2200 [ + + ]: 3725435 : if ((tuplen = getlen(srcTape, true)) == 0)
2201 : 1180 : return false;
2202 : 3724255 : READTUP(state, stup, srcTape, tuplen);
2203 : :
2204 : 3724255 : 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
2214 : 771498 : 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 : : */
2223 [ + + + + : 771498 : if (state->memtupcount < state->memtupsize && !LACKMEM(state) &&
- + ]
2224 [ + + ]: 770809 : !alltuples)
2225 : 770334 : 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 : : */
2235 [ + + - + ]: 1164 : if (state->memtupcount == 0 && state->currentRun > 0)
2236 : 0 : return;
2237 : :
2238 : : 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)
2245 [ # # ]: 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 : :
2250 [ + + ]: 1164 : if (state->currentRun > 0)
2251 : 689 : selectnewtape(state);
2252 : :
2253 : 1164 : state->currentRun++;
2254 : :
2255 [ - + ]: 1164 : if (trace_sort)
2256 [ # # ]: 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 : : */
2264 : 1164 : tuplesort_sort_memtuples(state);
2265 : :
2266 [ - + ]: 1164 : if (trace_sort)
2267 [ # # ]: 0 : elog(LOG, "worker %d finished quicksort of run %d: %s",
2268 : : state->worker, state->currentRun,
2269 : : pg_rusage_show(&state->ru_start));
2270 : :
2271 : 1164 : memtupwrite = state->memtupcount;
2272 [ + + ]: 3085063 : for (i = 0; i < memtupwrite; i++)
2273 : : {
2274 : 3083899 : SortTuple *stup = &state->memtuples[i];
2275 : :
2276 : 3083899 : 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 : : */
2288 : 1164 : MemoryContextReset(state->base.tuplecontext);
2289 : :
2290 : : /*
2291 : : * Now update the memory accounting to subtract the memory used by the
2292 : : * tuple.
2293 : : */
2294 : 1164 : FREEMEM(state, state->tupleMem);
2295 : 1164 : state->tupleMem = 0;
2296 : :
2297 : 1164 : markrunend(state->destTape);
2298 : :
2299 [ - + ]: 1164 : if (trace_sort)
2300 [ # # ]: 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
2309 : 38 : tuplesort_rescan(Tuplesortstate *state)
2310 : : {
2311 : 38 : MemoryContext oldcontext = MemoryContextSwitchTo(state->base.sortcontext);
2312 : :
2313 : : Assert(state->base.sortopt & TUPLESORT_RANDOMACCESS);
2314 : :
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:
2324 : 5 : LogicalTapeRewindForRead(state->result_tape, 0);
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;
2330 : 0 : default:
2331 [ # # ]: 0 : elog(ERROR, "invalid tuplesort state");
2332 : : break;
2333 : : }
2334 : :
2335 : 38 : MemoryContextSwitchTo(oldcontext);
2336 : 38 : }
2337 : :
2338 : : /*
2339 : : * tuplesort_markpos - saves current position in the merged sort file
2340 : : */
2341 : : void
2342 : 356017 : tuplesort_markpos(Tuplesortstate *state)
2343 : : {
2344 : 356017 : MemoryContext oldcontext = MemoryContextSwitchTo(state->base.sortcontext);
2345 : :
2346 : : Assert(state->base.sortopt & TUPLESORT_RANDOMACCESS);
2347 : :
2348 [ + + - ]: 356017 : switch (state->status)
2349 : : {
2350 : 350145 : case TSS_SORTEDINMEM:
2351 : 350145 : state->markpos_offset = state->current;
2352 : 350145 : state->markpos_eof = state->eof_reached;
2353 : 350145 : break;
2354 : 5872 : case TSS_SORTEDONTAPE:
2355 : 5872 : LogicalTapeTell(state->result_tape,
2356 : : &state->markpos_block,
2357 : : &state->markpos_offset);
2358 : 5872 : state->markpos_eof = state->eof_reached;
2359 : 5872 : break;
2360 : 0 : default:
2361 [ # # ]: 0 : elog(ERROR, "invalid tuplesort state");
2362 : : break;
2363 : : }
2364 : :
2365 : 356017 : MemoryContextSwitchTo(oldcontext);
2366 : 356017 : }
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 : : {
2375 : 28324 : MemoryContext oldcontext = MemoryContextSwitchTo(state->base.sortcontext);
2376 : :
2377 : : Assert(state->base.sortopt & TUPLESORT_RANDOMACCESS);
2378 : :
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:
2386 : 4128 : LogicalTapeSeek(state->result_tape,
2387 : : state->markpos_block,
2388 : : state->markpos_offset);
2389 : 4128 : state->eof_reached = state->markpos_eof;
2390 : 4128 : break;
2391 : 0 : default:
2392 [ # # ]: 0 : elog(ERROR, "invalid tuplesort state");
2393 : : break;
2394 : : }
2395 : :
2396 : 28324 : MemoryContextSwitchTo(oldcontext);
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
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 : : */
2418 : 264 : tuplesort_updatemax(state);
2419 : :
2420 [ + + ]: 264 : if (state->isMaxSpaceDisk)
2421 : 4 : stats->spaceType = SORT_SPACE_TYPE_DISK;
2422 : : else
2423 : 260 : stats->spaceType = SORT_SPACE_TYPE_MEMORY;
2424 : 264 : stats->spaceUsed = (state->maxSpace + 1023) / 1024;
2425 : :
2426 [ + - + - ]: 264 : switch (state->maxSpaceStatus)
2427 : : {
2428 : 260 : case TSS_SORTEDINMEM:
2429 [ + + ]: 260 : if (state->boundUsed)
2430 : 28 : stats->sortMethod = SORT_TYPE_TOP_N_HEAPSORT;
2431 : : else
2432 : 232 : stats->sortMethod = SORT_TYPE_QUICKSORT;
2433 : 260 : break;
2434 : 0 : case TSS_SORTEDONTAPE:
2435 : 0 : stats->sortMethod = SORT_TYPE_EXTERNAL_SORT;
2436 : 0 : break;
2437 : 4 : case TSS_FINALMERGE:
2438 : 4 : stats->sortMethod = SORT_TYPE_EXTERNAL_MERGE;
2439 : 4 : break;
2440 : 0 : default:
2441 : 0 : stats->sortMethod = SORT_TYPE_STILL_IN_PROGRESS;
2442 : 0 : break;
2443 : : }
2444 : 264 : }
2445 : :
2446 : : /*
2447 : : * Convert TuplesortMethod to a string.
2448 : : */
2449 : : const char *
2450 : 196 : tuplesort_method_name(TuplesortMethod m)
2451 : : {
2452 [ - + + - : 196 : switch (m)
+ - ]
2453 : : {
2454 : 0 : case SORT_TYPE_STILL_IN_PROGRESS:
2455 : 0 : return "still in progress";
2456 : 28 : case SORT_TYPE_TOP_N_HEAPSORT:
2457 : 28 : return "top-N heapsort";
2458 : 164 : case SORT_TYPE_QUICKSORT:
2459 : 164 : return "quicksort";
2460 : 0 : case SORT_TYPE_EXTERNAL_SORT:
2461 : 0 : return "external sort";
2462 : 4 : case SORT_TYPE_EXTERNAL_MERGE:
2463 : 4 : return "external merge";
2464 : : }
2465 : :
2466 : 0 : return "unknown";
2467 : : }
2468 : :
2469 : : /*
2470 : : * Convert TuplesortSpaceType to a string.
2471 : : */
2472 : : const char *
2473 : 172 : tuplesort_space_type_name(TuplesortSpaceType t)
2474 : : {
2475 : : 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
2494 : 269 : make_bounded_heap(Tuplesortstate *state)
2495 : : {
2496 : 269 : int tupcount = state->memtupcount;
2497 : : int i;
2498 : :
2499 : : Assert(state->status == TSS_INITIAL);
2500 : : Assert(state->bounded);
2501 : : Assert(tupcount >= state->bound);
2502 : : Assert(SERIAL(state));
2503 : :
2504 : : /* Reverse sort direction so largest entry will be at root */
2505 : 269 : reversedirection(state);
2506 : :
2507 : 269 : state->memtupcount = 0; /* make the heap empty */
2508 [ + + ]: 26416 : for (i = 0; i < tupcount; i++)
2509 : : {
2510 [ + + ]: 26147 : if (state->memtupcount < state->bound)
2511 : : {
2512 : : /* Insert next tuple into heap */
2513 : : /* Must copy source tuple to avoid possible overwrite */
2514 : 12939 : SortTuple stup = state->memtuples[i];
2515 : :
2516 : 12939 : 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 : : */
2525 [ + + ]: 13208 : if (COMPARETUP(state, &state->memtuples[i], &state->memtuples[0]) <= 0)
2526 : : {
2527 : 6458 : free_sort_tuple(state, &state->memtuples[i]);
2528 [ - + ]: 6458 : CHECK_FOR_INTERRUPTS();
2529 : : }
2530 : : else
2531 : 6750 : tuplesort_heap_replace_top(state, &state->memtuples[i]);
2532 : : }
2533 : : }
2534 : :
2535 : : Assert(state->memtupcount == state->bound);
2536 : 269 : state->status = TSS_BOUNDED;
2537 : 269 : }
2538 : :
2539 : : /*
2540 : : * Convert the bounded heap to a properly-sorted array
2541 : : */
2542 : : static void
2543 : 269 : sort_bounded_heap(Tuplesortstate *state)
2544 : : {
2545 : 269 : int tupcount = state->memtupcount;
2546 : :
2547 : : Assert(state->status == TSS_BOUNDED);
2548 : : Assert(state->bounded);
2549 : : Assert(tupcount == state->bound);
2550 : : 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 : : */
2557 [ + + ]: 12939 : while (state->memtupcount > 1)
2558 : : {
2559 : 12670 : SortTuple stup = state->memtuples[0];
2560 : :
2561 : : /* this sifts-up the next-largest entry and decreases memtupcount */
2562 : 12670 : tuplesort_heap_delete_top(state);
2563 : 12670 : state->memtuples[state->memtupcount] = stup;
2564 : : }
2565 : 269 : 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 : : */
2571 : 269 : reversedirection(state);
2572 : :
2573 : 269 : state->status = TSS_SORTEDINMEM;
2574 : 269 : state->boundUsed = true;
2575 : 269 : }
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
2584 : 27142486 : current_byte(Datum key, int level)
2585 : : {
2586 : 27142486 : int shift = (sizeof(Datum) - 1 - level) * BITS_PER_BYTE;
2587 : :
2588 : 27142486 : 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 : 27190731 : normalize_datum(Datum orig, SortSupport ssup)
2597 : : {
2598 : : Datum norm_datum1;
2599 : :
2600 [ + + ]: 27190731 : if (ssup->comparator == ssup_datum_int64_cmp)
2601 : 1110912 : norm_datum1 = orig + (Int64GetDatum(PG_INT64_MAX)) + 1;
2602 [ + + ]: 26079819 : else if (ssup->comparator == ssup_datum_uint64_cmp)
2603 : 6960109 : 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 : 19119710 : uint32 u32 = DatumGetUInt32(orig);
2612 : :
2613 [ + + ]: 19119710 : if (ssup->comparator == ssup_datum_int32_cmp)
2614 : 7791145 : norm_datum1 = UInt32GetDatum(u32 + ((uint32) PG_INT32_MAX) + 1);
2615 : : else
2616 : : {
2617 : 11328565 : norm_datum1 = UInt32GetDatum(u32);
2618 : : Assert(ssup->comparator == ssup_datum_uint32_cmp);
2619 : : }
2620 : : }
2621 : :
2622 [ + + ]: 27190731 : if (ssup->ssup_reverse)
2623 : 790326 : norm_datum1 = ~norm_datum1;
2624 : :
2625 : 27190731 : 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 : 48245 : radix_sort_recursive(SortTuple *begin, size_t n_elems, int level, Tuplesortstate *state)
2667 : : {
2668 : 48245 : RadixSortInfo partitions[256] = {0};
2669 : : uint8 remaining_partitions[256];
2670 : 48245 : size_t total = 0;
2671 : 48245 : int num_partitions = 0;
2672 : : int num_remaining;
2673 : 48245 : SortSupport ssup = &state->base.sortKeys[0];
2674 : : Datum ref_datum;
2675 : 48245 : Datum common_upper_bits = 0;
2676 : 48245 : size_t start_offset = 0;
2677 : 48245 : SortTuple *partition_begin = begin;
2678 : : int next_level;
2679 : :
2680 : : /* count number of occurrences of each byte */
2681 : 48245 : ref_datum = normalize_datum(begin[0].datum1, ssup);
2682 [ + + ]: 27190731 : for (SortTuple *st = begin; st < begin + n_elems; st++)
2683 : : {
2684 : : Datum this_datum;
2685 : : uint8 this_partition;
2686 : :
2687 : 27142486 : this_datum = normalize_datum(st->datum1, ssup);
2688 : : /* accumulate bits different from the reference datum */
2689 : 27142486 : common_upper_bits |= ref_datum ^ this_datum;
2690 : :
2691 : : /* extract the byte for this level from the normalized datum */
2692 : 27142486 : this_partition = current_byte(this_datum, level);
2693 : :
2694 : : /* save it for the permutation step */
2695 : 27142486 : st->curbyte = this_partition;
2696 : :
2697 : 27142486 : partitions[this_partition].count++;
2698 : :
2699 [ + + ]: 27142486 : CHECK_FOR_INTERRUPTS();
2700 : : }
2701 : :
2702 : : /* compute partition offsets */
2703 [ + + ]: 12398965 : for (int i = 0; i < 256; i++)
2704 : : {
2705 : 12350720 : size_t count = partitions[i].count;
2706 : :
2707 [ + + ]: 12350720 : if (count != 0)
2708 : : {
2709 : 2669777 : partitions[i].offset = total;
2710 : 2669777 : total += count;
2711 : 2669777 : remaining_partitions[num_partitions] = i;
2712 : 2669777 : num_partitions++;
2713 : : }
2714 : 12350720 : 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 : 48245 : num_remaining = num_partitions;
2738 [ + + ]: 198869 : while (num_remaining > 1)
2739 : : {
2740 : : /* start the count over */
2741 : 150624 : num_remaining = num_partitions;
2742 : :
2743 [ + + ]: 11832384 : for (int i = 0; i < num_partitions; i++)
2744 : : {
2745 : 11681760 : uint8 idx = remaining_partitions[i];
2746 : :
2747 : 11681760 : for (SortTuple *st = begin + partitions[idx].offset;
2748 [ + + ]: 29256050 : st < begin + partitions[idx].next_offset;
2749 : 17574290 : st++)
2750 : : {
2751 : 17574290 : size_t offset = partitions[st->curbyte].offset++;
2752 : : SortTuple tmp;
2753 : :
2754 : : /* swap current tuple with destination position */
2755 : : Assert(offset < n_elems);
2756 : 17574290 : tmp = *st;
2757 : 17574290 : *st = begin[offset];
2758 : 17574290 : begin[offset] = tmp;
2759 : :
2760 [ - + ]: 17574290 : CHECK_FOR_INTERRUPTS();
2761 : : };
2762 : :
2763 : : /* Is this partition sorted? */
2764 [ + + ]: 11681760 : if (partitions[idx].offset == partitions[idx].next_offset)
2765 : 9009131 : num_remaining--;
2766 : : }
2767 : : }
2768 : :
2769 : : /* recurse */
2770 : :
2771 [ + + ]: 48245 : 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 [ + + ]: 9567 : if (common_upper_bits == 0)
2781 : 1051 : 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 : 8516 : diffpos = pg_leftmost_one_pos64(DatumGetUInt64(common_upper_bits));
2791 : 8516 : next_level = sizeof(Datum) - 1 - (diffpos / BITS_PER_BYTE);
2792 : : }
2793 : : }
2794 : : else
2795 : 38678 : next_level = level + 1;
2796 : :
2797 : : Assert(next_level > level);
2798 : :
2799 : 48245 : for (uint8 *rp = remaining_partitions;
2800 [ + + ]: 2718022 : rp < remaining_partitions + num_partitions;
2801 : 2669777 : rp++)
2802 : : {
2803 : 2669777 : size_t end_offset = partitions[*rp].next_offset;
2804 : 2669777 : SortTuple *partition_end = begin + end_offset;
2805 : 2669777 : size_t num_elements = end_offset - start_offset;
2806 : :
2807 [ + + ]: 2669777 : if (num_elements > 1)
2808 : : {
2809 [ + + ]: 875860 : if (next_level < sizeof(Datum))
2810 : : {
2811 [ + + ]: 684559 : if (num_elements < QSORT_THRESHOLD)
2812 : : {
2813 : 642007 : qsort_tuple(partition_begin,
2814 : : num_elements,
2815 : : state->base.comparetup,
2816 : : state);
2817 : : }
2818 : : else
2819 : : {
2820 : 42552 : radix_sort_recursive(partition_begin,
2821 : : num_elements,
2822 : : next_level,
2823 : : state);
2824 : : }
2825 : : }
2826 [ + + ]: 191301 : 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 : 95878 : qsort_tuple(partition_begin,
2834 : : num_elements,
2835 : : state->base.comparetup_tiebreak,
2836 : : state);
2837 : : }
2838 : : }
2839 : :
2840 : 2669777 : start_offset = end_offset;
2841 : 2669777 : partition_begin = partition_end;
2842 : : }
2843 : 48245 : }
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 : 7744 : radix_sort_tuple(SortTuple *data, size_t n, Tuplesortstate *state)
2853 : : {
2854 : 7744 : bool nulls_first = state->base.sortKeys[0].ssup_nulls_first;
2855 : : SortTuple *null_start;
2856 : : SortTuple *not_null_start;
2857 : 7744 : 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 [ + + + + ]: 13597800 : while (d1 < n && data[d1].isnull1 == nulls_first)
2869 : : {
2870 : 13590056 : d1++;
2871 [ - + ]: 13590056 : 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 : : Assert(n > 0);
2880 [ + + ]: 7744 : if (d1 < n - 1)
2881 : : {
2882 : 746 : size_t i = d1,
2883 : 746 : j = d1;
2884 : 746 : SortTuple tmp = data[d1]; /* create gap at front */
2885 : :
2886 [ + + ]: 436507 : while (j < n - 1)
2887 : : {
2888 : : /* gap is at j, move i's element to gap */
2889 : 435761 : data[j] = data[i];
2890 : : /* advance j to the first unknown element */
2891 : 435761 : j += 1;
2892 : : /* move the first unknown element back to i */
2893 : 435761 : data[i] = data[j];
2894 : : /* advance i if this element belongs in the left partition */
2895 : 435761 : i += (data[i].isnull1 == nulls_first);
2896 : :
2897 [ - + ]: 435761 : CHECK_FOR_INTERRUPTS();
2898 : : }
2899 : :
2900 : : /* place gap between left and right partitions */
2901 : 746 : data[j] = data[i];
2902 : : /* restore the saved element */
2903 : 746 : data[i] = tmp;
2904 : : /* assign it to the correct partition */
2905 : 746 : i += (data[i].isnull1 == nulls_first);
2906 : :
2907 : : /* d1 is now the number of elements in the left partition */
2908 : 746 : d1 = i;
2909 : : }
2910 : :
2911 : 7744 : d2 = n - d1;
2912 : :
2913 : : /* set pointers and counts for each partition */
2914 [ + + ]: 7744 : if (nulls_first)
2915 : : {
2916 : 637 : null_start = data;
2917 : 637 : null_count = d1;
2918 : 637 : not_null_start = data + d1;
2919 : 637 : not_null_count = d2;
2920 : : }
2921 : : else
2922 : : {
2923 : 7107 : not_null_start = data;
2924 : 7107 : not_null_count = d1;
2925 : 7107 : null_start = data + d1;
2926 : 7107 : null_count = d2;
2927 : : }
2928 : :
2929 : 7744 : for (SortTuple *st = null_start;
2930 [ + + ]: 11637 : st < null_start + null_count;
2931 : 3893 : st++)
2932 : : Assert(st->isnull1 == true);
2933 : 7744 : for (SortTuple *st = not_null_start;
2934 [ + + ]: 14030418 : st < not_null_start + not_null_count;
2935 : 14022674 : st++)
2936 : : Assert(st->isnull1 == false);
2937 : :
2938 : : /*
2939 : : * Sort the NULL partition using tiebreak comparator, if necessary.
2940 : : */
2941 [ + + + + ]: 7744 : 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 [ + + ]: 7744 : 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 : 7726 : bool presorted = true;
2963 : :
2964 : 7726 : for (SortTuple *st = not_null_start + 1;
2965 [ + + ]: 5105365 : st < not_null_start + not_null_count;
2966 : 5097639 : st++)
2967 : : {
2968 [ + + ]: 5103332 : if (COMPARETUP(state, st - 1, st) > 0)
2969 : : {
2970 : 5693 : presorted = false;
2971 : 5693 : break;
2972 : : }
2973 : :
2974 [ + + ]: 5097639 : CHECK_FOR_INTERRUPTS();
2975 : : }
2976 : :
2977 [ + + ]: 7726 : if (presorted)
2978 : 2033 : return;
2979 : : else
2980 : : {
2981 : 5693 : 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 : 7744 : verify_memtuples_sorted(Tuplesortstate *state)
2992 : : {
2993 : : #ifdef USE_ASSERT_CHECKING
2994 : : for (SortTuple *st = state->memtuples + 1;
2995 : : st < state->memtuples + state->memtupcount;
2996 : : st++)
2997 : : Assert(COMPARETUP(state, st - 1, st) <= 0);
2998 : : #endif
2999 : 7744 : }
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
3008 : 151052 : tuplesort_sort_memtuples(Tuplesortstate *state)
3009 : : {
3010 : : Assert(!LEADER(state));
3011 : :
3012 [ + + ]: 151052 : if (state->memtupcount > 1)
3013 : : {
3014 : : /*
3015 : : * Do we have the leading column's value or abbreviation in datum1?
3016 : : */
3017 [ + + + + ]: 44899 : if (state->base.haveDatum1 && state->base.sortKeys)
3018 : : {
3019 : 44833 : SortSupport ssup = &state->base.sortKeys[0];
3020 : :
3021 : : /* Does it compare as an integer? */
3022 [ + + ]: 44833 : if (state->memtupcount >= QSORT_THRESHOLD &&
3023 [ + + ]: 8849 : (ssup->comparator == ssup_datum_uint64_cmp ||
3024 [ + + ]: 8282 : ssup->comparator == ssup_datum_int64_cmp ||
3025 [ + + ]: 8089 : ssup->comparator == ssup_datum_uint32_cmp ||
3026 [ + + ]: 4334 : ssup->comparator == ssup_datum_int32_cmp))
3027 : : {
3028 : 7744 : radix_sort_tuple(state->memtuples,
3029 : 7744 : state->memtupcount,
3030 : : state);
3031 : 7744 : verify_memtuples_sorted(state);
3032 : 7744 : return;
3033 : : }
3034 : : }
3035 : :
3036 : : /* Can we use the single-key sort function? */
3037 [ + + ]: 37155 : if (state->base.onlyKey != NULL)
3038 : : {
3039 : 26600 : qsort_ssup(state->memtuples, state->memtupcount,
3040 : 26600 : state->base.onlyKey);
3041 : : }
3042 : : else
3043 : : {
3044 : 10555 : qsort_tuple(state->memtuples,
3045 : 10555 : 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
3062 : 13926 : tuplesort_heap_insert(Tuplesortstate *state, SortTuple *tuple)
3063 : : {
3064 : : SortTuple *memtuples;
3065 : : int j;
3066 : :
3067 : 13926 : memtuples = state->memtuples;
3068 : : Assert(state->memtupcount < state->memtupsize);
3069 : :
3070 [ + + ]: 13926 : 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 : : */
3076 : 13926 : j = state->memtupcount++;
3077 [ + + ]: 38538 : while (j > 0)
3078 : : {
3079 : 34301 : int i = (j - 1) >> 1;
3080 : :
3081 [ + + ]: 34301 : if (COMPARETUP(state, tuple, &memtuples[i]) >= 0)
3082 : 9689 : break;
3083 : 24612 : memtuples[j] = memtuples[i];
3084 : 24612 : j = i;
3085 : : }
3086 : 13926 : memtuples[j] = *tuple;
3087 : 13926 : }
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
3097 : 13637 : tuplesort_heap_delete_top(Tuplesortstate *state)
3098 : : {
3099 : 13637 : SortTuple *memtuples = state->memtuples;
3100 : : SortTuple *tuple;
3101 : :
3102 [ + + ]: 13637 : if (--state->memtupcount <= 0)
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 : : */
3109 : 13377 : tuple = &memtuples[state->memtupcount];
3110 : 13377 : 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 : 4078560 : tuplesort_heap_replace_top(Tuplesortstate *state, SortTuple *tuple)
3122 : : {
3123 : 4078560 : SortTuple *memtuples = state->memtuples;
3124 : : unsigned int i,
3125 : : n;
3126 : :
3127 : : Assert(state->memtupcount >= 1);
3128 : :
3129 [ + + ]: 4078560 : 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 : : */
3136 : 4078560 : n = state->memtupcount;
3137 : 4078560 : i = 0; /* i is where the "hole" is */
3138 : : for (;;)
3139 : 1171886 : {
3140 : 5250446 : unsigned int j = 2 * i + 1;
3141 : :
3142 [ + + ]: 5250446 : if (j >= n)
3143 : 886444 : break;
3144 [ + + + + ]: 5944055 : if (j + 1 < n &&
3145 : 1580053 : COMPARETUP(state, &memtuples[j], &memtuples[j + 1]) > 0)
3146 : 633799 : j++;
3147 [ + + ]: 4364002 : if (COMPARETUP(state, tuple, &memtuples[j]) <= 0)
3148 : 3192116 : break;
3149 : 1171886 : memtuples[i] = memtuples[j];
3150 : 1171886 : i = j;
3151 : : }
3152 : 4078560 : memtuples[i] = *tuple;
3153 : 4078560 : }
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
3161 : 538 : reversedirection(Tuplesortstate *state)
3162 : : {
3163 : 538 : SortSupport sortKey = state->base.sortKeys;
3164 : : int nkey;
3165 : :
3166 [ + + ]: 1308 : for (nkey = 0; nkey < state->base.nKeys; nkey++, sortKey++)
3167 : : {
3168 : 770 : sortKey->ssup_reverse = !sortKey->ssup_reverse;
3169 : 770 : sortKey->ssup_nulls_first = !sortKey->ssup_nulls_first;
3170 : : }
3171 : 538 : }
3172 : :
3173 : :
3174 : : /*
3175 : : * Tape interface routines
3176 : : */
3177 : :
3178 : : static unsigned int
3179 : 3922442 : getlen(LogicalTape *tape, bool eofOK)
3180 : : {
3181 : : unsigned int len;
3182 : :
3183 [ - + ]: 3922442 : if (LogicalTapeRead(tape,
3184 : : &len, sizeof(len)) != sizeof(len))
3185 [ # # ]: 0 : elog(ERROR, "unexpected end of tape");
3186 [ + + - + ]: 3922442 : if (len == 0 && !eofOK)
3187 [ # # ]: 0 : elog(ERROR, "unexpected end of data");
3188 : 3922442 : return len;
3189 : : }
3190 : :
3191 : : static void
3192 : 1310 : markrunend(LogicalTape *tape)
3193 : : {
3194 : 1310 : unsigned int len = 0;
3195 : :
3196 : 1310 : LogicalTapeWrite(tape, &len, sizeof(len));
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 *
3206 : 3666047 : 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 : : */
3214 : : Assert(state->slabFreeHead);
3215 : :
3216 [ + + - + ]: 3666047 : if (tuplen > SLAB_SLOT_SIZE || !state->slabFreeHead)
3217 : 5 : return MemoryContextAlloc(state->base.sortcontext, tuplen);
3218 : : else
3219 : : {
3220 : 3666042 : buf = state->slabFreeHead;
3221 : : /* Reuse this slot */
3222 : 3666042 : state->slabFreeHead = buf->nextfree;
3223 : :
3224 : 3666042 : 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
3240 : 134 : tuplesort_estimate_shared(int nWorkers)
3241 : : {
3242 : : Size tapesSize;
3243 : :
3244 : : 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 : : Assert(nWorkers > 0);
3266 : :
3267 : 182 : pg_atomic_init_u32(&shared->currentWorker, 0);
3268 : 182 : pg_atomic_init_u32(&shared->workersFinished, 0);
3269 : 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 : : Assert(WORKER(state));
3306 : :
3307 : 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
3324 : 385 : worker_freeze_result_tape(Tuplesortstate *state)
3325 : : {
3326 : 385 : Sharedsort *shared = state->shared;
3327 : : TapeShare output;
3328 : :
3329 : : Assert(WORKER(state));
3330 : : Assert(state->result_tape != NULL);
3331 : : 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 : : */
3346 : 385 : LogicalTapeFreeze(state->result_tape, &output);
3347 : :
3348 : : /* Store properties of output tape, and update finished worker count */
3349 : 385 : shared->tapes[state->worker] = output;
3350 : 385 : pg_atomic_fetch_add_u32(&shared->workersFinished, 1);
3351 : 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 : : Assert(WORKER(state));
3363 : : Assert(state->result_tape == NULL);
3364 : : Assert(state->nOutputRuns == 1);
3365 : :
3366 : 385 : state->result_tape = state->destTape;
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 : : Assert(LEADER(state));
3390 : : Assert(nParticipants >= 1);
3391 : :
3392 : 133 : workersFinished = pg_atomic_read_membarrier_u32(&shared->workersFinished);
3393 : :
3394 [ - + ]: 133 : if (nParticipants != workersFinished)
3395 [ # # ]: 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 : : */
3402 : 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 : : */
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 : : */
3419 : 133 : state->inputTapes = NULL;
3420 : 133 : state->nInputTapes = 0;
3421 : 133 : state->nInputRuns = 0;
3422 : :
3423 : 133 : state->outputTapes = palloc0_array(LogicalTape *, nParticipants);
3424 : 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 : :
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
3439 : 2154675 : free_sort_tuple(Tuplesortstate *state, SortTuple *stup)
3440 : : {
3441 [ + + ]: 2154675 : if (stup->tuple)
3442 : : {
3443 : 2047566 : FREEMEM(state, GetMemoryChunkSpace(stup->tuple));
3444 : 2047566 : pfree(stup->tuple);
3445 : 2047566 : stup->tuple = NULL;
3446 : : }
3447 : 2154675 : }
3448 : :
3449 : : int
3450 : 2549353 : ssup_datum_uint64_cmp(Datum x, Datum y, SortSupport ssup)
3451 : : {
3452 [ + + ]: 2549353 : if (x < y)
3453 : 874476 : return -1;
3454 [ + + ]: 1674877 : else if (x > y)
3455 : 641296 : return 1;
3456 : : else
3457 : 1033581 : return 0;
3458 : : }
3459 : :
3460 : : int
3461 : 1949287 : ssup_datum_int64_cmp(Datum x, Datum y, SortSupport ssup)
3462 : : {
3463 : 1949287 : int64 xx = DatumGetInt64(x);
3464 : 1949287 : int64 yy = DatumGetInt64(y);
3465 : :
3466 [ + + ]: 1949287 : if (xx < yy)
3467 : 1447869 : return -1;
3468 [ + + ]: 501418 : else if (xx > yy)
3469 : 245802 : return 1;
3470 : : else
3471 : 255616 : return 0;
3472 : : }
3473 : :
3474 : : int
3475 : 123876436 : ssup_datum_uint32_cmp(Datum x, Datum y, SortSupport ssup)
3476 : : {
3477 : 123876436 : uint32 xx = DatumGetUInt32(x);
3478 : 123876436 : uint32 yy = DatumGetUInt32(y);
3479 : :
3480 [ + + ]: 123876436 : if (xx < yy)
3481 : 30357786 : return -1;
3482 [ + + ]: 93518650 : else if (xx > yy)
3483 : 30445527 : return 1;
3484 : : else
3485 : 63073123 : return 0;
3486 : : }
3487 : :
3488 : : int
3489 : 166284201 : ssup_datum_int32_cmp(Datum x, Datum y, SortSupport ssup)
3490 : : {
3491 : 166284201 : int32 xx = DatumGetInt32(x);
3492 : 166284201 : int32 yy = DatumGetInt32(y);
3493 : :
3494 [ + + ]: 166284201 : if (xx < yy)
3495 : 38828588 : return -1;
3496 [ + + ]: 127455613 : else if (xx > yy)
3497 : 34254365 : return 1;
3498 : : else
3499 : 93201248 : return 0;
3500 : : }
|