PostgreSQL Source Code  git master
nbtsort.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * nbtsort.c
4  * Build a btree from sorted input by loading leaf pages sequentially.
5  *
6  * NOTES
7  *
8  * We use tuplesort.c to sort the given index tuples into order.
9  * Then we scan the index tuples in order and build the btree pages
10  * for each level. We load source tuples into leaf-level pages.
11  * Whenever we fill a page at one level, we add a link to it to its
12  * parent level (starting a new parent level if necessary). When
13  * done, we write out each final page on each level, adding it to
14  * its parent level. When we have only one page on a level, it must be
15  * the root -- it can be attached to the btree metapage and we are done.
16  *
17  * It is not wise to pack the pages entirely full, since then *any*
18  * insertion would cause a split (and not only of the leaf page; the need
19  * for a split would cascade right up the tree). The steady-state load
20  * factor for btrees is usually estimated at 70%. We choose to pack leaf
21  * pages to the user-controllable fill factor (default 90%) while upper pages
22  * are always packed to 70%. This gives us reasonable density (there aren't
23  * many upper pages if the keys are reasonable-size) without risking a lot of
24  * cascading splits during early insertions.
25  *
26  * Formerly the index pages being built were kept in shared buffers, but
27  * that is of no value (since other backends have no interest in them yet)
28  * and it created locking problems for CHECKPOINT, because the upper-level
29  * pages were held exclusive-locked for long periods. Now we just build
30  * the pages in local memory and smgrwrite or smgrextend them as we finish
31  * them. They will need to be re-read into shared buffers on first use after
32  * the build finishes.
33  *
34  * Since the index will never be used unless it is completely built,
35  * from a crash-recovery point of view there is no need to WAL-log the
36  * steps of the build. After completing the index build, we can just sync
37  * the whole file to disk using smgrimmedsync() before exiting this module.
38  * This can be seen to be sufficient for crash recovery by considering that
39  * it's effectively equivalent to what would happen if a CHECKPOINT occurred
40  * just after the index build. However, it is clearly not sufficient if the
41  * DBA is using the WAL log for PITR or replication purposes, since another
42  * machine would not be able to reconstruct the index from WAL. Therefore,
43  * we log the completed index pages to WAL if and only if WAL archiving is
44  * active.
45  *
46  * This code isn't concerned about the FSM at all. The caller is responsible
47  * for initializing that.
48  *
49  * Portions Copyright (c) 1996-2019, PostgreSQL Global Development Group
50  * Portions Copyright (c) 1994, Regents of the University of California
51  *
52  * IDENTIFICATION
53  * src/backend/access/nbtree/nbtsort.c
54  *
55  *-------------------------------------------------------------------------
56  */
57 
58 #include "postgres.h"
59 
60 #include "access/nbtree.h"
61 #include "access/parallel.h"
62 #include "access/relscan.h"
63 #include "access/table.h"
64 #include "access/tableam.h"
65 #include "access/xact.h"
66 #include "access/xlog.h"
67 #include "access/xloginsert.h"
68 #include "catalog/index.h"
69 #include "commands/progress.h"
70 #include "miscadmin.h"
71 #include "pgstat.h"
72 #include "storage/smgr.h"
73 #include "tcop/tcopprot.h" /* pgrminclude ignore */
74 #include "utils/rel.h"
75 #include "utils/sortsupport.h"
76 #include "utils/tuplesort.h"
77 
78 
79 /* Magic numbers for parallel state sharing */
80 #define PARALLEL_KEY_BTREE_SHARED UINT64CONST(0xA000000000000001)
81 #define PARALLEL_KEY_TUPLESORT UINT64CONST(0xA000000000000002)
82 #define PARALLEL_KEY_TUPLESORT_SPOOL2 UINT64CONST(0xA000000000000003)
83 #define PARALLEL_KEY_QUERY_TEXT UINT64CONST(0xA000000000000004)
84 
85 /*
86  * DISABLE_LEADER_PARTICIPATION disables the leader's participation in
87  * parallel index builds. This may be useful as a debugging aid.
88 #undef DISABLE_LEADER_PARTICIPATION
89  */
90 
91 /*
92  * Status record for spooling/sorting phase. (Note we may have two of
93  * these due to the special requirements for uniqueness-checking with
94  * dead tuples.)
95  */
96 typedef struct BTSpool
97 {
98  Tuplesortstate *sortstate; /* state data for tuplesort.c */
101  bool isunique;
102 } BTSpool;
103 
104 /*
105  * Status for index builds performed in parallel. This is allocated in a
106  * dynamic shared memory segment. Note that there is a separate tuplesort TOC
107  * entry, private to tuplesort.c but allocated by this module on its behalf.
108  */
109 typedef struct BTShared
110 {
111  /*
112  * These fields are not modified during the sort. They primarily exist
113  * for the benefit of worker processes that need to create BTSpool state
114  * corresponding to that used by the leader.
115  */
118  bool isunique;
121 
122  /*
123  * workersdonecv is used to monitor the progress of workers. All parallel
124  * participants must indicate that they are done before leader can use
125  * mutable state that workers maintain during scan (and before leader can
126  * proceed to tuplesort_performsort()).
127  */
129 
130  /*
131  * mutex protects all fields before heapdesc.
132  *
133  * These fields contain status information of interest to B-Tree index
134  * builds that must work just the same when an index is built in parallel.
135  */
137 
138  /*
139  * Mutable state that is maintained by workers, and reported back to
140  * leader at end of parallel scan.
141  *
142  * nparticipantsdone is number of worker processes finished.
143  *
144  * reltuples is the total number of input heap tuples.
145  *
146  * havedead indicates if RECENTLY_DEAD tuples were encountered during
147  * build.
148  *
149  * indtuples is the total number of tuples that made it into the index.
150  *
151  * brokenhotchain indicates if any worker detected a broken HOT chain
152  * during build.
153  */
155  double reltuples;
156  bool havedead;
157  double indtuples;
159 
160  /*
161  * ParallelTableScanDescData data follows. Can't directly embed here, as
162  * implementations of the parallel table scan desc interface might need
163  * stronger alignment.
164  */
165 } BTShared;
166 
167 /*
168  * Return pointer to a BTShared's parallel table scan.
169  *
170  * c.f. shm_toc_allocate as to why BUFFERALIGN is used, rather than just
171  * MAXALIGN.
172  */
173 #define ParallelTableScanFromBTShared(shared) \
174  (ParallelTableScanDesc) ((char *) (shared) + BUFFERALIGN(sizeof(BTShared)))
175 
176 /*
177  * Status for leader in parallel index build.
178  */
179 typedef struct BTLeader
180 {
181  /* parallel context itself */
183 
184  /*
185  * nparticipanttuplesorts is the exact number of worker processes
186  * successfully launched, plus one leader process if it participates as a
187  * worker (only DISABLE_LEADER_PARTICIPATION builds avoid leader
188  * participating as a worker).
189  */
191 
192  /*
193  * Leader process convenience pointers to shared state (leader avoids TOC
194  * lookups).
195  *
196  * btshared is the shared state for entire build. sharedsort is the
197  * shared, tuplesort-managed state passed to each process tuplesort.
198  * sharedsort2 is the corresponding btspool2 shared state, used only when
199  * building unique indexes. snapshot is the snapshot used by the scan iff
200  * an MVCC snapshot is required.
201  */
206 } BTLeader;
207 
208 /*
209  * Working state for btbuild and its callback.
210  *
211  * When parallel CREATE INDEX is used, there is a BTBuildState for each
212  * participant.
213  */
214 typedef struct BTBuildState
215 {
216  bool isunique;
217  bool havedead;
220 
221  /*
222  * spool2 is needed only when the index is a unique index. Dead tuples are
223  * put into spool2 instead of spool in order to avoid uniqueness check.
224  */
226  double indtuples;
227 
228  /*
229  * btleader is only present when a parallel index build is performed, and
230  * only in the leader process. (Actually, only the leader has a
231  * BTBuildState. Workers have their own spool and spool2, though.)
232  */
234 } BTBuildState;
235 
236 /*
237  * Status record for a btree page being built. We have one of these
238  * for each active tree level.
239  */
240 typedef struct BTPageState
241 {
242  Page btps_page; /* workspace for page building */
243  BlockNumber btps_blkno; /* block # to write this page at */
244  IndexTuple btps_lowkey; /* page's strict lower bound pivot tuple */
245  OffsetNumber btps_lastoff; /* last item offset loaded */
246  uint32 btps_level; /* tree level (0 = leaf) */
247  Size btps_full; /* "full" if less than this much free space */
248  struct BTPageState *btps_next; /* link to parent level, if any */
249 } BTPageState;
250 
251 /*
252  * Overall status record for index writing phase.
253  */
254 typedef struct BTWriteState
255 {
258  BTScanInsert inskey; /* generic insertion scankey */
259  bool btws_use_wal; /* dump pages to WAL? */
260  BlockNumber btws_pages_alloced; /* # pages allocated */
261  BlockNumber btws_pages_written; /* # pages written out */
262  Page btws_zeropage; /* workspace for filling zeroes */
263 } BTWriteState;
264 
265 
267  BTBuildState *buildstate, IndexInfo *indexInfo);
268 static void _bt_spooldestroy(BTSpool *btspool);
269 static void _bt_spool(BTSpool *btspool, ItemPointer self,
270  Datum *values, bool *isnull);
271 static void _bt_leafbuild(BTSpool *btspool, BTSpool *btspool2);
273  bool *isnull, bool tupleIsAlive, void *state);
274 static Page _bt_blnewpage(uint32 level);
275 static BTPageState *_bt_pagestate(BTWriteState *wstate, uint32 level);
276 static void _bt_slideleft(Page page);
277 static void _bt_sortaddtup(Page page, Size itemsize,
278  IndexTuple itup, OffsetNumber itup_off);
279 static void _bt_buildadd(BTWriteState *wstate, BTPageState *state,
280  IndexTuple itup);
281 static void _bt_uppershutdown(BTWriteState *wstate, BTPageState *state);
282 static void _bt_load(BTWriteState *wstate,
283  BTSpool *btspool, BTSpool *btspool2);
284 static void _bt_begin_parallel(BTBuildState *buildstate, bool isconcurrent,
285  int request);
286 static void _bt_end_parallel(BTLeader *btleader);
288 static double _bt_parallel_heapscan(BTBuildState *buildstate,
289  bool *brokenhotchain);
290 static void _bt_leader_participate_as_worker(BTBuildState *buildstate);
291 static void _bt_parallel_scan_and_sort(BTSpool *btspool, BTSpool *btspool2,
292  BTShared *btshared, Sharedsort *sharedsort,
293  Sharedsort *sharedsort2, int sortmem,
294  bool progress);
295 
296 
297 /*
298  * btbuild() -- build a new btree index.
299  */
302 {
303  IndexBuildResult *result;
304  BTBuildState buildstate;
305  double reltuples;
306 
307 #ifdef BTREE_BUILD_STATS
309  ResetUsage();
310 #endif /* BTREE_BUILD_STATS */
311 
312  buildstate.isunique = indexInfo->ii_Unique;
313  buildstate.havedead = false;
314  buildstate.heap = heap;
315  buildstate.spool = NULL;
316  buildstate.spool2 = NULL;
317  buildstate.indtuples = 0;
318  buildstate.btleader = NULL;
319 
320  /*
321  * We expect to be called exactly once for any index relation. If that's
322  * not the case, big trouble's what we have.
323  */
324  if (RelationGetNumberOfBlocks(index) != 0)
325  elog(ERROR, "index \"%s\" already contains data",
326  RelationGetRelationName(index));
327 
328  reltuples = _bt_spools_heapscan(heap, index, &buildstate, indexInfo);
329 
330  /*
331  * Finish the build by (1) completing the sort of the spool file, (2)
332  * inserting the sorted tuples into btree pages and (3) building the upper
333  * levels. Finally, it may also be necessary to end use of parallelism.
334  */
335  _bt_leafbuild(buildstate.spool, buildstate.spool2);
336  _bt_spooldestroy(buildstate.spool);
337  if (buildstate.spool2)
338  _bt_spooldestroy(buildstate.spool2);
339  if (buildstate.btleader)
340  _bt_end_parallel(buildstate.btleader);
341 
342  result = (IndexBuildResult *) palloc(sizeof(IndexBuildResult));
343 
344  result->heap_tuples = reltuples;
345  result->index_tuples = buildstate.indtuples;
346 
347 #ifdef BTREE_BUILD_STATS
349  {
350  ShowUsage("BTREE BUILD STATS");
351  ResetUsage();
352  }
353 #endif /* BTREE_BUILD_STATS */
354 
355  return result;
356 }
357 
358 /*
359  * Create and initialize one or two spool structures, and save them in caller's
360  * buildstate argument. May also fill-in fields within indexInfo used by index
361  * builds.
362  *
363  * Scans the heap, possibly in parallel, filling spools with IndexTuples. This
364  * routine encapsulates all aspects of managing parallelism. Caller need only
365  * call _bt_end_parallel() in parallel case after it is done with spool/spool2.
366  *
367  * Returns the total number of heap tuples scanned.
368  */
369 static double
371  IndexInfo *indexInfo)
372 {
373  BTSpool *btspool = (BTSpool *) palloc0(sizeof(BTSpool));
374  SortCoordinate coordinate = NULL;
375  double reltuples = 0;
376 
377  /*
378  * We size the sort area as maintenance_work_mem rather than work_mem to
379  * speed index creation. This should be OK since a single backend can't
380  * run multiple index creations in parallel (see also: notes on
381  * parallelism and maintenance_work_mem below).
382  */
383  btspool->heap = heap;
384  btspool->index = index;
385  btspool->isunique = indexInfo->ii_Unique;
386 
387  /* Save as primary spool */
388  buildstate->spool = btspool;
389 
390  /* Report table scan phase started */
393 
394  /* Attempt to launch parallel worker scan when required */
395  if (indexInfo->ii_ParallelWorkers > 0)
396  _bt_begin_parallel(buildstate, indexInfo->ii_Concurrent,
397  indexInfo->ii_ParallelWorkers);
398 
399  /*
400  * If parallel build requested and at least one worker process was
401  * successfully launched, set up coordination state
402  */
403  if (buildstate->btleader)
404  {
405  coordinate = (SortCoordinate) palloc0(sizeof(SortCoordinateData));
406  coordinate->isWorker = false;
407  coordinate->nParticipants =
408  buildstate->btleader->nparticipanttuplesorts;
409  coordinate->sharedsort = buildstate->btleader->sharedsort;
410  }
411 
412  /*
413  * Begin serial/leader tuplesort.
414  *
415  * In cases where parallelism is involved, the leader receives the same
416  * share of maintenance_work_mem as a serial sort (it is generally treated
417  * in the same way as a serial sort once we return). Parallel worker
418  * Tuplesortstates will have received only a fraction of
419  * maintenance_work_mem, though.
420  *
421  * We rely on the lifetime of the Leader Tuplesortstate almost not
422  * overlapping with any worker Tuplesortstate's lifetime. There may be
423  * some small overlap, but that's okay because we rely on leader
424  * Tuplesortstate only allocating a small, fixed amount of memory here.
425  * When its tuplesort_performsort() is called (by our caller), and
426  * significant amounts of memory are likely to be used, all workers must
427  * have already freed almost all memory held by their Tuplesortstates
428  * (they are about to go away completely, too). The overall effect is
429  * that maintenance_work_mem always represents an absolute high watermark
430  * on the amount of memory used by a CREATE INDEX operation, regardless of
431  * the use of parallelism or any other factor.
432  */
433  buildstate->spool->sortstate =
434  tuplesort_begin_index_btree(heap, index, buildstate->isunique,
435  maintenance_work_mem, coordinate,
436  false);
437 
438  /*
439  * If building a unique index, put dead tuples in a second spool to keep
440  * them out of the uniqueness check. We expect that the second spool (for
441  * dead tuples) won't get very full, so we give it only work_mem.
442  */
443  if (indexInfo->ii_Unique)
444  {
445  BTSpool *btspool2 = (BTSpool *) palloc0(sizeof(BTSpool));
446  SortCoordinate coordinate2 = NULL;
447 
448  /* Initialize secondary spool */
449  btspool2->heap = heap;
450  btspool2->index = index;
451  btspool2->isunique = false;
452  /* Save as secondary spool */
453  buildstate->spool2 = btspool2;
454 
455  if (buildstate->btleader)
456  {
457  /*
458  * Set up non-private state that is passed to
459  * tuplesort_begin_index_btree() about the basic high level
460  * coordination of a parallel sort.
461  */
462  coordinate2 = (SortCoordinate) palloc0(sizeof(SortCoordinateData));
463  coordinate2->isWorker = false;
464  coordinate2->nParticipants =
465  buildstate->btleader->nparticipanttuplesorts;
466  coordinate2->sharedsort = buildstate->btleader->sharedsort2;
467  }
468 
469  /*
470  * We expect that the second one (for dead tuples) won't get very
471  * full, so we give it only work_mem
472  */
473  buildstate->spool2->sortstate =
474  tuplesort_begin_index_btree(heap, index, false, work_mem,
475  coordinate2, false);
476  }
477 
478  /* Fill spool using either serial or parallel heap scan */
479  if (!buildstate->btleader)
480  reltuples = table_index_build_scan(heap, index, indexInfo, true, true,
481  _bt_build_callback, (void *) buildstate,
482  NULL);
483  else
484  reltuples = _bt_parallel_heapscan(buildstate,
485  &indexInfo->ii_BrokenHotChain);
486 
487  /*
488  * Set the progress target for the next phase. Reset the block number
489  * values set by table_index_build_scan
490  */
491  {
492  const int index[] = {
496  };
497  const int64 val[] = {
498  buildstate->indtuples,
499  0, 0
500  };
501 
502  pgstat_progress_update_multi_param(3, index, val);
503  }
504 
505  /* okay, all heap tuples are spooled */
506  if (buildstate->spool2 && !buildstate->havedead)
507  {
508  /* spool2 turns out to be unnecessary */
509  _bt_spooldestroy(buildstate->spool2);
510  buildstate->spool2 = NULL;
511  }
512 
513  return reltuples;
514 }
515 
516 /*
517  * clean up a spool structure and its substructures.
518  */
519 static void
521 {
522  tuplesort_end(btspool->sortstate);
523  pfree(btspool);
524 }
525 
526 /*
527  * spool an index entry into the sort file.
528  */
529 static void
530 _bt_spool(BTSpool *btspool, ItemPointer self, Datum *values, bool *isnull)
531 {
532  tuplesort_putindextuplevalues(btspool->sortstate, btspool->index,
533  self, values, isnull);
534 }
535 
536 /*
537  * given a spool loaded by successive calls to _bt_spool,
538  * create an entire btree.
539  */
540 static void
541 _bt_leafbuild(BTSpool *btspool, BTSpool *btspool2)
542 {
543  BTWriteState wstate;
544 
545 #ifdef BTREE_BUILD_STATS
547  {
548  ShowUsage("BTREE BUILD (Spool) STATISTICS");
549  ResetUsage();
550  }
551 #endif /* BTREE_BUILD_STATS */
552 
556  if (btspool2)
557  {
560  tuplesort_performsort(btspool2->sortstate);
561  }
562 
563  wstate.heap = btspool->heap;
564  wstate.index = btspool->index;
565  wstate.inskey = _bt_mkscankey(wstate.index, NULL);
566 
567  /*
568  * We need to log index creation in WAL iff WAL archiving/streaming is
569  * enabled UNLESS the index isn't WAL-logged anyway.
570  */
571  wstate.btws_use_wal = XLogIsNeeded() && RelationNeedsWAL(wstate.index);
572 
573  /* reserve the metapage */
574  wstate.btws_pages_alloced = BTREE_METAPAGE + 1;
575  wstate.btws_pages_written = 0;
576  wstate.btws_zeropage = NULL; /* until needed */
577 
580  _bt_load(&wstate, btspool, btspool2);
581 }
582 
583 /*
584  * Per-tuple callback for table_index_build_scan
585  */
586 static void
588  ItemPointer tid,
589  Datum *values,
590  bool *isnull,
591  bool tupleIsAlive,
592  void *state)
593 {
594  BTBuildState *buildstate = (BTBuildState *) state;
595 
596  /*
597  * insert the index tuple into the appropriate spool file for subsequent
598  * processing
599  */
600  if (tupleIsAlive || buildstate->spool2 == NULL)
601  _bt_spool(buildstate->spool, tid, values, isnull);
602  else
603  {
604  /* dead tuples are put into spool2 */
605  buildstate->havedead = true;
606  _bt_spool(buildstate->spool2, tid, values, isnull);
607  }
608 
609  buildstate->indtuples += 1;
610 }
611 
612 /*
613  * allocate workspace for a new, clean btree page, not linked to any siblings.
614  */
615 static Page
617 {
618  Page page;
619  BTPageOpaque opaque;
620 
621  page = (Page) palloc(BLCKSZ);
622 
623  /* Zero the page and set up standard page header info */
624  _bt_pageinit(page, BLCKSZ);
625 
626  /* Initialize BT opaque state */
627  opaque = (BTPageOpaque) PageGetSpecialPointer(page);
628  opaque->btpo_prev = opaque->btpo_next = P_NONE;
629  opaque->btpo.level = level;
630  opaque->btpo_flags = (level > 0) ? 0 : BTP_LEAF;
631  opaque->btpo_cycleid = 0;
632 
633  /* Make the P_HIKEY line pointer appear allocated */
634  ((PageHeader) page)->pd_lower += sizeof(ItemIdData);
635 
636  return page;
637 }
638 
639 /*
640  * emit a completed btree page, and release the working storage.
641  */
642 static void
644 {
645  /* Ensure rd_smgr is open (could have been closed by relcache flush!) */
646  RelationOpenSmgr(wstate->index);
647 
648  /* XLOG stuff */
649  if (wstate->btws_use_wal)
650  {
651  /* We use the XLOG_FPI record type for this */
652  log_newpage(&wstate->index->rd_node, MAIN_FORKNUM, blkno, page, true);
653  }
654 
655  /*
656  * If we have to write pages nonsequentially, fill in the space with
657  * zeroes until we come back and overwrite. This is not logically
658  * necessary on standard Unix filesystems (unwritten space will read as
659  * zeroes anyway), but it should help to avoid fragmentation. The dummy
660  * pages aren't WAL-logged though.
661  */
662  while (blkno > wstate->btws_pages_written)
663  {
664  if (!wstate->btws_zeropage)
665  wstate->btws_zeropage = (Page) palloc0(BLCKSZ);
666  /* don't set checksum for all-zero page */
668  wstate->btws_pages_written++,
669  (char *) wstate->btws_zeropage,
670  true);
671  }
672 
673  PageSetChecksumInplace(page, blkno);
674 
675  /*
676  * Now write the page. There's no need for smgr to schedule an fsync for
677  * this write; we'll do it ourselves before ending the build.
678  */
679  if (blkno == wstate->btws_pages_written)
680  {
681  /* extending the file... */
682  smgrextend(wstate->index->rd_smgr, MAIN_FORKNUM, blkno,
683  (char *) page, true);
684  wstate->btws_pages_written++;
685  }
686  else
687  {
688  /* overwriting a block we zero-filled before */
689  smgrwrite(wstate->index->rd_smgr, MAIN_FORKNUM, blkno,
690  (char *) page, true);
691  }
692 
693  pfree(page);
694 }
695 
696 /*
697  * allocate and initialize a new BTPageState. the returned structure
698  * is suitable for immediate use by _bt_buildadd.
699  */
700 static BTPageState *
702 {
704 
705  /* create initial page for level */
706  state->btps_page = _bt_blnewpage(level);
707 
708  /* and assign it a page position */
709  state->btps_blkno = wstate->btws_pages_alloced++;
710 
711  state->btps_lowkey = NULL;
712  /* initialize lastoff so first item goes into P_FIRSTKEY */
713  state->btps_lastoff = P_HIKEY;
714  state->btps_level = level;
715  /* set "full" threshold based on level. See notes at head of file. */
716  if (level > 0)
717  state->btps_full = (BLCKSZ * (100 - BTREE_NONLEAF_FILLFACTOR) / 100);
718  else
721  /* no parent level, yet */
722  state->btps_next = NULL;
723 
724  return state;
725 }
726 
727 /*
728  * slide an array of ItemIds back one slot (from P_FIRSTKEY to
729  * P_HIKEY, overwriting P_HIKEY). we need to do this when we discover
730  * that we have built an ItemId array in what has turned out to be a
731  * P_RIGHTMOST page.
732  */
733 static void
735 {
736  OffsetNumber off;
737  OffsetNumber maxoff;
738  ItemId previi;
739  ItemId thisii;
740 
741  if (!PageIsEmpty(page))
742  {
743  maxoff = PageGetMaxOffsetNumber(page);
744  previi = PageGetItemId(page, P_HIKEY);
745  for (off = P_FIRSTKEY; off <= maxoff; off = OffsetNumberNext(off))
746  {
747  thisii = PageGetItemId(page, off);
748  *previi = *thisii;
749  previi = thisii;
750  }
751  ((PageHeader) page)->pd_lower -= sizeof(ItemIdData);
752  }
753 }
754 
755 /*
756  * Add an item to a page being built.
757  *
758  * The main difference between this routine and a bare PageAddItem call
759  * is that this code knows that the leftmost data item on a non-leaf
760  * btree page doesn't need to have a key. Therefore, it strips such
761  * items down to just the item header.
762  *
763  * This is almost like nbtinsert.c's _bt_pgaddtup(), but we can't use
764  * that because it assumes that P_RIGHTMOST() will return the correct
765  * answer for the page. Here, we don't know yet if the page will be
766  * rightmost. Offset P_FIRSTKEY is always the first data key.
767  */
768 static void
770  Size itemsize,
771  IndexTuple itup,
772  OffsetNumber itup_off)
773 {
775  IndexTupleData trunctuple;
776 
777  if (!P_ISLEAF(opaque) && itup_off == P_FIRSTKEY)
778  {
779  trunctuple = *itup;
780  trunctuple.t_info = sizeof(IndexTupleData);
781  /* Deliberately zero INDEX_ALT_TID_MASK bits */
782  BTreeTupleSetNAtts(&trunctuple, 0);
783  itup = &trunctuple;
784  itemsize = sizeof(IndexTupleData);
785  }
786 
787  if (PageAddItem(page, (Item) itup, itemsize, itup_off,
788  false, false) == InvalidOffsetNumber)
789  elog(ERROR, "failed to add item to the index page");
790 }
791 
792 /*----------
793  * Add an item to a disk page from the sort output.
794  *
795  * We must be careful to observe the page layout conventions of nbtsearch.c:
796  * - rightmost pages start data items at P_HIKEY instead of at P_FIRSTKEY.
797  * - on non-leaf pages, the key portion of the first item need not be
798  * stored, we should store only the link.
799  *
800  * A leaf page being built looks like:
801  *
802  * +----------------+---------------------------------+
803  * | PageHeaderData | linp0 linp1 linp2 ... |
804  * +-----------+----+---------------------------------+
805  * | ... linpN | |
806  * +-----------+--------------------------------------+
807  * | ^ last |
808  * | |
809  * +-------------+------------------------------------+
810  * | | itemN ... |
811  * +-------------+------------------+-----------------+
812  * | ... item3 item2 item1 | "special space" |
813  * +--------------------------------+-----------------+
814  *
815  * Contrast this with the diagram in bufpage.h; note the mismatch
816  * between linps and items. This is because we reserve linp0 as a
817  * placeholder for the pointer to the "high key" item; when we have
818  * filled up the page, we will set linp0 to point to itemN and clear
819  * linpN. On the other hand, if we find this is the last (rightmost)
820  * page, we leave the items alone and slide the linp array over. If
821  * the high key is to be truncated, offset 1 is deleted, and we insert
822  * the truncated high key at offset 1.
823  *
824  * 'last' pointer indicates the last offset added to the page.
825  *----------
826  */
827 static void
829 {
830  Page npage;
831  BlockNumber nblkno;
832  OffsetNumber last_off;
833  Size pgspc;
834  Size itupsz;
835  bool isleaf;
836 
837  /*
838  * This is a handy place to check for cancel interrupts during the btree
839  * load phase of index creation.
840  */
842 
843  npage = state->btps_page;
844  nblkno = state->btps_blkno;
845  last_off = state->btps_lastoff;
846 
847  pgspc = PageGetFreeSpace(npage);
848  itupsz = IndexTupleSize(itup);
849  itupsz = MAXALIGN(itupsz);
850  /* Leaf case has slightly different rules due to suffix truncation */
851  isleaf = (state->btps_level == 0);
852 
853  /*
854  * Check whether the new item can fit on a btree page on current level at
855  * all.
856  *
857  * Every newly built index will treat heap TID as part of the keyspace,
858  * which imposes the requirement that new high keys must occasionally have
859  * a heap TID appended within _bt_truncate(). That may leave a new pivot
860  * tuple one or two MAXALIGN() quantums larger than the original first
861  * right tuple it's derived from. v4 deals with the problem by decreasing
862  * the limit on the size of tuples inserted on the leaf level by the same
863  * small amount. Enforce the new v4+ limit on the leaf level, and the old
864  * limit on internal levels, since pivot tuples may need to make use of
865  * the reserved space. This should never fail on internal pages.
866  */
867  if (unlikely(itupsz > BTMaxItemSize(npage)))
868  _bt_check_third_page(wstate->index, wstate->heap, isleaf, npage,
869  itup);
870 
871  /*
872  * Check to see if current page will fit new item, with space left over to
873  * append a heap TID during suffix truncation when page is a leaf page.
874  *
875  * It is guaranteed that we can fit at least 2 non-pivot tuples plus a
876  * high key with heap TID when finishing off a leaf page, since we rely on
877  * _bt_check_third_page() rejecting oversized non-pivot tuples. On
878  * internal pages we can always fit 3 pivot tuples with larger internal
879  * page tuple limit (includes page high key).
880  *
881  * Most of the time, a page is only "full" in the sense that the soft
882  * fillfactor-wise limit has been exceeded. However, we must always leave
883  * at least two items plus a high key on each page before starting a new
884  * page. Disregard fillfactor and insert on "full" current page if we
885  * don't have the minimum number of items yet. (Note that we deliberately
886  * assume that suffix truncation neither enlarges nor shrinks new high key
887  * when applying soft limit.)
888  */
889  if (pgspc < itupsz + (isleaf ? MAXALIGN(sizeof(ItemPointerData)) : 0) ||
890  (pgspc < state->btps_full && last_off > P_FIRSTKEY))
891  {
892  /*
893  * Finish off the page and write it out.
894  */
895  Page opage = npage;
896  BlockNumber oblkno = nblkno;
897  ItemId ii;
898  ItemId hii;
899  IndexTuple oitup;
900 
901  /* Create new page of same level */
902  npage = _bt_blnewpage(state->btps_level);
903 
904  /* and assign it a page position */
905  nblkno = wstate->btws_pages_alloced++;
906 
907  /*
908  * We copy the last item on the page into the new page, and then
909  * rearrange the old page so that the 'last item' becomes its high key
910  * rather than a true data item. There had better be at least two
911  * items on the page already, else the page would be empty of useful
912  * data.
913  */
914  Assert(last_off > P_FIRSTKEY);
915  ii = PageGetItemId(opage, last_off);
916  oitup = (IndexTuple) PageGetItem(opage, ii);
917  _bt_sortaddtup(npage, ItemIdGetLength(ii), oitup, P_FIRSTKEY);
918 
919  /*
920  * Move 'last' into the high key position on opage. _bt_blnewpage()
921  * allocated empty space for a line pointer when opage was first
922  * created, so this is a matter of rearranging already-allocated space
923  * on page, and initializing high key line pointer. (Actually, leaf
924  * pages must also swap oitup with a truncated version of oitup, which
925  * is sometimes larger than oitup, though never by more than the space
926  * needed to append a heap TID.)
927  */
928  hii = PageGetItemId(opage, P_HIKEY);
929  *hii = *ii;
930  ItemIdSetUnused(ii); /* redundant */
931  ((PageHeader) opage)->pd_lower -= sizeof(ItemIdData);
932 
933  if (isleaf)
934  {
935  IndexTuple lastleft;
936  IndexTuple truncated;
937 
938  /*
939  * Truncate away any unneeded attributes from high key on leaf
940  * level. This is only done at the leaf level because downlinks
941  * in internal pages are either negative infinity items, or get
942  * their contents from copying from one level down. See also:
943  * _bt_split().
944  *
945  * We don't try to bias our choice of split point to make it more
946  * likely that _bt_truncate() can truncate away more attributes,
947  * whereas the split point used within _bt_split() is chosen much
948  * more delicately. Suffix truncation is mostly useful because it
949  * improves space utilization for workloads with random
950  * insertions. It doesn't seem worthwhile to add logic for
951  * choosing a split point here for a benefit that is bound to be
952  * much smaller.
953  *
954  * Overwrite the old item with new truncated high key directly.
955  * oitup is already located at the physical beginning of tuple
956  * space, so this should directly reuse the existing tuple space.
957  */
958  ii = PageGetItemId(opage, OffsetNumberPrev(last_off));
959  lastleft = (IndexTuple) PageGetItem(opage, ii);
960 
961  truncated = _bt_truncate(wstate->index, lastleft, oitup,
962  wstate->inskey);
963  if (!PageIndexTupleOverwrite(opage, P_HIKEY, (Item) truncated,
964  IndexTupleSize(truncated)))
965  elog(ERROR, "failed to add high key to the index page");
966  pfree(truncated);
967 
968  /* oitup should continue to point to the page's high key */
969  hii = PageGetItemId(opage, P_HIKEY);
970  oitup = (IndexTuple) PageGetItem(opage, hii);
971  }
972 
973  /*
974  * Link the old page into its parent, using its low key. If we don't
975  * have a parent, we have to create one; this adds a new btree level.
976  */
977  if (state->btps_next == NULL)
978  state->btps_next = _bt_pagestate(wstate, state->btps_level + 1);
979 
980  Assert((BTreeTupleGetNAtts(state->btps_lowkey, wstate->index) <=
982  BTreeTupleGetNAtts(state->btps_lowkey, wstate->index) > 0) ||
984  Assert(BTreeTupleGetNAtts(state->btps_lowkey, wstate->index) == 0 ||
986  BTreeInnerTupleSetDownLink(state->btps_lowkey, oblkno);
987  _bt_buildadd(wstate, state->btps_next, state->btps_lowkey);
988  pfree(state->btps_lowkey);
989 
990  /*
991  * Save a copy of the high key from the old page. It is also the low
992  * key for the new page.
993  */
994  state->btps_lowkey = CopyIndexTuple(oitup);
995 
996  /*
997  * Set the sibling links for both pages.
998  */
999  {
1000  BTPageOpaque oopaque = (BTPageOpaque) PageGetSpecialPointer(opage);
1001  BTPageOpaque nopaque = (BTPageOpaque) PageGetSpecialPointer(npage);
1002 
1003  oopaque->btpo_next = nblkno;
1004  nopaque->btpo_prev = oblkno;
1005  nopaque->btpo_next = P_NONE; /* redundant */
1006  }
1007 
1008  /*
1009  * Write out the old page. We never need to touch it again, so we can
1010  * free the opage workspace too.
1011  */
1012  _bt_blwritepage(wstate, opage, oblkno);
1013 
1014  /*
1015  * Reset last_off to point to new page
1016  */
1017  last_off = P_FIRSTKEY;
1018  }
1019 
1020  /*
1021  * By here, either original page is still the current page, or a new page
1022  * was created that became the current page. Either way, the current page
1023  * definitely has space for new item.
1024  *
1025  * If the new item is the first for its page, it must also be the first
1026  * item on its entire level. On later same-level pages, a low key for a
1027  * page will be copied from the prior page in the code above. Generate a
1028  * minus infinity low key here instead.
1029  */
1030  if (last_off == P_HIKEY)
1031  {
1032  Assert(state->btps_lowkey == NULL);
1033  state->btps_lowkey = palloc0(sizeof(IndexTupleData));
1034  state->btps_lowkey->t_info = sizeof(IndexTupleData);
1035  BTreeTupleSetNAtts(state->btps_lowkey, 0);
1036  }
1037 
1038  /*
1039  * Add the new item into the current page.
1040  */
1041  last_off = OffsetNumberNext(last_off);
1042  _bt_sortaddtup(npage, itupsz, itup, last_off);
1043 
1044  state->btps_page = npage;
1045  state->btps_blkno = nblkno;
1046  state->btps_lastoff = last_off;
1047 }
1048 
1049 /*
1050  * Finish writing out the completed btree.
1051  */
1052 static void
1054 {
1055  BTPageState *s;
1056  BlockNumber rootblkno = P_NONE;
1057  uint32 rootlevel = 0;
1058  Page metapage;
1059 
1060  /*
1061  * Each iteration of this loop completes one more level of the tree.
1062  */
1063  for (s = state; s != NULL; s = s->btps_next)
1064  {
1065  BlockNumber blkno;
1066  BTPageOpaque opaque;
1067 
1068  blkno = s->btps_blkno;
1070 
1071  /*
1072  * We have to link the last page on this level to somewhere.
1073  *
1074  * If we're at the top, it's the root, so attach it to the metapage.
1075  * Otherwise, add an entry for it to its parent using its low key.
1076  * This may cause the last page of the parent level to split, but
1077  * that's not a problem -- we haven't gotten to it yet.
1078  */
1079  if (s->btps_next == NULL)
1080  {
1081  opaque->btpo_flags |= BTP_ROOT;
1082  rootblkno = blkno;
1083  rootlevel = s->btps_level;
1084  }
1085  else
1086  {
1087  Assert((BTreeTupleGetNAtts(s->btps_lowkey, wstate->index) <=
1089  BTreeTupleGetNAtts(s->btps_lowkey, wstate->index) > 0) ||
1090  P_LEFTMOST(opaque));
1091  Assert(BTreeTupleGetNAtts(s->btps_lowkey, wstate->index) == 0 ||
1092  !P_LEFTMOST(opaque));
1094  _bt_buildadd(wstate, s->btps_next, s->btps_lowkey);
1095  pfree(s->btps_lowkey);
1096  s->btps_lowkey = NULL;
1097  }
1098 
1099  /*
1100  * This is the rightmost page, so the ItemId array needs to be slid
1101  * back one slot. Then we can dump out the page.
1102  */
1104  _bt_blwritepage(wstate, s->btps_page, s->btps_blkno);
1105  s->btps_page = NULL; /* writepage freed the workspace */
1106  }
1107 
1108  /*
1109  * As the last step in the process, construct the metapage and make it
1110  * point to the new root (unless we had no data at all, in which case it's
1111  * set to point to "P_NONE"). This changes the index to the "valid" state
1112  * by filling in a valid magic number in the metapage.
1113  */
1114  metapage = (Page) palloc(BLCKSZ);
1115  _bt_initmetapage(metapage, rootblkno, rootlevel);
1116  _bt_blwritepage(wstate, metapage, BTREE_METAPAGE);
1117 }
1118 
1119 /*
1120  * Read tuples in correct sort order from tuplesort, and load them into
1121  * btree leaves.
1122  */
1123 static void
1124 _bt_load(BTWriteState *wstate, BTSpool *btspool, BTSpool *btspool2)
1125 {
1126  BTPageState *state = NULL;
1127  bool merge = (btspool2 != NULL);
1128  IndexTuple itup,
1129  itup2 = NULL;
1130  bool load1;
1131  TupleDesc tupdes = RelationGetDescr(wstate->index);
1132  int i,
1134  SortSupport sortKeys;
1135  int64 tuples_done = 0;
1136 
1137  if (merge)
1138  {
1139  /*
1140  * Another BTSpool for dead tuples exists. Now we have to merge
1141  * btspool and btspool2.
1142  */
1143 
1144  /* the preparation of merge */
1145  itup = tuplesort_getindextuple(btspool->sortstate, true);
1146  itup2 = tuplesort_getindextuple(btspool2->sortstate, true);
1147 
1148  /* Prepare SortSupport data for each column */
1149  sortKeys = (SortSupport) palloc0(keysz * sizeof(SortSupportData));
1150 
1151  for (i = 0; i < keysz; i++)
1152  {
1153  SortSupport sortKey = sortKeys + i;
1154  ScanKey scanKey = wstate->inskey->scankeys + i;
1155  int16 strategy;
1156 
1157  sortKey->ssup_cxt = CurrentMemoryContext;
1158  sortKey->ssup_collation = scanKey->sk_collation;
1159  sortKey->ssup_nulls_first =
1160  (scanKey->sk_flags & SK_BT_NULLS_FIRST) != 0;
1161  sortKey->ssup_attno = scanKey->sk_attno;
1162  /* Abbreviation is not supported here */
1163  sortKey->abbreviate = false;
1164 
1165  AssertState(sortKey->ssup_attno != 0);
1166 
1167  strategy = (scanKey->sk_flags & SK_BT_DESC) != 0 ?
1169 
1170  PrepareSortSupportFromIndexRel(wstate->index, strategy, sortKey);
1171  }
1172 
1173  for (;;)
1174  {
1175  load1 = true; /* load BTSpool next ? */
1176  if (itup2 == NULL)
1177  {
1178  if (itup == NULL)
1179  break;
1180  }
1181  else if (itup != NULL)
1182  {
1183  int32 compare = 0;
1184 
1185  for (i = 1; i <= keysz; i++)
1186  {
1187  SortSupport entry;
1188  Datum attrDatum1,
1189  attrDatum2;
1190  bool isNull1,
1191  isNull2;
1192 
1193  entry = sortKeys + i - 1;
1194  attrDatum1 = index_getattr(itup, i, tupdes, &isNull1);
1195  attrDatum2 = index_getattr(itup2, i, tupdes, &isNull2);
1196 
1197  compare = ApplySortComparator(attrDatum1, isNull1,
1198  attrDatum2, isNull2,
1199  entry);
1200  if (compare > 0)
1201  {
1202  load1 = false;
1203  break;
1204  }
1205  else if (compare < 0)
1206  break;
1207  }
1208 
1209  /*
1210  * If key values are equal, we sort on ItemPointer. This is
1211  * required for btree indexes, since heap TID is treated as an
1212  * implicit last key attribute in order to ensure that all
1213  * keys in the index are physically unique.
1214  */
1215  if (compare == 0)
1216  {
1217  compare = ItemPointerCompare(&itup->t_tid, &itup2->t_tid);
1218  Assert(compare != 0);
1219  if (compare > 0)
1220  load1 = false;
1221  }
1222  }
1223  else
1224  load1 = false;
1225 
1226  /* When we see first tuple, create first index page */
1227  if (state == NULL)
1228  state = _bt_pagestate(wstate, 0);
1229 
1230  if (load1)
1231  {
1232  _bt_buildadd(wstate, state, itup);
1233  itup = tuplesort_getindextuple(btspool->sortstate, true);
1234  }
1235  else
1236  {
1237  _bt_buildadd(wstate, state, itup2);
1238  itup2 = tuplesort_getindextuple(btspool2->sortstate, true);
1239  }
1240 
1241  /* Report progress */
1243  ++tuples_done);
1244  }
1245  pfree(sortKeys);
1246  }
1247  else
1248  {
1249  /* merge is unnecessary */
1250  while ((itup = tuplesort_getindextuple(btspool->sortstate,
1251  true)) != NULL)
1252  {
1253  /* When we see first tuple, create first index page */
1254  if (state == NULL)
1255  state = _bt_pagestate(wstate, 0);
1256 
1257  _bt_buildadd(wstate, state, itup);
1258 
1259  /* Report progress */
1261  ++tuples_done);
1262  }
1263  }
1264 
1265  /* Close down final pages and write the metapage */
1266  _bt_uppershutdown(wstate, state);
1267 
1268  /*
1269  * If the index is WAL-logged, we must fsync it down to disk before it's
1270  * safe to commit the transaction. (For a non-WAL-logged index we don't
1271  * care since the index will be uninteresting after a crash anyway.)
1272  *
1273  * It's obvious that we must do this when not WAL-logging the build. It's
1274  * less obvious that we have to do it even if we did WAL-log the index
1275  * pages. The reason is that since we're building outside shared buffers,
1276  * a CHECKPOINT occurring during the build has no way to flush the
1277  * previously written data to disk (indeed it won't know the index even
1278  * exists). A crash later on would replay WAL from the checkpoint,
1279  * therefore it wouldn't replay our earlier WAL entries. If we do not
1280  * fsync those pages here, they might still not be on disk when the crash
1281  * occurs.
1282  */
1283  if (RelationNeedsWAL(wstate->index))
1284  {
1285  RelationOpenSmgr(wstate->index);
1287  }
1288 }
1289 
1290 /*
1291  * Create parallel context, and launch workers for leader.
1292  *
1293  * buildstate argument should be initialized (with the exception of the
1294  * tuplesort state in spools, which may later be created based on shared
1295  * state initially set up here).
1296  *
1297  * isconcurrent indicates if operation is CREATE INDEX CONCURRENTLY.
1298  *
1299  * request is the target number of parallel worker processes to launch.
1300  *
1301  * Sets buildstate's BTLeader, which caller must use to shut down parallel
1302  * mode by passing it to _bt_end_parallel() at the very end of its index
1303  * build. If not even a single worker process can be launched, this is
1304  * never set, and caller should proceed with a serial index build.
1305  */
1306 static void
1307 _bt_begin_parallel(BTBuildState *buildstate, bool isconcurrent, int request)
1308 {
1309  ParallelContext *pcxt;
1310  int scantuplesortstates;
1311  Snapshot snapshot;
1312  Size estbtshared;
1313  Size estsort;
1314  BTShared *btshared;
1315  Sharedsort *sharedsort;
1316  Sharedsort *sharedsort2;
1317  BTSpool *btspool = buildstate->spool;
1318  BTLeader *btleader = (BTLeader *) palloc0(sizeof(BTLeader));
1319  bool leaderparticipates = true;
1320  char *sharedquery;
1321  int querylen;
1322 
1323 #ifdef DISABLE_LEADER_PARTICIPATION
1324  leaderparticipates = false;
1325 #endif
1326 
1327  /*
1328  * Enter parallel mode, and create context for parallel build of btree
1329  * index
1330  */
1332  Assert(request > 0);
1333  pcxt = CreateParallelContext("postgres", "_bt_parallel_build_main",
1334  request);
1335  scantuplesortstates = leaderparticipates ? request + 1 : request;
1336 
1337  /*
1338  * Prepare for scan of the base relation. In a normal index build, we use
1339  * SnapshotAny because we must retrieve all tuples and do our own time
1340  * qual checks (because we have to index RECENTLY_DEAD tuples). In a
1341  * concurrent build, we take a regular MVCC snapshot and index whatever's
1342  * live according to that.
1343  */
1344  if (!isconcurrent)
1345  snapshot = SnapshotAny;
1346  else
1348 
1349  /*
1350  * Estimate size for our own PARALLEL_KEY_BTREE_SHARED workspace, and
1351  * PARALLEL_KEY_TUPLESORT tuplesort workspace
1352  */
1353  estbtshared = _bt_parallel_estimate_shared(btspool->heap, snapshot);
1354  shm_toc_estimate_chunk(&pcxt->estimator, estbtshared);
1355  estsort = tuplesort_estimate_shared(scantuplesortstates);
1356  shm_toc_estimate_chunk(&pcxt->estimator, estsort);
1357 
1358  /*
1359  * Unique case requires a second spool, and so we may have to account for
1360  * another shared workspace for that -- PARALLEL_KEY_TUPLESORT_SPOOL2
1361  */
1362  if (!btspool->isunique)
1363  shm_toc_estimate_keys(&pcxt->estimator, 2);
1364  else
1365  {
1366  shm_toc_estimate_chunk(&pcxt->estimator, estsort);
1367  shm_toc_estimate_keys(&pcxt->estimator, 3);
1368  }
1369 
1370  /* Finally, estimate PARALLEL_KEY_QUERY_TEXT space */
1371  querylen = strlen(debug_query_string);
1372  shm_toc_estimate_chunk(&pcxt->estimator, querylen + 1);
1373  shm_toc_estimate_keys(&pcxt->estimator, 1);
1374 
1375  /* Everyone's had a chance to ask for space, so now create the DSM */
1376  InitializeParallelDSM(pcxt);
1377 
1378  /* Store shared build state, for which we reserved space */
1379  btshared = (BTShared *) shm_toc_allocate(pcxt->toc, estbtshared);
1380  /* Initialize immutable state */
1381  btshared->heaprelid = RelationGetRelid(btspool->heap);
1382  btshared->indexrelid = RelationGetRelid(btspool->index);
1383  btshared->isunique = btspool->isunique;
1384  btshared->isconcurrent = isconcurrent;
1385  btshared->scantuplesortstates = scantuplesortstates;
1387  SpinLockInit(&btshared->mutex);
1388  /* Initialize mutable state */
1389  btshared->nparticipantsdone = 0;
1390  btshared->reltuples = 0.0;
1391  btshared->havedead = false;
1392  btshared->indtuples = 0.0;
1393  btshared->brokenhotchain = false;
1396  snapshot);
1397 
1398  /*
1399  * Store shared tuplesort-private state, for which we reserved space.
1400  * Then, initialize opaque state using tuplesort routine.
1401  */
1402  sharedsort = (Sharedsort *) shm_toc_allocate(pcxt->toc, estsort);
1403  tuplesort_initialize_shared(sharedsort, scantuplesortstates,
1404  pcxt->seg);
1405 
1406  shm_toc_insert(pcxt->toc, PARALLEL_KEY_BTREE_SHARED, btshared);
1407  shm_toc_insert(pcxt->toc, PARALLEL_KEY_TUPLESORT, sharedsort);
1408 
1409  /* Unique case requires a second spool, and associated shared state */
1410  if (!btspool->isunique)
1411  sharedsort2 = NULL;
1412  else
1413  {
1414  /*
1415  * Store additional shared tuplesort-private state, for which we
1416  * reserved space. Then, initialize opaque state using tuplesort
1417  * routine.
1418  */
1419  sharedsort2 = (Sharedsort *) shm_toc_allocate(pcxt->toc, estsort);
1420  tuplesort_initialize_shared(sharedsort2, scantuplesortstates,
1421  pcxt->seg);
1422 
1423  shm_toc_insert(pcxt->toc, PARALLEL_KEY_TUPLESORT_SPOOL2, sharedsort2);
1424  }
1425 
1426  /* Store query string for workers */
1427  sharedquery = (char *) shm_toc_allocate(pcxt->toc, querylen + 1);
1428  memcpy(sharedquery, debug_query_string, querylen + 1);
1429  shm_toc_insert(pcxt->toc, PARALLEL_KEY_QUERY_TEXT, sharedquery);
1430 
1431  /* Launch workers, saving status for leader/caller */
1432  LaunchParallelWorkers(pcxt);
1433  btleader->pcxt = pcxt;
1434  btleader->nparticipanttuplesorts = pcxt->nworkers_launched;
1435  if (leaderparticipates)
1436  btleader->nparticipanttuplesorts++;
1437  btleader->btshared = btshared;
1438  btleader->sharedsort = sharedsort;
1439  btleader->sharedsort2 = sharedsort2;
1440  btleader->snapshot = snapshot;
1441 
1442  /* If no workers were successfully launched, back out (do serial build) */
1443  if (pcxt->nworkers_launched == 0)
1444  {
1445  _bt_end_parallel(btleader);
1446  return;
1447  }
1448 
1449  /* Save leader state now that it's clear build will be parallel */
1450  buildstate->btleader = btleader;
1451 
1452  /* Join heap scan ourselves */
1453  if (leaderparticipates)
1455 
1456  /*
1457  * Caller needs to wait for all launched workers when we return. Make
1458  * sure that the failure-to-start case will not hang forever.
1459  */
1461 }
1462 
1463 /*
1464  * Shut down workers, destroy parallel context, and end parallel mode.
1465  */
1466 static void
1468 {
1469  /* Shutdown worker processes */
1471  /* Free last reference to MVCC snapshot, if one was used */
1472  if (IsMVCCSnapshot(btleader->snapshot))
1473  UnregisterSnapshot(btleader->snapshot);
1474  DestroyParallelContext(btleader->pcxt);
1475  ExitParallelMode();
1476 }
1477 
1478 /*
1479  * Returns size of shared memory required to store state for a parallel
1480  * btree index build based on the snapshot its parallel scan will use.
1481  */
1482 static Size
1484 {
1485  /* c.f. shm_toc_allocate as to why BUFFERALIGN is used */
1486  return add_size(BUFFERALIGN(sizeof(BTShared)),
1487  table_parallelscan_estimate(heap, snapshot));
1488 }
1489 
1490 /*
1491  * Within leader, wait for end of heap scan.
1492  *
1493  * When called, parallel heap scan started by _bt_begin_parallel() will
1494  * already be underway within worker processes (when leader participates
1495  * as a worker, we should end up here just as workers are finishing).
1496  *
1497  * Fills in fields needed for ambuild statistics, and lets caller set
1498  * field indicating that some worker encountered a broken HOT chain.
1499  *
1500  * Returns the total number of heap tuples scanned.
1501  */
1502 static double
1503 _bt_parallel_heapscan(BTBuildState *buildstate, bool *brokenhotchain)
1504 {
1505  BTShared *btshared = buildstate->btleader->btshared;
1506  int nparticipanttuplesorts;
1507  double reltuples;
1508 
1509  nparticipanttuplesorts = buildstate->btleader->nparticipanttuplesorts;
1510  for (;;)
1511  {
1512  SpinLockAcquire(&btshared->mutex);
1513  if (btshared->nparticipantsdone == nparticipanttuplesorts)
1514  {
1515  buildstate->havedead = btshared->havedead;
1516  buildstate->indtuples = btshared->indtuples;
1517  *brokenhotchain = btshared->brokenhotchain;
1518  reltuples = btshared->reltuples;
1519  SpinLockRelease(&btshared->mutex);
1520  break;
1521  }
1522  SpinLockRelease(&btshared->mutex);
1523 
1526  }
1527 
1529 
1530  return reltuples;
1531 }
1532 
1533 /*
1534  * Within leader, participate as a parallel worker.
1535  */
1536 static void
1538 {
1539  BTLeader *btleader = buildstate->btleader;
1540  BTSpool *leaderworker;
1541  BTSpool *leaderworker2;
1542  int sortmem;
1543 
1544  /* Allocate memory and initialize private spool */
1545  leaderworker = (BTSpool *) palloc0(sizeof(BTSpool));
1546  leaderworker->heap = buildstate->spool->heap;
1547  leaderworker->index = buildstate->spool->index;
1548  leaderworker->isunique = buildstate->spool->isunique;
1549 
1550  /* Initialize second spool, if required */
1551  if (!btleader->btshared->isunique)
1552  leaderworker2 = NULL;
1553  else
1554  {
1555  /* Allocate memory for worker's own private secondary spool */
1556  leaderworker2 = (BTSpool *) palloc0(sizeof(BTSpool));
1557 
1558  /* Initialize worker's own secondary spool */
1559  leaderworker2->heap = leaderworker->heap;
1560  leaderworker2->index = leaderworker->index;
1561  leaderworker2->isunique = false;
1562  }
1563 
1564  /*
1565  * Might as well use reliable figure when doling out maintenance_work_mem
1566  * (when requested number of workers were not launched, this will be
1567  * somewhat higher than it is for other workers).
1568  */
1569  sortmem = maintenance_work_mem / btleader->nparticipanttuplesorts;
1570 
1571  /* Perform work common to all participants */
1572  _bt_parallel_scan_and_sort(leaderworker, leaderworker2, btleader->btshared,
1573  btleader->sharedsort, btleader->sharedsort2,
1574  sortmem, true);
1575 
1576 #ifdef BTREE_BUILD_STATS
1578  {
1579  ShowUsage("BTREE BUILD (Leader Partial Spool) STATISTICS");
1580  ResetUsage();
1581  }
1582 #endif /* BTREE_BUILD_STATS */
1583 }
1584 
1585 /*
1586  * Perform work within a launched parallel process.
1587  */
1588 void
1590 {
1591  char *sharedquery;
1592  BTSpool *btspool;
1593  BTSpool *btspool2;
1594  BTShared *btshared;
1595  Sharedsort *sharedsort;
1596  Sharedsort *sharedsort2;
1597  Relation heapRel;
1598  Relation indexRel;
1599  LOCKMODE heapLockmode;
1600  LOCKMODE indexLockmode;
1601  int sortmem;
1602 
1603 #ifdef BTREE_BUILD_STATS
1605  ResetUsage();
1606 #endif /* BTREE_BUILD_STATS */
1607 
1608  /* Set debug_query_string for individual workers first */
1609  sharedquery = shm_toc_lookup(toc, PARALLEL_KEY_QUERY_TEXT, false);
1610  debug_query_string = sharedquery;
1611 
1612  /* Report the query string from leader */
1614 
1615  /* Look up nbtree shared state */
1616  btshared = shm_toc_lookup(toc, PARALLEL_KEY_BTREE_SHARED, false);
1617 
1618  /* Open relations using lock modes known to be obtained by index.c */
1619  if (!btshared->isconcurrent)
1620  {
1621  heapLockmode = ShareLock;
1622  indexLockmode = AccessExclusiveLock;
1623  }
1624  else
1625  {
1626  heapLockmode = ShareUpdateExclusiveLock;
1627  indexLockmode = RowExclusiveLock;
1628  }
1629 
1630  /* Open relations within worker */
1631  heapRel = table_open(btshared->heaprelid, heapLockmode);
1632  indexRel = index_open(btshared->indexrelid, indexLockmode);
1633 
1634  /* Initialize worker's own spool */
1635  btspool = (BTSpool *) palloc0(sizeof(BTSpool));
1636  btspool->heap = heapRel;
1637  btspool->index = indexRel;
1638  btspool->isunique = btshared->isunique;
1639 
1640  /* Look up shared state private to tuplesort.c */
1641  sharedsort = shm_toc_lookup(toc, PARALLEL_KEY_TUPLESORT, false);
1642  tuplesort_attach_shared(sharedsort, seg);
1643  if (!btshared->isunique)
1644  {
1645  btspool2 = NULL;
1646  sharedsort2 = NULL;
1647  }
1648  else
1649  {
1650  /* Allocate memory for worker's own private secondary spool */
1651  btspool2 = (BTSpool *) palloc0(sizeof(BTSpool));
1652 
1653  /* Initialize worker's own secondary spool */
1654  btspool2->heap = btspool->heap;
1655  btspool2->index = btspool->index;
1656  btspool2->isunique = false;
1657  /* Look up shared state private to tuplesort.c */
1658  sharedsort2 = shm_toc_lookup(toc, PARALLEL_KEY_TUPLESORT_SPOOL2, false);
1659  tuplesort_attach_shared(sharedsort2, seg);
1660  }
1661 
1662  /* Perform sorting of spool, and possibly a spool2 */
1663  sortmem = maintenance_work_mem / btshared->scantuplesortstates;
1664  _bt_parallel_scan_and_sort(btspool, btspool2, btshared, sharedsort,
1665  sharedsort2, sortmem, false);
1666 
1667 #ifdef BTREE_BUILD_STATS
1669  {
1670  ShowUsage("BTREE BUILD (Worker Partial Spool) STATISTICS");
1671  ResetUsage();
1672  }
1673 #endif /* BTREE_BUILD_STATS */
1674 
1675  index_close(indexRel, indexLockmode);
1676  table_close(heapRel, heapLockmode);
1677 }
1678 
1679 /*
1680  * Perform a worker's portion of a parallel sort.
1681  *
1682  * This generates a tuplesort for passed btspool, and a second tuplesort
1683  * state if a second btspool is need (i.e. for unique index builds). All
1684  * other spool fields should already be set when this is called.
1685  *
1686  * sortmem is the amount of working memory to use within each worker,
1687  * expressed in KBs.
1688  *
1689  * When this returns, workers are done, and need only release resources.
1690  */
1691 static void
1693  BTShared *btshared, Sharedsort *sharedsort,
1694  Sharedsort *sharedsort2, int sortmem, bool progress)
1695 {
1696  SortCoordinate coordinate;
1697  BTBuildState buildstate;
1698  TableScanDesc scan;
1699  double reltuples;
1700  IndexInfo *indexInfo;
1701 
1702  /* Initialize local tuplesort coordination state */
1703  coordinate = palloc0(sizeof(SortCoordinateData));
1704  coordinate->isWorker = true;
1705  coordinate->nParticipants = -1;
1706  coordinate->sharedsort = sharedsort;
1707 
1708  /* Begin "partial" tuplesort */
1709  btspool->sortstate = tuplesort_begin_index_btree(btspool->heap,
1710  btspool->index,
1711  btspool->isunique,
1712  sortmem, coordinate,
1713  false);
1714 
1715  /*
1716  * Just as with serial case, there may be a second spool. If so, a
1717  * second, dedicated spool2 partial tuplesort is required.
1718  */
1719  if (btspool2)
1720  {
1721  SortCoordinate coordinate2;
1722 
1723  /*
1724  * We expect that the second one (for dead tuples) won't get very
1725  * full, so we give it only work_mem (unless sortmem is less for
1726  * worker). Worker processes are generally permitted to allocate
1727  * work_mem independently.
1728  */
1729  coordinate2 = palloc0(sizeof(SortCoordinateData));
1730  coordinate2->isWorker = true;
1731  coordinate2->nParticipants = -1;
1732  coordinate2->sharedsort = sharedsort2;
1733  btspool2->sortstate =
1734  tuplesort_begin_index_btree(btspool->heap, btspool->index, false,
1735  Min(sortmem, work_mem), coordinate2,
1736  false);
1737  }
1738 
1739  /* Fill in buildstate for _bt_build_callback() */
1740  buildstate.isunique = btshared->isunique;
1741  buildstate.havedead = false;
1742  buildstate.heap = btspool->heap;
1743  buildstate.spool = btspool;
1744  buildstate.spool2 = btspool2;
1745  buildstate.indtuples = 0;
1746  buildstate.btleader = NULL;
1747 
1748  /* Join parallel scan */
1749  indexInfo = BuildIndexInfo(btspool->index);
1750  indexInfo->ii_Concurrent = btshared->isconcurrent;
1751  scan = table_beginscan_parallel(btspool->heap,
1752  ParallelTableScanFromBTShared(btshared));
1753  reltuples = table_index_build_scan(btspool->heap, btspool->index, indexInfo,
1754  true, progress, _bt_build_callback,
1755  (void *) &buildstate, scan);
1756 
1757  /*
1758  * Execute this worker's part of the sort.
1759  *
1760  * Unlike leader and serial cases, we cannot avoid calling
1761  * tuplesort_performsort() for spool2 if it ends up containing no dead
1762  * tuples (this is disallowed for workers by tuplesort).
1763  */
1764  tuplesort_performsort(btspool->sortstate);
1765  if (btspool2)
1766  tuplesort_performsort(btspool2->sortstate);
1767 
1768  /*
1769  * Done. Record ambuild statistics, and whether we encountered a broken
1770  * HOT chain.
1771  */
1772  SpinLockAcquire(&btshared->mutex);
1773  btshared->nparticipantsdone++;
1774  btshared->reltuples += reltuples;
1775  if (buildstate.havedead)
1776  btshared->havedead = true;
1777  btshared->indtuples += buildstate.indtuples;
1778  if (indexInfo->ii_BrokenHotChain)
1779  btshared->brokenhotchain = true;
1780  SpinLockRelease(&btshared->mutex);
1781 
1782  /* Notify leader */
1784 
1785  /* We can end tuplesorts immediately */
1786  tuplesort_end(btspool->sortstate);
1787  if (btspool2)
1788  tuplesort_end(btspool2->sortstate);
1789 }
struct SortSupportData * SortSupport
Definition: sortsupport.h:58
IndexTuple tuplesort_getindextuple(Tuplesortstate *state, bool forward)
Definition: tuplesort.c:2216
static void _bt_begin_parallel(BTBuildState *buildstate, bool isconcurrent, int request)
Definition: nbtsort.c:1307
int32 ItemPointerCompare(ItemPointer arg1, ItemPointer arg2)
Definition: itemptr.c:52
signed short int16
Definition: c.h:346
bool ssup_nulls_first
Definition: sortsupport.h:75
int slock_t
Definition: s_lock.h:934
#define BTP_ROOT
Definition: nbtree.h:72
Sharedsort * sharedsort2
Definition: nbtsort.c:204
void tuplesort_performsort(Tuplesortstate *state)
Definition: tuplesort.c:1791
BlockNumber btpo_next
Definition: nbtree.h:58
#define PROGRESS_BTREE_PHASE_INDEXBUILD_TABLESCAN
Definition: nbtree.h:688
#define PageIsEmpty(page)
Definition: bufpage.h:222
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
int scantuplesortstates
Definition: nbtsort.c:120
#define BTGreaterStrategyNumber
Definition: stratnum.h:33
struct BTWriteState BTWriteState
#define PARALLEL_KEY_TUPLESORT
Definition: nbtsort.c:81
Relation heap
Definition: nbtsort.c:218
#define AssertState(condition)
Definition: c.h:736
Page btws_zeropage
Definition: nbtsort.c:262
ParallelContext * CreateParallelContext(const char *library_name, const char *function_name, int nworkers)
Definition: parallel.c:158
BTShared * btshared
Definition: nbtsort.c:202
int nparticipantsdone
Definition: nbtsort.c:154
static void _bt_load(BTWriteState *wstate, BTSpool *btspool, BTSpool *btspool2)
Definition: nbtsort.c:1124
Snapshot RegisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:865
#define RelationGetDescr(relation)
Definition: rel.h:449
int LOCKMODE
Definition: lockdefs.h:26
BTScanInsert _bt_mkscankey(Relation rel, IndexTuple itup)
Definition: nbtutils.c:86
Oid indexrelid
Definition: nbtsort.c:117
void pgstat_report_activity(BackendState state, const char *cmd_str)
Definition: pgstat.c:3119
#define PROGRESS_BTREE_PHASE_PERFORMSORT_1
Definition: nbtree.h:689
void ShowUsage(const char *title)
Definition: postgres.c:4580
dsm_segment * seg
Definition: parallel.h:42
BlockNumber btws_pages_alloced
Definition: nbtsort.c:260
struct SMgrRelationData * rd_smgr
Definition: rel.h:56
void pgstat_progress_update_param(int index, int64 val)
Definition: pgstat.c:3218
Sharedsort * sharedsort
Definition: nbtsort.c:203
shm_toc_estimator estimator
Definition: parallel.h:41
#define SpinLockInit(lock)
Definition: spin.h:60
#define BTP_LEAF
Definition: nbtree.h:71
#define XLogIsNeeded()
Definition: xlog.h:181
ItemPointerData t_tid
Definition: itup.h:37
void _bt_parallel_build_main(dsm_segment *seg, shm_toc *toc)
Definition: nbtsort.c:1589
#define Min(x, y)
Definition: c.h:905
union BTPageOpaqueData::@46 btpo
bool havedead
Definition: nbtsort.c:217
Snapshot snapshot
Definition: nbtsort.c:205
Pointer Item
Definition: item.h:17
#define P_NONE
Definition: nbtree.h:181
Sharedsort * sharedsort
Definition: tuplesort.h:55
bool isunique
Definition: nbtsort.c:118
#define PageAddItem(page, item, size, offsetNumber, overwrite, is_heap)
Definition: bufpage.h:416
#define ParallelTableScanFromBTShared(shared)
Definition: nbtsort.c:173
bool isconcurrent
Definition: nbtsort.c:119
#define PROGRESS_CREATEIDX_TUPLES_TOTAL
Definition: progress.h:67
uint32 BlockNumber
Definition: block.h:31
static void _bt_end_parallel(BTLeader *btleader)
Definition: nbtsort.c:1467
Tuplesortstate * sortstate
Definition: nbtsort.c:98
IndexInfo * BuildIndexInfo(Relation index)
Definition: index.c:2285
static void _bt_leafbuild(BTSpool *btspool, BTSpool *btspool2)
Definition: nbtsort.c:541
BlockNumber btps_blkno
Definition: nbtsort.c:243
void tuplesort_initialize_shared(Sharedsort *shared, int nWorkers, dsm_segment *seg)
Definition: tuplesort.c:4391
unsigned int Oid
Definition: postgres_ext.h:31
#define shm_toc_estimate_chunk(e, sz)
Definition: shm_toc.h:51
#define BTreeTupleGetNAtts(itup, rel)
Definition: nbtree.h:327
bool btws_use_wal
Definition: nbtsort.c:259
BTSpool * spool
Definition: nbtsort.c:219
static void _bt_blwritepage(BTWriteState *wstate, Page page, BlockNumber blkno)
Definition: nbtsort.c:643
static pairingheap_node * merge(pairingheap *heap, pairingheap_node *a, pairingheap_node *b)
Definition: pairingheap.c:79
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:306
#define PageGetMaxOffsetNumber(page)
Definition: bufpage.h:357
#define BTreeTupleSetNAtts(itup, n)
Definition: nbtree.h:336
ParallelContext * pcxt
Definition: nbtsort.c:182
BTPageOpaqueData * BTPageOpaque
Definition: nbtree.h:68
Size PageGetFreeSpace(Page page)
Definition: bufpage.c:581
Relation heap
Definition: nbtsort.c:99
signed int int32
Definition: c.h:347
struct BTBuildState BTBuildState
uint16 OffsetNumber
Definition: off.h:24
Definition: type.h:89
#define RelationOpenSmgr(relation)
Definition: rel.h:480
IndexTuple _bt_truncate(Relation rel, IndexTuple lastleft, IndexTuple firstright, BTScanInsert itup_key)
Definition: nbtutils.c:2098
void ResetUsage(void)
Definition: postgres.c:4573
void WaitForParallelWorkersToFinish(ParallelContext *pcxt)
Definition: parallel.c:716
#define SpinLockAcquire(lock)
Definition: spin.h:62
void ConditionVariableInit(ConditionVariable *cv)
void DestroyParallelContext(ParallelContext *pcxt)
Definition: parallel.c:870
Page btps_page
Definition: nbtsort.c:242
struct BTSpool BTSpool
#define ItemIdGetLength(itemId)
Definition: itemid.h:59
void pfree(void *pointer)
Definition: mcxt.c:1056
void ConditionVariableCancelSleep(void)
#define BTREE_NONLEAF_FILLFACTOR
Definition: nbtree.h:170
static int compare(const void *arg1, const void *arg2)
Definition: geqo_pool.c:145
Size btps_full
Definition: nbtsort.c:247
#define ERROR
Definition: elog.h:43
static double _bt_parallel_heapscan(BTBuildState *buildstate, bool *brokenhotchain)
Definition: nbtsort.c:1503
IndexBuildResult * btbuild(Relation heap, Relation index, IndexInfo *indexInfo)
Definition: nbtsort.c:301
static double table_index_build_scan(Relation table_rel, Relation index_rel, struct IndexInfo *index_info, bool allow_sync, bool progress, IndexBuildCallback callback, void *callback_state, TableScanDesc scan)
Definition: tableam.h:1499
bool isunique
Definition: nbtsort.c:101
MemoryContext ssup_cxt
Definition: sortsupport.h:66
BTCycleId btpo_cycleid
Definition: nbtree.h:65
void ConditionVariableSignal(ConditionVariable *cv)
#define PROGRESS_BTREE_PHASE_PERFORMSORT_2
Definition: nbtree.h:690
static void _bt_buildadd(BTWriteState *wstate, BTPageState *state, IndexTuple itup)
Definition: nbtsort.c:828
void ExitParallelMode(void)
Definition: xact.c:976
Oid heaprelid
Definition: nbtsort.c:116
void _bt_initmetapage(Page page, BlockNumber rootbknum, uint32 level)
Definition: nbtpage.c:50
bool PageIndexTupleOverwrite(Page page, OffsetNumber offnum, Item newtup, Size newsize)
Definition: bufpage.c:1065
BlockNumber btpo_prev
Definition: nbtree.h:57
IndexTuple CopyIndexTuple(IndexTuple source)
Definition: indextuple.c:509
OffsetNumber btps_lastoff
Definition: nbtsort.c:245
void smgrwrite(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum, char *buffer, bool skipFsync)
Definition: smgr.c:530
BTSpool * spool2
Definition: nbtsort.c:225
#define RowExclusiveLock
Definition: lockdefs.h:38
IndexTupleData * IndexTuple
Definition: itup.h:53
struct BTShared BTShared
#define PARALLEL_KEY_QUERY_TEXT
Definition: nbtsort.c:83
#define P_FIRSTKEY
Definition: nbtree.h:218
double indtuples
Definition: nbtsort.c:226
bool isunique
Definition: nbtsort.c:216
#define RelationGetRelationName(relation)
Definition: rel.h:457
#define P_LEFTMOST(opaque)
Definition: nbtree.h:187
#define PARALLEL_KEY_TUPLESORT_SPOOL2
Definition: nbtsort.c:82
bool ii_BrokenHotChain
Definition: execnodes.h:173
unsigned int uint32
Definition: c.h:359
struct ItemIdData ItemIdData
MemoryContext CurrentMemoryContext
Definition: mcxt.c:38
#define IndexRelationGetNumberOfKeyAttributes(relation)
Definition: rel.h:442
int nworkers_launched
Definition: parallel.h:37
void PrepareSortSupportFromIndexRel(Relation indexRel, int16 strategy, SortSupport ssup)
Definition: sortsupport.c:161
bool brokenhotchain
Definition: nbtsort.c:158
void LaunchParallelWorkers(ParallelContext *pcxt)
Definition: parallel.c:493
#define BTREE_DEFAULT_FILLFACTOR
Definition: nbtree.h:169
#define BTREE_METAPAGE
Definition: nbtree.h:131
#define RelationGetTargetPageFreeSpace(relation, defaultff)
Definition: rel.h:307
void UnregisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:907
Relation index
Definition: nbtsort.c:100
Relation index
Definition: nbtsort.c:257
TableScanDesc table_beginscan_parallel(Relation relation, ParallelTableScanDesc parallel_scan)
Definition: tableam.c:161
const char * debug_query_string
Definition: postgres.c:86
void InitializeParallelDSM(ParallelContext *pcxt)
Definition: parallel.c:195
#define PageGetItemId(page, offsetNumber)
Definition: bufpage.h:235
#define SK_BT_NULLS_FIRST
Definition: nbtree.h:681
int progress
Definition: pgbench.c:234
uint32 level
Definition: nbtree.h:61
#define SpinLockRelease(lock)
Definition: spin.h:64
struct BTLeader BTLeader
BlockNumber btws_pages_written
Definition: nbtsort.c:261
void * palloc0(Size size)
Definition: mcxt.c:980
struct SortCoordinateData * SortCoordinate
Definition: tuplesort.h:58
#define PROGRESS_SCAN_BLOCKS_DONE
Definition: progress.h:103
uint32 btps_level
Definition: nbtsort.c:246
uintptr_t Datum
Definition: postgres.h:367
struct IndexTupleData IndexTupleData
static BTPageState * _bt_pagestate(BTWriteState *wstate, uint32 level)
Definition: nbtsort.c:701
static void _bt_build_callback(Relation index, ItemPointer tid, Datum *values, bool *isnull, bool tupleIsAlive, void *state)
Definition: nbtsort.c:587
Size add_size(Size s1, Size s2)
Definition: shmem.c:475
static double _bt_spools_heapscan(Relation heap, Relation index, BTBuildState *buildstate, IndexInfo *indexInfo)
Definition: nbtsort.c:370
bool log_btree_build_stats
Definition: guc.c:498
BTLeader * btleader
Definition: nbtsort.c:233
int work_mem
Definition: globals.c:121
double reltuples
Definition: nbtsort.c:155
AttrNumber ssup_attno
Definition: sortsupport.h:81
#define RelationGetNumberOfBlocks(reln)
Definition: bufmgr.h:198
double indtuples
Definition: nbtsort.c:157
static void _bt_parallel_scan_and_sort(BTSpool *btspool, BTSpool *btspool2, BTShared *btshared, Sharedsort *sharedsort, Sharedsort *sharedsort2, int sortmem, bool progress)
Definition: nbtsort.c:1692
#define IsMVCCSnapshot(snapshot)
Definition: snapmgr.h:97
struct BTPageState * btps_next
Definition: nbtsort.c:248
BTScanInsert inskey
Definition: nbtsort.c:258
#define InvalidOffsetNumber
Definition: off.h:26
IndexTuple btps_lowkey
Definition: nbtsort.c:244
void tuplesort_putindextuplevalues(Tuplesortstate *state, Relation rel, ItemPointer self, Datum *values, bool *isnull)
Definition: tuplesort.c:1478
slock_t mutex
Definition: nbtsort.c:136
int maintenance_work_mem
Definition: globals.c:122
Size table_parallelscan_estimate(Relation rel, Snapshot snapshot)
Definition: tableam.c:126
bool havedead
Definition: nbtsort.c:156
RelFileNode rd_node
Definition: rel.h:54
bool ii_Unique
Definition: execnodes.h:170
void tuplesort_attach_shared(Sharedsort *shared, dsm_segment *seg)
Definition: tuplesort.c:4414
#define ShareUpdateExclusiveLock
Definition: lockdefs.h:39
void ConditionVariableSleep(ConditionVariable *cv, uint32 wait_event_info)
PageHeaderData * PageHeader
Definition: bufpage.h:166
int sk_flags
Definition: skey.h:66
#define Assert(condition)
Definition: c.h:733
#define SK_BT_DESC
Definition: nbtree.h:680
Definition: regguts.h:298
int nparticipanttuplesorts
Definition: nbtsort.c:190
void pgstat_progress_update_multi_param(int nparam, const int *index, const int64 *val)
Definition: pgstat.c:3240
#define OffsetNumberNext(offsetNumber)
Definition: off.h:52
int ii_ParallelWorkers
Definition: execnodes.h:174
size_t Size
Definition: c.h:467
#define PageGetSpecialPointer(page)
Definition: bufpage.h:326
static Size _bt_parallel_estimate_shared(Relation heap, Snapshot snapshot)
Definition: nbtsort.c:1483
#define shm_toc_estimate_keys(e, cnt)
Definition: shm_toc.h:53
#define OffsetNumberPrev(offsetNumber)
Definition: off.h:54
void PageSetChecksumInplace(Page page, BlockNumber blkno)
Definition: bufpage.c:1198
#define MAXALIGN(LEN)
Definition: c.h:686
#define index_getattr(tup, attnum, tupleDesc, isnull)
Definition: itup.h:100
void EnterParallelMode(void)
Definition: xact.c:963
#define PROGRESS_SCAN_BLOCKS_TOTAL
Definition: progress.h:102
ScanKeyData scankeys[INDEX_MAX_KEYS]
Definition: nbtree.h:477
void * shm_toc_allocate(shm_toc *toc, Size nbytes)
Definition: shm_toc.c:88
static void _bt_leader_participate_as_worker(BTBuildState *buildstate)
Definition: nbtsort.c:1537
Size tuplesort_estimate_shared(int nWorkers)
Definition: tuplesort.c:4370
#define RelationNeedsWAL(relation)
Definition: rel.h:525
void _bt_check_third_page(Relation rel, Relation heap, bool needheaptidspace, Page page, IndexTuple newtup)
Definition: nbtutils.c:2512
bool ii_Concurrent
Definition: execnodes.h:172
#define SnapshotAny
Definition: snapmgr.h:69
#define PROGRESS_BTREE_PHASE_LEAF_LOAD
Definition: nbtree.h:691
static void _bt_spooldestroy(BTSpool *btspool)
Definition: nbtsort.c:520
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:152
void smgrextend(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum, char *buffer, bool skipFsync)
Definition: smgr.c:483
#define BTreeInnerTupleSetDownLink(itup, blkno)
Definition: nbtree.h:303
#define BTMaxItemSize(page)
Definition: nbtree.h:147
#define P_HIKEY
Definition: nbtree.h:217
static Datum values[MAXATTR]
Definition: bootstrap.c:167
static void _bt_slideleft(Page page)
Definition: nbtsort.c:734
struct BTPageState BTPageState
#define AccessExclusiveLock
Definition: lockdefs.h:45
void shm_toc_insert(shm_toc *toc, uint64 key, void *address)
Definition: shm_toc.c:171
void * palloc(Size size)
Definition: mcxt.c:949
#define PROGRESS_CREATEIDX_TUPLES_DONE
Definition: progress.h:68
static Page _bt_blnewpage(uint32 level)
Definition: nbtsort.c:616
Oid sk_collation
Definition: skey.h:70
XLogRecPtr log_newpage(RelFileNode *rnode, ForkNumber forkNum, BlockNumber blkno, Page page, bool page_std)
Definition: xloginsert.c:972
#define elog(elevel,...)
Definition: elog.h:228
#define ShareLock
Definition: lockdefs.h:41
int i
static void _bt_spool(BTSpool *btspool, ItemPointer self, Datum *values, bool *isnull)
Definition: nbtsort.c:530
void _bt_pageinit(Page page, Size size)
Definition: nbtpage.c:924
static void _bt_sortaddtup(Page page, Size itemsize, IndexTuple itup, OffsetNumber itup_off)
Definition: nbtsort.c:769
#define BUFFERALIGN(LEN)
Definition: c.h:688
#define unlikely(x)
Definition: c.h:208
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:99
#define PROGRESS_CREATEIDX_SUBPHASE
Definition: progress.h:66
Tuplesortstate * tuplesort_begin_index_btree(Relation heapRel, Relation indexRel, bool enforceUnique, int workMem, SortCoordinate coordinate, bool randomAccess)
Definition: tuplesort.c:975
static void _bt_uppershutdown(BTWriteState *wstate, BTPageState *state)
Definition: nbtsort.c:1053
ConditionVariable workersdonecv
Definition: nbtsort.c:128
unsigned short t_info
Definition: itup.h:49
Relation heap
Definition: nbtsort.c:256
#define ItemIdSetUnused(itemId)
Definition: itemid.h:128
#define PARALLEL_KEY_BTREE_SHARED
Definition: nbtsort.c:80
void table_parallelscan_initialize(Relation rel, ParallelTableScanDesc pscan, Snapshot snapshot)
Definition: tableam.c:141
void tuplesort_end(Tuplesortstate *state)
Definition: tuplesort.c:1236
#define BTLessStrategyNumber
Definition: stratnum.h:29
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
static int ApplySortComparator(Datum datum1, bool isNull1, Datum datum2, bool isNull2, SortSupport ssup)
Definition: sortsupport.h:200
uint16 btpo_flags
Definition: nbtree.h:64
void WaitForParallelWorkersToAttach(ParallelContext *pcxt)
Definition: parallel.c:613
void smgrimmedsync(SMgrRelation reln, ForkNumber forknum)
Definition: smgr.c:637
#define RelationGetRelid(relation)
Definition: rel.h:423
long val
Definition: informix.c:684
void * shm_toc_lookup(shm_toc *toc, uint64 key, bool noError)
Definition: shm_toc.c:232
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:126
float4 reltuples
Definition: pg_class.h:63
#define PageGetItem(page, itemId)
Definition: bufpage.h:340
AttrNumber sk_attno
Definition: skey.h:67
Pointer Page
Definition: bufpage.h:78
#define IndexTupleSize(itup)
Definition: itup.h:71
shm_toc * toc
Definition: parallel.h:44
double index_tuples
Definition: genam.h:33
double heap_tuples
Definition: genam.h:32
#define P_ISLEAF(opaque)
Definition: nbtree.h:189