PostgreSQL Source Code  git master
gistbuild.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * gistbuild.c
4  * build algorithm for GiST indexes implementation.
5  *
6  * There are two different strategies:
7  *
8  * 1. Sort all input tuples, pack them into GiST leaf pages in the sorted
9  * order, and create downlinks and internal pages as we go. This builds
10  * the index from the bottom up, similar to how B-tree index build
11  * works.
12  *
13  * 2. Start with an empty index, and insert all tuples one by one.
14  *
15  * The sorted method is used if the operator classes for all columns have
16  * a 'sortsupport' defined. Otherwise, we resort to the second strategy.
17  *
18  * The second strategy can optionally use buffers at different levels of
19  * the tree to reduce I/O, see "Buffering build algorithm" in the README
20  * for a more detailed explanation. It initially calls insert over and
21  * over, but switches to the buffered algorithm after a certain number of
22  * tuples (unless buffering mode is disabled).
23  *
24  *
25  * Portions Copyright (c) 1996-2022, PostgreSQL Global Development Group
26  * Portions Copyright (c) 1994, Regents of the University of California
27  *
28  * IDENTIFICATION
29  * src/backend/access/gist/gistbuild.c
30  *
31  *-------------------------------------------------------------------------
32  */
33 #include "postgres.h"
34 
35 #include <math.h>
36 
37 #include "access/genam.h"
38 #include "access/gist_private.h"
39 #include "access/gistxlog.h"
40 #include "access/tableam.h"
41 #include "access/xloginsert.h"
42 #include "catalog/index.h"
43 #include "miscadmin.h"
44 #include "optimizer/optimizer.h"
45 #include "storage/bufmgr.h"
46 #include "storage/smgr.h"
47 #include "utils/memutils.h"
48 #include "utils/rel.h"
49 #include "utils/tuplesort.h"
50 
51 /* Step of index tuples for check whether to switch to buffering build mode */
52 #define BUFFERING_MODE_SWITCH_CHECK_STEP 256
53 
54 /*
55  * Number of tuples to process in the slow way before switching to buffering
56  * mode, when buffering is explicitly turned on. Also, the number of tuples
57  * to process between readjusting the buffer size parameter, while in
58  * buffering mode.
59  */
60 #define BUFFERING_MODE_TUPLE_SIZE_STATS_TARGET 4096
61 
62 /*
63  * Strategy used to build the index. It can change between the
64  * GIST_BUFFERING_* modes on the fly, but if the Sorted method is used,
65  * that needs to be decided up-front and cannot be changed afterwards.
66  */
67 typedef enum
68 {
69  GIST_SORTED_BUILD, /* bottom-up build by sorting */
70  GIST_BUFFERING_DISABLED, /* in regular build mode and aren't going to
71  * switch */
72  GIST_BUFFERING_AUTO, /* in regular build mode, but will switch to
73  * buffering build mode if the index grows too
74  * big */
75  GIST_BUFFERING_STATS, /* gathering statistics of index tuple size
76  * before switching to the buffering build
77  * mode */
78  GIST_BUFFERING_ACTIVE /* in buffering build mode */
80 
81 /* Working state for gistbuild and its callback */
82 typedef struct
83 {
87 
88  Size freespace; /* amount of free space to leave on pages */
89 
91 
92  int64 indtuples; /* number of tuples indexed */
93 
94  /*
95  * Extra data structures used during a buffering build. 'gfbb' contains
96  * information related to managing the build buffers. 'parentMap' is a
97  * lookup table of the parent of each internal page.
98  */
99  int64 indtuplesSize; /* total size of all indexed tuples */
102 
103  /*
104  * Extra data structures used during a sorting build.
105  */
106  Tuplesortstate *sortstate; /* state data for tuplesort.c */
107 
110 
113  Page ready_pages[XLR_MAX_BLOCK_ID];
115 
116 #define GIST_SORTED_BUILD_PAGE_NUM 4
117 
118 /*
119  * In sorted build, we use a stack of these structs, one for each level,
120  * to hold an in-memory buffer of last pages at the level.
121  *
122  * Sorting GiST build requires good linearization of the sort opclass. This is
123  * not always the case in multidimensional data. To tackle the anomalies, we
124  * buffer index tuples and apply picksplit that can be multidimension-aware.
125  */
127 {
130  struct GistSortedBuildLevelState *parent; /* Upper level, if any */
133 
134 /* prototypes for private functions */
135 
137  Datum *values, bool *isnull,
138  bool tupleIsAlive, void *state);
141  GistSortedBuildLevelState *levelstate,
142  IndexTuple itup);
144  GistSortedBuildLevelState *levelstate);
146 
147 static void gistInitBuffering(GISTBuildState *buildstate);
148 static int calculatePagesPerBuffer(GISTBuildState *buildstate, int levelStep);
149 static void gistBuildCallback(Relation index,
150  ItemPointer tid,
151  Datum *values,
152  bool *isnull,
153  bool tupleIsAlive,
154  void *state);
155 static void gistBufferingBuildInsert(GISTBuildState *buildstate,
156  IndexTuple itup);
157 static bool gistProcessItup(GISTBuildState *buildstate, IndexTuple itup,
158  BlockNumber startblkno, int startlevel);
160  Buffer buffer, int level,
161  IndexTuple *itup, int ntup, OffsetNumber oldoffnum,
162  BlockNumber parentblk, OffsetNumber downlinkoffnum);
164  BlockNumber childblkno, int level,
165  BlockNumber *parentblkno,
166  OffsetNumber *downlinkoffnum);
167 static void gistProcessEmptyingQueue(GISTBuildState *buildstate);
168 static void gistEmptyAllBuffers(GISTBuildState *buildstate);
169 static int gistGetMaxLevel(Relation index);
170 
171 static void gistInitParentMap(GISTBuildState *buildstate);
172 static void gistMemorizeParent(GISTBuildState *buildstate, BlockNumber child,
174 static void gistMemorizeAllDownlinks(GISTBuildState *buildstate,
175  Buffer parentbuf);
176 static BlockNumber gistGetParent(GISTBuildState *buildstate, BlockNumber child);
177 
178 
179 /*
180  * Main entry point to GiST index build.
181  */
184 {
185  IndexBuildResult *result;
186  double reltuples;
187  GISTBuildState buildstate;
189  int fillfactor;
190  Oid SortSupportFnOids[INDEX_MAX_KEYS];
191  GiSTOptions *options = (GiSTOptions *) index->rd_options;
192 
193  /*
194  * We expect to be called exactly once for any index relation. If that's
195  * not the case, big trouble's what we have.
196  */
198  elog(ERROR, "index \"%s\" already contains data",
200 
201  buildstate.indexrel = index;
202  buildstate.heaprel = heap;
203  buildstate.sortstate = NULL;
204  buildstate.giststate = initGISTstate(index);
205 
206  /*
207  * Create a temporary memory context that is reset once for each tuple
208  * processed. (Note: we don't bother to make this a child of the
209  * giststate's scanCxt, so we have to delete it separately at the end.)
210  */
211  buildstate.giststate->tempCxt = createTempGistContext();
212 
213  /*
214  * Choose build strategy. First check whether the user specified to use
215  * buffering mode. (The use-case for that in the field is somewhat
216  * questionable perhaps, but it's important for testing purposes.)
217  */
218  if (options)
219  {
220  if (options->buffering_mode == GIST_OPTION_BUFFERING_ON)
221  buildstate.buildMode = GIST_BUFFERING_STATS;
222  else if (options->buffering_mode == GIST_OPTION_BUFFERING_OFF)
223  buildstate.buildMode = GIST_BUFFERING_DISABLED;
224  else /* must be "auto" */
225  buildstate.buildMode = GIST_BUFFERING_AUTO;
226  }
227  else
228  {
229  buildstate.buildMode = GIST_BUFFERING_AUTO;
230  }
231 
232  /*
233  * Unless buffering mode was forced, see if we can use sorting instead.
234  */
235  if (buildstate.buildMode != GIST_BUFFERING_STATS)
236  {
237  bool hasallsortsupports = true;
239 
240  for (int i = 0; i < keyscount; i++)
241  {
242  SortSupportFnOids[i] = index_getprocid(index, i + 1,
244  if (!OidIsValid(SortSupportFnOids[i]))
245  {
246  hasallsortsupports = false;
247  break;
248  }
249  }
250  if (hasallsortsupports)
251  buildstate.buildMode = GIST_SORTED_BUILD;
252  }
253 
254  /*
255  * Calculate target amount of free space to leave on pages.
256  */
258  buildstate.freespace = BLCKSZ * (100 - fillfactor) / 100;
259 
260  /*
261  * Build the index using the chosen strategy.
262  */
263  buildstate.indtuples = 0;
264  buildstate.indtuplesSize = 0;
265 
266  if (buildstate.buildMode == GIST_SORTED_BUILD)
267  {
268  /*
269  * Sort all data, build the index from bottom up.
270  */
271  buildstate.sortstate = tuplesort_begin_index_gist(heap,
272  index,
274  NULL,
276 
277  /* Scan the table, adding all tuples to the tuplesort */
278  reltuples = table_index_build_scan(heap, index, indexInfo, true, true,
280  (void *) &buildstate, NULL);
281 
282  /*
283  * Perform the sort and build index pages.
284  */
285  tuplesort_performsort(buildstate.sortstate);
286 
287  gist_indexsortbuild(&buildstate);
288 
289  tuplesort_end(buildstate.sortstate);
290  }
291  else
292  {
293  /*
294  * Initialize an empty index and insert all tuples, possibly using
295  * buffers on intermediate levels.
296  */
297  Buffer buffer;
298  Page page;
299 
300  /* initialize the root page */
301  buffer = gistNewBuffer(index);
303  page = BufferGetPage(buffer);
304 
306 
307  GISTInitBuffer(buffer, F_LEAF);
308 
309  MarkBufferDirty(buffer);
310  PageSetLSN(page, GistBuildLSN);
311 
312  UnlockReleaseBuffer(buffer);
313 
315 
316  /* Scan the table, inserting all the tuples to the index. */
317  reltuples = table_index_build_scan(heap, index, indexInfo, true, true,
319  (void *) &buildstate, NULL);
320 
321  /*
322  * If buffering was used, flush out all the tuples that are still in
323  * the buffers.
324  */
325  if (buildstate.buildMode == GIST_BUFFERING_ACTIVE)
326  {
327  elog(DEBUG1, "all tuples processed, emptying buffers");
328  gistEmptyAllBuffers(&buildstate);
329  gistFreeBuildBuffers(buildstate.gfbb);
330  }
331 
332  /*
333  * We didn't write WAL records as we built the index, so if
334  * WAL-logging is required, write all pages to the WAL now.
335  */
336  if (RelationNeedsWAL(index))
337  {
340  true);
341  }
342  }
343 
344  /* okay, all heap tuples are indexed */
345  MemoryContextSwitchTo(oldcxt);
347 
348  freeGISTstate(buildstate.giststate);
349 
350  /*
351  * Return statistics
352  */
353  result = (IndexBuildResult *) palloc(sizeof(IndexBuildResult));
354 
355  result->heap_tuples = reltuples;
356  result->index_tuples = (double) buildstate.indtuples;
357 
358  return result;
359 }
360 
361 /*-------------------------------------------------------------------------
362  * Routines for sorted build
363  *-------------------------------------------------------------------------
364  */
365 
366 /*
367  * Per-tuple callback for table_index_build_scan.
368  */
369 static void
371  ItemPointer tid,
372  Datum *values,
373  bool *isnull,
374  bool tupleIsAlive,
375  void *state)
376 {
377  GISTBuildState *buildstate = (GISTBuildState *) state;
378  MemoryContext oldCtx;
379  Datum compressed_values[INDEX_MAX_KEYS];
380 
381  oldCtx = MemoryContextSwitchTo(buildstate->giststate->tempCxt);
382 
383  /* Form an index tuple and point it at the heap tuple */
384  gistCompressValues(buildstate->giststate, index,
385  values, isnull,
386  true, compressed_values);
387 
389  buildstate->indexrel,
390  tid,
391  compressed_values, isnull);
392 
393  MemoryContextSwitchTo(oldCtx);
394  MemoryContextReset(buildstate->giststate->tempCxt);
395 
396  /* Update tuple count. */
397  buildstate->indtuples += 1;
398 }
399 
400 /*
401  * Build GiST index from bottom up from pre-sorted tuples.
402  */
403 static void
405 {
406  IndexTuple itup;
407  GistSortedBuildLevelState *levelstate;
408  Page page;
409 
410  state->pages_allocated = 0;
411  state->pages_written = 0;
412  state->ready_num_pages = 0;
413 
414  /*
415  * Write an empty page as a placeholder for the root page. It will be
416  * replaced with the real root page at the end.
417  */
418  page = palloc0(BLCKSZ);
420  page, true);
421  state->pages_allocated++;
422  state->pages_written++;
423 
424  /* Allocate a temporary buffer for the first leaf page batch. */
425  levelstate = palloc0(sizeof(GistSortedBuildLevelState));
426  levelstate->pages[0] = page;
427  levelstate->parent = NULL;
428  gistinitpage(page, F_LEAF);
429 
430  /*
431  * Fill index pages with tuples in the sorted order.
432  */
433  while ((itup = tuplesort_getindextuple(state->sortstate, true)) != NULL)
434  {
435  gist_indexsortbuild_levelstate_add(state, levelstate, itup);
436  MemoryContextReset(state->giststate->tempCxt);
437  }
438 
439  /*
440  * Write out the partially full non-root pages.
441  *
442  * Keep in mind that flush can build a new root. If number of pages is > 1
443  * then new root is required.
444  */
445  while (levelstate->parent != NULL || levelstate->current_page != 0)
446  {
448 
450  parent = levelstate->parent;
451  for (int i = 0; i < GIST_SORTED_BUILD_PAGE_NUM; i++)
452  if (levelstate->pages[i])
453  pfree(levelstate->pages[i]);
454  pfree(levelstate);
455  levelstate = parent;
456  }
457 
459 
460  /* Write out the root */
461  PageSetLSN(levelstate->pages[0], GistBuildLSN);
464  levelstate->pages[0], true);
465  if (RelationNeedsWAL(state->indexrel))
466  log_newpage(&state->indexrel->rd_locator, MAIN_FORKNUM, GIST_ROOT_BLKNO,
467  levelstate->pages[0], true);
468 
469  pfree(levelstate->pages[0]);
470  pfree(levelstate);
471 
472  /*
473  * When we WAL-logged index pages, we must nonetheless fsync index files.
474  * Since we're building outside shared buffers, a CHECKPOINT occurring
475  * during the build has no way to flush the previously written data to
476  * disk (indeed it won't know the index even exists). A crash later on
477  * would replay WAL from the checkpoint, therefore it wouldn't replay our
478  * earlier WAL entries. If we do not fsync those pages here, they might
479  * still not be on disk when the crash occurs.
480  */
481  if (RelationNeedsWAL(state->indexrel))
483 }
484 
485 /*
486  * Add tuple to a page. If the pages are full, write them out and re-initialize
487  * a new page first.
488  */
489 static void
491  GistSortedBuildLevelState *levelstate,
492  IndexTuple itup)
493 {
494  Size sizeNeeded;
495 
496  /* Check if tuple can be added to the current page */
497  sizeNeeded = IndexTupleSize(itup) + sizeof(ItemIdData); /* fillfactor ignored */
498  if (PageGetFreeSpace(levelstate->pages[levelstate->current_page]) < sizeNeeded)
499  {
500  Page newPage;
501  Page old_page = levelstate->pages[levelstate->current_page];
502  uint16 old_page_flags = GistPageGetOpaque(old_page)->flags;
503 
504  if (levelstate->current_page + 1 == GIST_SORTED_BUILD_PAGE_NUM)
505  {
507  }
508  else
509  levelstate->current_page++;
510 
511  if (levelstate->pages[levelstate->current_page] == NULL)
512  levelstate->pages[levelstate->current_page] = palloc(BLCKSZ);
513 
514  newPage = levelstate->pages[levelstate->current_page];
515  gistinitpage(newPage, old_page_flags);
516  }
517 
518  gistfillbuffer(levelstate->pages[levelstate->current_page], &itup, 1, InvalidOffsetNumber);
519 }
520 
521 static void
523  GistSortedBuildLevelState *levelstate)
524 {
526  BlockNumber blkno;
527  MemoryContext oldCtx;
528  IndexTuple union_tuple;
529  SplitedPageLayout *dist;
530  IndexTuple *itvec;
531  int vect_len;
532  bool isleaf = GistPageIsLeaf(levelstate->pages[0]);
533 
535 
536  oldCtx = MemoryContextSwitchTo(state->giststate->tempCxt);
537 
538  /* Get index tuples from first page */
539  itvec = gistextractpage(levelstate->pages[0], &vect_len);
540  if (levelstate->current_page > 0)
541  {
542  /* Append tuples from each page */
543  for (int i = 1; i < levelstate->current_page + 1; i++)
544  {
545  int len_local;
546  IndexTuple *itvec_local = gistextractpage(levelstate->pages[i], &len_local);
547 
548  itvec = gistjoinvector(itvec, &vect_len, itvec_local, len_local);
549  pfree(itvec_local);
550  }
551 
552  /* Apply picksplit to list of all collected tuples */
553  dist = gistSplit(state->indexrel, levelstate->pages[0], itvec, vect_len, state->giststate);
554  }
555  else
556  {
557  /* Create splitted layout from single page */
558  dist = (SplitedPageLayout *) palloc0(sizeof(SplitedPageLayout));
559  union_tuple = gistunion(state->indexrel, itvec, vect_len,
560  state->giststate);
561  dist->itup = union_tuple;
562  dist->list = gistfillitupvec(itvec, vect_len, &(dist->lenlist));
563  dist->block.num = vect_len;
564  }
565 
566  MemoryContextSwitchTo(oldCtx);
567 
568  /* Reset page counter */
569  levelstate->current_page = 0;
570 
571  /* Create pages for all partitions in split result */
572  for (; dist != NULL; dist = dist->next)
573  {
574  char *data;
575  Page target;
576 
577  /* check once per page */
579 
580  /* Create page and copy data */
581  data = (char *) (dist->list);
582  target = palloc0(BLCKSZ);
583  gistinitpage(target, isleaf ? F_LEAF : 0);
584  for (int i = 0; i < dist->block.num; i++)
585  {
586  IndexTuple thistup = (IndexTuple) data;
587 
588  if (PageAddItem(target, (Item) data, IndexTupleSize(thistup), i + FirstOffsetNumber, false, false) == InvalidOffsetNumber)
589  elog(ERROR, "failed to add item to index page in \"%s\"", RelationGetRelationName(state->indexrel));
590 
591  data += IndexTupleSize(thistup);
592  }
593  union_tuple = dist->itup;
594 
595  if (state->ready_num_pages == XLR_MAX_BLOCK_ID)
597 
598  /*
599  * The page is now complete. Assign a block number to it, and add it
600  * to the list of finished pages. (We don't write it out immediately,
601  * because we want to WAL-log the pages in batches.)
602  */
603  blkno = state->pages_allocated++;
604  state->ready_blknos[state->ready_num_pages] = blkno;
605  state->ready_pages[state->ready_num_pages] = target;
606  state->ready_num_pages++;
607  ItemPointerSetBlockNumber(&(union_tuple->t_tid), blkno);
608 
609  /*
610  * Set the right link to point to the previous page. This is just for
611  * debugging purposes: GiST only follows the right link if a page is
612  * split concurrently to a scan, and that cannot happen during index
613  * build.
614  *
615  * It's a bit counterintuitive that we set the right link on the new
616  * page to point to the previous page, not the other way around. But
617  * GiST pages are not ordered like B-tree pages are, so as long as the
618  * right-links form a chain through all the pages at the same level,
619  * the order doesn't matter.
620  */
621  if (levelstate->last_blkno)
622  GistPageGetOpaque(target)->rightlink = levelstate->last_blkno;
623  levelstate->last_blkno = blkno;
624 
625  /*
626  * Insert the downlink to the parent page. If this was the root,
627  * create a new page as the parent, which becomes the new root.
628  */
629  parent = levelstate->parent;
630  if (parent == NULL)
631  {
633  parent->pages[0] = (Page) palloc(BLCKSZ);
634  parent->parent = NULL;
635  gistinitpage(parent->pages[0], 0);
636 
637  levelstate->parent = parent;
638  }
640  }
641 }
642 
643 static void
645 {
646  if (state->ready_num_pages == 0)
647  return;
648 
649  for (int i = 0; i < state->ready_num_pages; i++)
650  {
651  Page page = state->ready_pages[i];
652  BlockNumber blkno = state->ready_blknos[i];
653 
654  /* Currently, the blocks must be buffered in order. */
655  if (blkno != state->pages_written)
656  elog(ERROR, "unexpected block number to flush GiST sorting build");
657 
658  PageSetLSN(page, GistBuildLSN);
659  PageSetChecksumInplace(page, blkno);
660  smgrextend(RelationGetSmgr(state->indexrel), MAIN_FORKNUM, blkno, page,
661  true);
662 
663  state->pages_written++;
664  }
665 
666  if (RelationNeedsWAL(state->indexrel))
667  log_newpages(&state->indexrel->rd_locator, MAIN_FORKNUM, state->ready_num_pages,
668  state->ready_blknos, state->ready_pages, true);
669 
670  for (int i = 0; i < state->ready_num_pages; i++)
671  pfree(state->ready_pages[i]);
672 
673  state->ready_num_pages = 0;
674 }
675 
676 
677 /*-------------------------------------------------------------------------
678  * Routines for non-sorted build
679  *-------------------------------------------------------------------------
680  */
681 
682 /*
683  * Attempt to switch to buffering mode.
684  *
685  * If there is not enough memory for buffering build, sets bufferingMode
686  * to GIST_BUFFERING_DISABLED, so that we don't bother to try the switch
687  * anymore. Otherwise initializes the build buffers, and sets bufferingMode to
688  * GIST_BUFFERING_ACTIVE.
689  */
690 static void
692 {
693  Relation index = buildstate->indexrel;
694  int pagesPerBuffer;
695  Size pageFreeSpace;
696  Size itupAvgSize,
697  itupMinSize;
698  double avgIndexTuplesPerPage,
699  maxIndexTuplesPerPage;
700  int i;
701  int levelStep;
702 
703  /* Calc space of index page which is available for index tuples */
704  pageFreeSpace = BLCKSZ - SizeOfPageHeaderData - sizeof(GISTPageOpaqueData)
705  - sizeof(ItemIdData)
706  - buildstate->freespace;
707 
708  /*
709  * Calculate average size of already inserted index tuples using gathered
710  * statistics.
711  */
712  itupAvgSize = (double) buildstate->indtuplesSize /
713  (double) buildstate->indtuples;
714 
715  /*
716  * Calculate minimal possible size of index tuple by index metadata.
717  * Minimal possible size of varlena is VARHDRSZ.
718  *
719  * XXX: that's not actually true, as a short varlen can be just 2 bytes.
720  * And we should take padding into account here.
721  */
722  itupMinSize = (Size) MAXALIGN(sizeof(IndexTupleData));
723  for (i = 0; i < index->rd_att->natts; i++)
724  {
725  if (TupleDescAttr(index->rd_att, i)->attlen < 0)
726  itupMinSize += VARHDRSZ;
727  else
728  itupMinSize += TupleDescAttr(index->rd_att, i)->attlen;
729  }
730 
731  /* Calculate average and maximal number of index tuples which fit to page */
732  avgIndexTuplesPerPage = pageFreeSpace / itupAvgSize;
733  maxIndexTuplesPerPage = pageFreeSpace / itupMinSize;
734 
735  /*
736  * We need to calculate two parameters for the buffering algorithm:
737  * levelStep and pagesPerBuffer.
738  *
739  * levelStep determines the size of subtree that we operate on, while
740  * emptying a buffer. A higher value is better, as you need fewer buffer
741  * emptying steps to build the index. However, if you set it too high, the
742  * subtree doesn't fit in cache anymore, and you quickly lose the benefit
743  * of the buffers.
744  *
745  * In Arge et al's paper, levelStep is chosen as logB(M/4B), where B is
746  * the number of tuples on page (ie. fanout), and M is the amount of
747  * internal memory available. Curiously, they doesn't explain *why* that
748  * setting is optimal. We calculate it by taking the highest levelStep so
749  * that a subtree still fits in cache. For a small B, our way of
750  * calculating levelStep is very close to Arge et al's formula. For a
751  * large B, our formula gives a value that is 2x higher.
752  *
753  * The average size (in pages) of a subtree of depth n can be calculated
754  * as a geometric series:
755  *
756  * B^0 + B^1 + B^2 + ... + B^n = (1 - B^(n + 1)) / (1 - B)
757  *
758  * where B is the average number of index tuples on page. The subtree is
759  * cached in the shared buffer cache and the OS cache, so we choose
760  * levelStep so that the subtree size is comfortably smaller than
761  * effective_cache_size, with a safety factor of 4.
762  *
763  * The estimate on the average number of index tuples on page is based on
764  * average tuple sizes observed before switching to buffered build, so the
765  * real subtree size can be somewhat larger. Also, it would selfish to
766  * gobble the whole cache for our index build. The safety factor of 4
767  * should account for those effects.
768  *
769  * The other limiting factor for setting levelStep is that while
770  * processing a subtree, we need to hold one page for each buffer at the
771  * next lower buffered level. The max. number of buffers needed for that
772  * is maxIndexTuplesPerPage^levelStep. This is very conservative, but
773  * hopefully maintenance_work_mem is set high enough that you're
774  * constrained by effective_cache_size rather than maintenance_work_mem.
775  *
776  * XXX: the buffer hash table consumes a fair amount of memory too per
777  * buffer, but that is not currently taken into account. That scales on
778  * the total number of buffers used, ie. the index size and on levelStep.
779  * Note that a higher levelStep *reduces* the amount of memory needed for
780  * the hash table.
781  */
782  levelStep = 1;
783  for (;;)
784  {
785  double subtreesize;
786  double maxlowestlevelpages;
787 
788  /* size of an average subtree at this levelStep (in pages). */
789  subtreesize =
790  (1 - pow(avgIndexTuplesPerPage, (double) (levelStep + 1))) /
791  (1 - avgIndexTuplesPerPage);
792 
793  /* max number of pages at the lowest level of a subtree */
794  maxlowestlevelpages = pow(maxIndexTuplesPerPage, (double) levelStep);
795 
796  /* subtree must fit in cache (with safety factor of 4) */
797  if (subtreesize > effective_cache_size / 4)
798  break;
799 
800  /* each node in the lowest level of a subtree has one page in memory */
801  if (maxlowestlevelpages > ((double) maintenance_work_mem * 1024) / BLCKSZ)
802  break;
803 
804  /* Good, we can handle this levelStep. See if we can go one higher. */
805  levelStep++;
806  }
807 
808  /*
809  * We just reached an unacceptable value of levelStep in previous loop.
810  * So, decrease levelStep to get last acceptable value.
811  */
812  levelStep--;
813 
814  /*
815  * If there's not enough cache or maintenance_work_mem, fall back to plain
816  * inserts.
817  */
818  if (levelStep <= 0)
819  {
820  elog(DEBUG1, "failed to switch to buffered GiST build");
821  buildstate->buildMode = GIST_BUFFERING_DISABLED;
822  return;
823  }
824 
825  /*
826  * The second parameter to set is pagesPerBuffer, which determines the
827  * size of each buffer. We adjust pagesPerBuffer also during the build,
828  * which is why this calculation is in a separate function.
829  */
830  pagesPerBuffer = calculatePagesPerBuffer(buildstate, levelStep);
831 
832  /* Initialize GISTBuildBuffers with these parameters */
833  buildstate->gfbb = gistInitBuildBuffers(pagesPerBuffer, levelStep,
835 
836  gistInitParentMap(buildstate);
837 
838  buildstate->buildMode = GIST_BUFFERING_ACTIVE;
839 
840  elog(DEBUG1, "switched to buffered GiST build; level step = %d, pagesPerBuffer = %d",
841  levelStep, pagesPerBuffer);
842 }
843 
844 /*
845  * Calculate pagesPerBuffer parameter for the buffering algorithm.
846  *
847  * Buffer size is chosen so that assuming that tuples are distributed
848  * randomly, emptying half a buffer fills on average one page in every buffer
849  * at the next lower level.
850  */
851 static int
852 calculatePagesPerBuffer(GISTBuildState *buildstate, int levelStep)
853 {
854  double pagesPerBuffer;
855  double avgIndexTuplesPerPage;
856  double itupAvgSize;
857  Size pageFreeSpace;
858 
859  /* Calc space of index page which is available for index tuples */
860  pageFreeSpace = BLCKSZ - SizeOfPageHeaderData - sizeof(GISTPageOpaqueData)
861  - sizeof(ItemIdData)
862  - buildstate->freespace;
863 
864  /*
865  * Calculate average size of already inserted index tuples using gathered
866  * statistics.
867  */
868  itupAvgSize = (double) buildstate->indtuplesSize /
869  (double) buildstate->indtuples;
870 
871  avgIndexTuplesPerPage = pageFreeSpace / itupAvgSize;
872 
873  /*
874  * Recalculate required size of buffers.
875  */
876  pagesPerBuffer = 2 * pow(avgIndexTuplesPerPage, levelStep);
877 
878  return (int) rint(pagesPerBuffer);
879 }
880 
881 /*
882  * Per-tuple callback for table_index_build_scan.
883  */
884 static void
886  ItemPointer tid,
887  Datum *values,
888  bool *isnull,
889  bool tupleIsAlive,
890  void *state)
891 {
892  GISTBuildState *buildstate = (GISTBuildState *) state;
893  IndexTuple itup;
894  MemoryContext oldCtx;
895 
896  oldCtx = MemoryContextSwitchTo(buildstate->giststate->tempCxt);
897 
898  /* form an index tuple and point it at the heap tuple */
899  itup = gistFormTuple(buildstate->giststate, index,
900  values, isnull,
901  true);
902  itup->t_tid = *tid;
903 
904  if (buildstate->buildMode == GIST_BUFFERING_ACTIVE)
905  {
906  /* We have buffers, so use them. */
907  gistBufferingBuildInsert(buildstate, itup);
908  }
909  else
910  {
911  /*
912  * There's no buffers (yet). Since we already have the index relation
913  * locked, we call gistdoinsert directly.
914  */
915  gistdoinsert(index, itup, buildstate->freespace,
916  buildstate->giststate, buildstate->heaprel, true);
917  }
918 
919  /* Update tuple count and total size. */
920  buildstate->indtuples += 1;
921  buildstate->indtuplesSize += IndexTupleSize(itup);
922 
923  MemoryContextSwitchTo(oldCtx);
924  MemoryContextReset(buildstate->giststate->tempCxt);
925 
926  if (buildstate->buildMode == GIST_BUFFERING_ACTIVE &&
928  {
929  /* Adjust the target buffer size now */
930  buildstate->gfbb->pagesPerBuffer =
931  calculatePagesPerBuffer(buildstate, buildstate->gfbb->levelStep);
932  }
933 
934  /*
935  * In 'auto' mode, check if the index has grown too large to fit in cache,
936  * and switch to buffering mode if it has.
937  *
938  * To avoid excessive calls to smgrnblocks(), only check this every
939  * BUFFERING_MODE_SWITCH_CHECK_STEP index tuples.
940  *
941  * In 'stats' state, switch as soon as we have seen enough tuples to have
942  * some idea of the average tuple size.
943  */
944  if ((buildstate->buildMode == GIST_BUFFERING_AUTO &&
945  buildstate->indtuples % BUFFERING_MODE_SWITCH_CHECK_STEP == 0 &&
947  MAIN_FORKNUM)) ||
948  (buildstate->buildMode == GIST_BUFFERING_STATS &&
950  {
951  /*
952  * Index doesn't fit in effective cache anymore. Try to switch to
953  * buffering build mode.
954  */
955  gistInitBuffering(buildstate);
956  }
957 }
958 
959 /*
960  * Insert function for buffering index build.
961  */
962 static void
964 {
965  /* Insert the tuple to buffers. */
966  gistProcessItup(buildstate, itup, 0, buildstate->gfbb->rootlevel);
967 
968  /* If we filled up (half of a) buffer, process buffer emptying. */
969  gistProcessEmptyingQueue(buildstate);
970 }
971 
972 /*
973  * Process an index tuple. Runs the tuple down the tree until we reach a leaf
974  * page or node buffer, and inserts the tuple there. Returns true if we have
975  * to stop buffer emptying process (because one of child buffers can't take
976  * index tuples anymore).
977  */
978 static bool
980  BlockNumber startblkno, int startlevel)
981 {
982  GISTSTATE *giststate = buildstate->giststate;
983  GISTBuildBuffers *gfbb = buildstate->gfbb;
984  Relation indexrel = buildstate->indexrel;
985  BlockNumber childblkno;
986  Buffer buffer;
987  bool result = false;
988  BlockNumber blkno;
989  int level;
990  OffsetNumber downlinkoffnum = InvalidOffsetNumber;
991  BlockNumber parentblkno = InvalidBlockNumber;
992 
994 
995  /*
996  * Loop until we reach a leaf page (level == 0) or a level with buffers
997  * (not including the level we start at, because we would otherwise make
998  * no progress).
999  */
1000  blkno = startblkno;
1001  level = startlevel;
1002  for (;;)
1003  {
1004  ItemId iid;
1005  IndexTuple idxtuple,
1006  newtup;
1007  Page page;
1008  OffsetNumber childoffnum;
1009 
1010  /* Have we reached a level with buffers? */
1011  if (LEVEL_HAS_BUFFERS(level, gfbb) && level != startlevel)
1012  break;
1013 
1014  /* Have we reached a leaf page? */
1015  if (level == 0)
1016  break;
1017 
1018  /*
1019  * Nope. Descend down to the next level then. Choose a child to
1020  * descend down to.
1021  */
1022 
1023  buffer = ReadBuffer(indexrel, blkno);
1024  LockBuffer(buffer, GIST_EXCLUSIVE);
1025 
1026  page = (Page) BufferGetPage(buffer);
1027  childoffnum = gistchoose(indexrel, page, itup, giststate);
1028  iid = PageGetItemId(page, childoffnum);
1029  idxtuple = (IndexTuple) PageGetItem(page, iid);
1030  childblkno = ItemPointerGetBlockNumber(&(idxtuple->t_tid));
1031 
1032  if (level > 1)
1033  gistMemorizeParent(buildstate, childblkno, blkno);
1034 
1035  /*
1036  * Check that the key representing the target child node is consistent
1037  * with the key we're inserting. Update it if it's not.
1038  */
1039  newtup = gistgetadjusted(indexrel, idxtuple, itup, giststate);
1040  if (newtup)
1041  {
1042  blkno = gistbufferinginserttuples(buildstate,
1043  buffer,
1044  level,
1045  &newtup,
1046  1,
1047  childoffnum,
1050  /* gistbufferinginserttuples() released the buffer */
1051  }
1052  else
1053  UnlockReleaseBuffer(buffer);
1054 
1055  /* Descend to the child */
1056  parentblkno = blkno;
1057  blkno = childblkno;
1058  downlinkoffnum = childoffnum;
1059  Assert(level > 0);
1060  level--;
1061  }
1062 
1063  if (LEVEL_HAS_BUFFERS(level, gfbb))
1064  {
1065  /*
1066  * We've reached level with buffers. Place the index tuple to the
1067  * buffer, and add the buffer to the emptying queue if it overflows.
1068  */
1069  GISTNodeBuffer *childNodeBuffer;
1070 
1071  /* Find the buffer or create a new one */
1072  childNodeBuffer = gistGetNodeBuffer(gfbb, giststate, blkno, level);
1073 
1074  /* Add index tuple to it */
1075  gistPushItupToNodeBuffer(gfbb, childNodeBuffer, itup);
1076 
1077  if (BUFFER_OVERFLOWED(childNodeBuffer, gfbb))
1078  result = true;
1079  }
1080  else
1081  {
1082  /*
1083  * We've reached a leaf page. Place the tuple here.
1084  */
1085  Assert(level == 0);
1086  buffer = ReadBuffer(indexrel, blkno);
1087  LockBuffer(buffer, GIST_EXCLUSIVE);
1088  gistbufferinginserttuples(buildstate, buffer, level,
1089  &itup, 1, InvalidOffsetNumber,
1090  parentblkno, downlinkoffnum);
1091  /* gistbufferinginserttuples() released the buffer */
1092  }
1093 
1094  return result;
1095 }
1096 
1097 /*
1098  * Insert tuples to a given page.
1099  *
1100  * This is analogous with gistinserttuples() in the regular insertion code.
1101  *
1102  * Returns the block number of the page where the (first) new or updated tuple
1103  * was inserted. Usually that's the original page, but might be a sibling page
1104  * if the original page was split.
1105  *
1106  * Caller should hold a lock on 'buffer' on entry. This function will unlock
1107  * and unpin it.
1108  */
1109 static BlockNumber
1110 gistbufferinginserttuples(GISTBuildState *buildstate, Buffer buffer, int level,
1111  IndexTuple *itup, int ntup, OffsetNumber oldoffnum,
1112  BlockNumber parentblk, OffsetNumber downlinkoffnum)
1113 {
1114  GISTBuildBuffers *gfbb = buildstate->gfbb;
1115  List *splitinfo;
1116  bool is_split;
1117  BlockNumber placed_to_blk = InvalidBlockNumber;
1118 
1119  is_split = gistplacetopage(buildstate->indexrel,
1120  buildstate->freespace,
1121  buildstate->giststate,
1122  buffer,
1123  itup, ntup, oldoffnum, &placed_to_blk,
1124  InvalidBuffer,
1125  &splitinfo,
1126  false,
1127  buildstate->heaprel, true);
1128 
1129  /*
1130  * If this is a root split, update the root path item kept in memory. This
1131  * ensures that all path stacks are always complete, including all parent
1132  * nodes up to the root. That simplifies the algorithm to re-find correct
1133  * parent.
1134  */
1135  if (is_split && BufferGetBlockNumber(buffer) == GIST_ROOT_BLKNO)
1136  {
1137  Page page = BufferGetPage(buffer);
1138  OffsetNumber off;
1139  OffsetNumber maxoff;
1140 
1141  Assert(level == gfbb->rootlevel);
1142  gfbb->rootlevel++;
1143 
1144  elog(DEBUG2, "splitting GiST root page, now %d levels deep", gfbb->rootlevel);
1145 
1146  /*
1147  * All the downlinks on the old root page are now on one of the child
1148  * pages. Visit all the new child pages to memorize the parents of the
1149  * grandchildren.
1150  */
1151  if (gfbb->rootlevel > 1)
1152  {
1153  maxoff = PageGetMaxOffsetNumber(page);
1154  for (off = FirstOffsetNumber; off <= maxoff; off++)
1155  {
1156  ItemId iid = PageGetItemId(page, off);
1157  IndexTuple idxtuple = (IndexTuple) PageGetItem(page, iid);
1158  BlockNumber childblkno = ItemPointerGetBlockNumber(&(idxtuple->t_tid));
1159  Buffer childbuf = ReadBuffer(buildstate->indexrel, childblkno);
1160 
1161  LockBuffer(childbuf, GIST_SHARE);
1162  gistMemorizeAllDownlinks(buildstate, childbuf);
1163  UnlockReleaseBuffer(childbuf);
1164 
1165  /*
1166  * Also remember that the parent of the new child page is the
1167  * root block.
1168  */
1169  gistMemorizeParent(buildstate, childblkno, GIST_ROOT_BLKNO);
1170  }
1171  }
1172  }
1173 
1174  if (splitinfo)
1175  {
1176  /*
1177  * Insert the downlinks to the parent. This is analogous with
1178  * gistfinishsplit() in the regular insertion code, but the locking is
1179  * simpler, and we have to maintain the buffers on internal nodes and
1180  * the parent map.
1181  */
1182  IndexTuple *downlinks;
1183  int ndownlinks,
1184  i;
1185  Buffer parentBuffer;
1186  ListCell *lc;
1187 
1188  /* Parent may have changed since we memorized this path. */
1189  parentBuffer =
1190  gistBufferingFindCorrectParent(buildstate,
1191  BufferGetBlockNumber(buffer),
1192  level,
1193  &parentblk,
1194  &downlinkoffnum);
1195 
1196  /*
1197  * If there's a buffer associated with this page, that needs to be
1198  * split too. gistRelocateBuildBuffersOnSplit() will also adjust the
1199  * downlinks in 'splitinfo', to make sure they're consistent not only
1200  * with the tuples already on the pages, but also the tuples in the
1201  * buffers that will eventually be inserted to them.
1202  */
1204  buildstate->giststate,
1205  buildstate->indexrel,
1206  level,
1207  buffer, splitinfo);
1208 
1209  /* Create an array of all the downlink tuples */
1210  ndownlinks = list_length(splitinfo);
1211  downlinks = (IndexTuple *) palloc(sizeof(IndexTuple) * ndownlinks);
1212  i = 0;
1213  foreach(lc, splitinfo)
1214  {
1215  GISTPageSplitInfo *splitinfo = lfirst(lc);
1216 
1217  /*
1218  * Remember the parent of each new child page in our parent map.
1219  * This assumes that the downlinks fit on the parent page. If the
1220  * parent page is split, too, when we recurse up to insert the
1221  * downlinks, the recursive gistbufferinginserttuples() call will
1222  * update the map again.
1223  */
1224  if (level > 0)
1225  gistMemorizeParent(buildstate,
1226  BufferGetBlockNumber(splitinfo->buf),
1227  BufferGetBlockNumber(parentBuffer));
1228 
1229  /*
1230  * Also update the parent map for all the downlinks that got moved
1231  * to a different page. (actually this also loops through the
1232  * downlinks that stayed on the original page, but it does no
1233  * harm).
1234  */
1235  if (level > 1)
1236  gistMemorizeAllDownlinks(buildstate, splitinfo->buf);
1237 
1238  /*
1239  * Since there's no concurrent access, we can release the lower
1240  * level buffers immediately. This includes the original page.
1241  */
1242  UnlockReleaseBuffer(splitinfo->buf);
1243  downlinks[i++] = splitinfo->downlink;
1244  }
1245 
1246  /* Insert them into parent. */
1247  gistbufferinginserttuples(buildstate, parentBuffer, level + 1,
1248  downlinks, ndownlinks, downlinkoffnum,
1250 
1251  list_free_deep(splitinfo); /* we don't need this anymore */
1252  }
1253  else
1254  UnlockReleaseBuffer(buffer);
1255 
1256  return placed_to_blk;
1257 }
1258 
1259 /*
1260  * Find the downlink pointing to a child page.
1261  *
1262  * 'childblkno' indicates the child page to find the parent for. 'level' is
1263  * the level of the child. On entry, *parentblkno and *downlinkoffnum can
1264  * point to a location where the downlink used to be - we will check that
1265  * location first, and save some cycles if it hasn't moved. The function
1266  * returns a buffer containing the downlink, exclusively-locked, and
1267  * *parentblkno and *downlinkoffnum are set to the real location of the
1268  * downlink.
1269  *
1270  * If the child page is a leaf (level == 0), the caller must supply a correct
1271  * parentblkno. Otherwise we use the parent map hash table to find the parent
1272  * block.
1273  *
1274  * This function serves the same purpose as gistFindCorrectParent() during
1275  * normal index inserts, but this is simpler because we don't need to deal
1276  * with concurrent inserts.
1277  */
1278 static Buffer
1280  BlockNumber childblkno, int level,
1281  BlockNumber *parentblkno,
1282  OffsetNumber *downlinkoffnum)
1283 {
1285  Buffer buffer;
1286  Page page;
1287  OffsetNumber maxoff;
1288  OffsetNumber off;
1289 
1290  if (level > 0)
1291  parent = gistGetParent(buildstate, childblkno);
1292  else
1293  {
1294  /*
1295  * For a leaf page, the caller must supply a correct parent block
1296  * number.
1297  */
1298  if (*parentblkno == InvalidBlockNumber)
1299  elog(ERROR, "no parent buffer provided of child %u", childblkno);
1300  parent = *parentblkno;
1301  }
1302 
1303  buffer = ReadBuffer(buildstate->indexrel, parent);
1304  page = BufferGetPage(buffer);
1305  LockBuffer(buffer, GIST_EXCLUSIVE);
1306  gistcheckpage(buildstate->indexrel, buffer);
1307  maxoff = PageGetMaxOffsetNumber(page);
1308 
1309  /* Check if it was not moved */
1310  if (parent == *parentblkno && *parentblkno != InvalidBlockNumber &&
1311  *downlinkoffnum != InvalidOffsetNumber && *downlinkoffnum <= maxoff)
1312  {
1313  ItemId iid = PageGetItemId(page, *downlinkoffnum);
1314  IndexTuple idxtuple = (IndexTuple) PageGetItem(page, iid);
1315 
1316  if (ItemPointerGetBlockNumber(&(idxtuple->t_tid)) == childblkno)
1317  {
1318  /* Still there */
1319  return buffer;
1320  }
1321  }
1322 
1323  /*
1324  * Downlink was not at the offset where it used to be. Scan the page to
1325  * find it. During normal gist insertions, it might've moved to another
1326  * page, to the right, but during a buffering build, we keep track of the
1327  * parent of each page in the lookup table so we should always know what
1328  * page it's on.
1329  */
1330  for (off = FirstOffsetNumber; off <= maxoff; off = OffsetNumberNext(off))
1331  {
1332  ItemId iid = PageGetItemId(page, off);
1333  IndexTuple idxtuple = (IndexTuple) PageGetItem(page, iid);
1334 
1335  if (ItemPointerGetBlockNumber(&(idxtuple->t_tid)) == childblkno)
1336  {
1337  /* yes!!, found it */
1338  *downlinkoffnum = off;
1339  return buffer;
1340  }
1341  }
1342 
1343  elog(ERROR, "failed to re-find parent for block %u", childblkno);
1344  return InvalidBuffer; /* keep compiler quiet */
1345 }
1346 
1347 /*
1348  * Process buffers emptying stack. Emptying of one buffer can cause emptying
1349  * of other buffers. This function iterates until this cascading emptying
1350  * process finished, e.g. until buffers emptying stack is empty.
1351  */
1352 static void
1354 {
1355  GISTBuildBuffers *gfbb = buildstate->gfbb;
1356 
1357  /* Iterate while we have elements in buffers emptying stack. */
1358  while (gfbb->bufferEmptyingQueue != NIL)
1359  {
1360  GISTNodeBuffer *emptyingNodeBuffer;
1361 
1362  /* Get node buffer from emptying stack. */
1363  emptyingNodeBuffer = (GISTNodeBuffer *) linitial(gfbb->bufferEmptyingQueue);
1365  emptyingNodeBuffer->queuedForEmptying = false;
1366 
1367  /*
1368  * We are going to load last pages of buffers where emptying will be
1369  * to. So let's unload any previously loaded buffers.
1370  */
1371  gistUnloadNodeBuffers(gfbb);
1372 
1373  /*
1374  * Pop tuples from the buffer and run them down to the buffers at
1375  * lower level, or leaf pages. We continue until one of the lower
1376  * level buffers fills up, or this buffer runs empty.
1377  *
1378  * In Arge et al's paper, the buffer emptying is stopped after
1379  * processing 1/2 node buffer worth of tuples, to avoid overfilling
1380  * any of the lower level buffers. However, it's more efficient to
1381  * keep going until one of the lower level buffers actually fills up,
1382  * so that's what we do. This doesn't need to be exact, if a buffer
1383  * overfills by a few tuples, there's no harm done.
1384  */
1385  while (true)
1386  {
1387  IndexTuple itup;
1388 
1389  /* Get next index tuple from the buffer */
1390  if (!gistPopItupFromNodeBuffer(gfbb, emptyingNodeBuffer, &itup))
1391  break;
1392 
1393  /*
1394  * Run it down to the underlying node buffer or leaf page.
1395  *
1396  * Note: it's possible that the buffer we're emptying splits as a
1397  * result of this call. If that happens, our emptyingNodeBuffer
1398  * points to the left half of the split. After split, it's very
1399  * likely that the new left buffer is no longer over the half-full
1400  * threshold, but we might as well keep flushing tuples from it
1401  * until we fill a lower-level buffer.
1402  */
1403  if (gistProcessItup(buildstate, itup, emptyingNodeBuffer->nodeBlocknum, emptyingNodeBuffer->level))
1404  {
1405  /*
1406  * A lower level buffer filled up. Stop emptying this buffer,
1407  * to avoid overflowing the lower level buffer.
1408  */
1409  break;
1410  }
1411 
1412  /* Free all the memory allocated during index tuple processing */
1413  MemoryContextReset(buildstate->giststate->tempCxt);
1414  }
1415  }
1416 }
1417 
1418 /*
1419  * Empty all node buffers, from top to bottom. This is done at the end of
1420  * index build to flush all remaining tuples to the index.
1421  *
1422  * Note: This destroys the buffersOnLevels lists, so the buffers should not
1423  * be inserted to after this call.
1424  */
1425 static void
1427 {
1428  GISTBuildBuffers *gfbb = buildstate->gfbb;
1429  MemoryContext oldCtx;
1430  int i;
1431 
1432  oldCtx = MemoryContextSwitchTo(buildstate->giststate->tempCxt);
1433 
1434  /*
1435  * Iterate through the levels from top to bottom.
1436  */
1437  for (i = gfbb->buffersOnLevelsLen - 1; i >= 0; i--)
1438  {
1439  /*
1440  * Empty all buffers on this level. Note that new buffers can pop up
1441  * in the list during the processing, as a result of page splits, so a
1442  * simple walk through the list won't work. We remove buffers from the
1443  * list when we see them empty; a buffer can't become non-empty once
1444  * it's been fully emptied.
1445  */
1446  while (gfbb->buffersOnLevels[i] != NIL)
1447  {
1448  GISTNodeBuffer *nodeBuffer;
1449 
1450  nodeBuffer = (GISTNodeBuffer *) linitial(gfbb->buffersOnLevels[i]);
1451 
1452  if (nodeBuffer->blocksCount != 0)
1453  {
1454  /*
1455  * Add this buffer to the emptying queue, and proceed to empty
1456  * the queue.
1457  */
1458  if (!nodeBuffer->queuedForEmptying)
1459  {
1461  nodeBuffer->queuedForEmptying = true;
1462  gfbb->bufferEmptyingQueue =
1463  lcons(nodeBuffer, gfbb->bufferEmptyingQueue);
1464  MemoryContextSwitchTo(buildstate->giststate->tempCxt);
1465  }
1466  gistProcessEmptyingQueue(buildstate);
1467  }
1468  else
1469  gfbb->buffersOnLevels[i] =
1471  }
1472  elog(DEBUG2, "emptied all buffers at level %d", i);
1473  }
1474  MemoryContextSwitchTo(oldCtx);
1475 }
1476 
1477 /*
1478  * Get the depth of the GiST index.
1479  */
1480 static int
1482 {
1483  int maxLevel;
1484  BlockNumber blkno;
1485 
1486  /*
1487  * Traverse down the tree, starting from the root, until we hit the leaf
1488  * level.
1489  */
1490  maxLevel = 0;
1491  blkno = GIST_ROOT_BLKNO;
1492  while (true)
1493  {
1494  Buffer buffer;
1495  Page page;
1496  IndexTuple itup;
1497 
1498  buffer = ReadBuffer(index, blkno);
1499 
1500  /*
1501  * There's no concurrent access during index build, so locking is just
1502  * pro forma.
1503  */
1504  LockBuffer(buffer, GIST_SHARE);
1505  page = (Page) BufferGetPage(buffer);
1506 
1507  if (GistPageIsLeaf(page))
1508  {
1509  /* We hit the bottom, so we're done. */
1510  UnlockReleaseBuffer(buffer);
1511  break;
1512  }
1513 
1514  /*
1515  * Pick the first downlink on the page, and follow it. It doesn't
1516  * matter which downlink we choose, the tree has the same depth
1517  * everywhere, so we just pick the first one.
1518  */
1519  itup = (IndexTuple) PageGetItem(page,
1521  blkno = ItemPointerGetBlockNumber(&(itup->t_tid));
1522  UnlockReleaseBuffer(buffer);
1523 
1524  /*
1525  * We're going down on the tree. It means that there is yet one more
1526  * level in the tree.
1527  */
1528  maxLevel++;
1529  }
1530  return maxLevel;
1531 }
1532 
1533 
1534 /*
1535  * Routines for managing the parent map.
1536  *
1537  * Whenever a page is split, we need to insert the downlinks into the parent.
1538  * We need to somehow find the parent page to do that. In normal insertions,
1539  * we keep a stack of nodes visited when we descend the tree. However, in
1540  * buffering build, we can start descending the tree from any internal node,
1541  * when we empty a buffer by cascading tuples to its children. So we don't
1542  * have a full stack up to the root available at that time.
1543  *
1544  * So instead, we maintain a hash table to track the parent of every internal
1545  * page. We don't need to track the parents of leaf nodes, however. Whenever
1546  * we insert to a leaf, we've just descended down from its parent, so we know
1547  * its immediate parent already. This helps a lot to limit the memory used
1548  * by this hash table.
1549  *
1550  * Whenever an internal node is split, the parent map needs to be updated.
1551  * the parent of the new child page needs to be recorded, and also the
1552  * entries for all page whose downlinks are moved to a new page at the split
1553  * needs to be updated.
1554  *
1555  * We also update the parent map whenever we descend the tree. That might seem
1556  * unnecessary, because we maintain the map whenever a downlink is moved or
1557  * created, but it is needed because we switch to buffering mode after
1558  * creating a tree with regular index inserts. Any pages created before
1559  * switching to buffering mode will not be present in the parent map initially,
1560  * but will be added there the first time we visit them.
1561  */
1562 
1563 typedef struct
1564 {
1565  BlockNumber childblkno; /* hash key */
1567 } ParentMapEntry;
1568 
1569 static void
1571 {
1572  HASHCTL hashCtl;
1573 
1574  hashCtl.keysize = sizeof(BlockNumber);
1575  hashCtl.entrysize = sizeof(ParentMapEntry);
1576  hashCtl.hcxt = CurrentMemoryContext;
1577  buildstate->parentMap = hash_create("gistbuild parent map",
1578  1024,
1579  &hashCtl,
1581 }
1582 
1583 static void
1585 {
1586  ParentMapEntry *entry;
1587  bool found;
1588 
1589  entry = (ParentMapEntry *) hash_search(buildstate->parentMap,
1590  (const void *) &child,
1591  HASH_ENTER,
1592  &found);
1593  entry->parentblkno = parent;
1594 }
1595 
1596 /*
1597  * Scan all downlinks on a page, and memorize their parent.
1598  */
1599 static void
1601 {
1602  OffsetNumber maxoff;
1603  OffsetNumber off;
1604  BlockNumber parentblkno = BufferGetBlockNumber(parentbuf);
1605  Page page = BufferGetPage(parentbuf);
1606 
1607  Assert(!GistPageIsLeaf(page));
1608 
1609  maxoff = PageGetMaxOffsetNumber(page);
1610  for (off = FirstOffsetNumber; off <= maxoff; off++)
1611  {
1612  ItemId iid = PageGetItemId(page, off);
1613  IndexTuple idxtuple = (IndexTuple) PageGetItem(page, iid);
1614  BlockNumber childblkno = ItemPointerGetBlockNumber(&(idxtuple->t_tid));
1615 
1616  gistMemorizeParent(buildstate, childblkno, parentblkno);
1617  }
1618 }
1619 
1620 static BlockNumber
1622 {
1623  ParentMapEntry *entry;
1624  bool found;
1625 
1626  /* Find node buffer in hash table */
1627  entry = (ParentMapEntry *) hash_search(buildstate->parentMap,
1628  (const void *) &child,
1629  HASH_FIND,
1630  &found);
1631  if (!found)
1632  elog(ERROR, "could not find parent of block %u in lookup table", child);
1633 
1634  return entry->parentblkno;
1635 }
uint32 BlockNumber
Definition: block.h:31
#define InvalidBlockNumber
Definition: block.h:33
static Datum values[MAXATTR]
Definition: bootstrap.c:156
int Buffer
Definition: buf.h:23
#define InvalidBuffer
Definition: buf.h:25
BlockNumber BufferGetBlockNumber(Buffer buffer)
Definition: bufmgr.c:2763
void UnlockReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3954
void MarkBufferDirty(Buffer buffer)
Definition: bufmgr.c:1583
void LockBuffer(Buffer buffer, int mode)
Definition: bufmgr.c:4172
Buffer ReadBuffer(Relation reln, BlockNumber blockNum)
Definition: bufmgr.c:712
#define RelationGetNumberOfBlocks(reln)
Definition: bufmgr.h:156
static Page BufferGetPage(Buffer buffer)
Definition: bufmgr.h:280
void PageSetChecksumInplace(Page page, BlockNumber blkno)
Definition: bufpage.c:1539
Size PageGetFreeSpace(Page page)
Definition: bufpage.c:907
Pointer Page
Definition: bufpage.h:78
static Item PageGetItem(Page page, ItemId itemId)
Definition: bufpage.h:351
#define SizeOfPageHeaderData
Definition: bufpage.h:213
static ItemId PageGetItemId(Page page, OffsetNumber offsetNumber)
Definition: bufpage.h:240
static void PageSetLSN(Page page, XLogRecPtr lsn)
Definition: bufpage.h:388
static OffsetNumber PageGetMaxOffsetNumber(Page page)
Definition: bufpage.h:369
#define PageAddItem(page, item, size, offsetNumber, overwrite, is_heap)
Definition: bufpage.h:468
unsigned short uint16
Definition: c.h:441
#define MAXALIGN(LEN)
Definition: c.h:747
#define VARHDRSZ
Definition: c.h:628
#define OidIsValid(objectId)
Definition: c.h:711
size_t Size
Definition: c.h:541
int effective_cache_size
Definition: costsize.c:129
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:953
HTAB * hash_create(const char *tabname, long nelem, const HASHCTL *info, int flags)
Definition: dynahash.c:350
#define DEBUG2
Definition: elog.h:25
#define DEBUG1
Definition: elog.h:26
#define ERROR
Definition: elog.h:35
void gistdoinsert(Relation r, IndexTuple itup, Size freespace, GISTSTATE *giststate, Relation heapRel, bool is_build)
Definition: gist.c:632
bool gistplacetopage(Relation rel, Size freespace, GISTSTATE *giststate, Buffer buffer, IndexTuple *itup, int ntup, OffsetNumber oldoffnum, BlockNumber *newblkno, Buffer leftchildbuf, List **splitinfo, bool markfollowright, Relation heapRel, bool is_build)
Definition: gist.c:223
SplitedPageLayout * gistSplit(Relation r, Page page, IndexTuple *itup, int len, GISTSTATE *giststate)
Definition: gist.c:1416
GISTSTATE * initGISTstate(Relation index)
Definition: gist.c:1503
MemoryContext createTempGistContext(void)
Definition: gist.c:120
void freeGISTstate(GISTSTATE *giststate)
Definition: gist.c:1631
#define F_LEAF
Definition: gist.h:46
#define GIST_SORTSUPPORT_PROC
Definition: gist.h:40
struct GISTPageOpaqueData GISTPageOpaqueData
#define GistPageIsLeaf(page)
Definition: gist.h:167
#define GistPageGetOpaque(page)
Definition: gist.h:165
#define GistBuildLSN
Definition: gist.h:67
#define LEVEL_HAS_BUFFERS(nlevel, gfbb)
Definition: gist_private.h:319
@ GIST_OPTION_BUFFERING_OFF
Definition: gist_private.h:388
@ GIST_OPTION_BUFFERING_ON
Definition: gist_private.h:387
#define GIST_ROOT_BLKNO
Definition: gist_private.h:262
#define GIST_DEFAULT_FILLFACTOR
Definition: gist_private.h:479
#define BUFFER_OVERFLOWED(nodeBuffer, gfbb)
Definition: gist_private.h:332
#define GIST_EXCLUSIVE
Definition: gist_private.h:43
#define GIST_SHARE
Definition: gist_private.h:42
GistBuildMode
Definition: gistbuild.c:68
@ GIST_BUFFERING_AUTO
Definition: gistbuild.c:72
@ GIST_SORTED_BUILD
Definition: gistbuild.c:69
@ GIST_BUFFERING_ACTIVE
Definition: gistbuild.c:78
@ GIST_BUFFERING_STATS
Definition: gistbuild.c:75
@ GIST_BUFFERING_DISABLED
Definition: gistbuild.c:70
static BlockNumber gistbufferinginserttuples(GISTBuildState *buildstate, Buffer buffer, int level, IndexTuple *itup, int ntup, OffsetNumber oldoffnum, BlockNumber parentblk, OffsetNumber downlinkoffnum)
Definition: gistbuild.c:1110
static void gistMemorizeAllDownlinks(GISTBuildState *buildstate, Buffer parentbuf)
Definition: gistbuild.c:1600
static bool gistProcessItup(GISTBuildState *buildstate, IndexTuple itup, BlockNumber startblkno, int startlevel)
Definition: gistbuild.c:979
static void gist_indexsortbuild_levelstate_flush(GISTBuildState *state, GistSortedBuildLevelState *levelstate)
Definition: gistbuild.c:522
#define BUFFERING_MODE_SWITCH_CHECK_STEP
Definition: gistbuild.c:52
static Buffer gistBufferingFindCorrectParent(GISTBuildState *buildstate, BlockNumber childblkno, int level, BlockNumber *parentblkno, OffsetNumber *downlinkoffnum)
Definition: gistbuild.c:1279
static int calculatePagesPerBuffer(GISTBuildState *buildstate, int levelStep)
Definition: gistbuild.c:852
static void gist_indexsortbuild_levelstate_add(GISTBuildState *state, GistSortedBuildLevelState *levelstate, IndexTuple itup)
Definition: gistbuild.c:490
static void gist_indexsortbuild(GISTBuildState *state)
Definition: gistbuild.c:404
static void gistInitParentMap(GISTBuildState *buildstate)
Definition: gistbuild.c:1570
static void gistBuildCallback(Relation index, ItemPointer tid, Datum *values, bool *isnull, bool tupleIsAlive, void *state)
Definition: gistbuild.c:885
static void gistSortedBuildCallback(Relation index, ItemPointer tid, Datum *values, bool *isnull, bool tupleIsAlive, void *state)
Definition: gistbuild.c:370
static void gistMemorizeParent(GISTBuildState *buildstate, BlockNumber child, BlockNumber parent)
Definition: gistbuild.c:1584
#define GIST_SORTED_BUILD_PAGE_NUM
Definition: gistbuild.c:116
static void gistEmptyAllBuffers(GISTBuildState *buildstate)
Definition: gistbuild.c:1426
#define BUFFERING_MODE_TUPLE_SIZE_STATS_TARGET
Definition: gistbuild.c:60
static void gistInitBuffering(GISTBuildState *buildstate)
Definition: gistbuild.c:691
static void gist_indexsortbuild_flush_ready_pages(GISTBuildState *state)
Definition: gistbuild.c:644
static void gistBufferingBuildInsert(GISTBuildState *buildstate, IndexTuple itup)
Definition: gistbuild.c:963
IndexBuildResult * gistbuild(Relation heap, Relation index, IndexInfo *indexInfo)
Definition: gistbuild.c:183
static BlockNumber gistGetParent(GISTBuildState *buildstate, BlockNumber child)
Definition: gistbuild.c:1621
static int gistGetMaxLevel(Relation index)
Definition: gistbuild.c:1481
struct GistSortedBuildLevelState GistSortedBuildLevelState
static void gistProcessEmptyingQueue(GISTBuildState *buildstate)
Definition: gistbuild.c:1353
void gistPushItupToNodeBuffer(GISTBuildBuffers *gfbb, GISTNodeBuffer *nodeBuffer, IndexTuple itup)
void gistRelocateBuildBuffersOnSplit(GISTBuildBuffers *gfbb, GISTSTATE *giststate, Relation r, int level, Buffer buffer, List *splitinfo)
GISTBuildBuffers * gistInitBuildBuffers(int pagesPerBuffer, int levelStep, int maxLevel)
void gistFreeBuildBuffers(GISTBuildBuffers *gfbb)
GISTNodeBuffer * gistGetNodeBuffer(GISTBuildBuffers *gfbb, GISTSTATE *giststate, BlockNumber nodeBlocknum, int level)
bool gistPopItupFromNodeBuffer(GISTBuildBuffers *gfbb, GISTNodeBuffer *nodeBuffer, IndexTuple *itup)
void gistUnloadNodeBuffers(GISTBuildBuffers *gfbb)
IndexTuple gistFormTuple(GISTSTATE *giststate, Relation r, Datum *attdata, bool *isnull, bool isleaf)
Definition: gistutil.c:575
Buffer gistNewBuffer(Relation r)
Definition: gistutil.c:824
void gistfillbuffer(Page page, IndexTuple *itup, int len, OffsetNumber off)
Definition: gistutil.c:34
IndexTuple * gistextractpage(Page page, int *len)
Definition: gistutil.c:95
IndexTuple gistgetadjusted(Relation r, IndexTuple oldtup, IndexTuple addtup, GISTSTATE *giststate)
Definition: gistutil.c:316
OffsetNumber gistchoose(Relation r, Page p, IndexTuple it, GISTSTATE *giststate)
Definition: gistutil.c:374
IndexTuple * gistjoinvector(IndexTuple *itvec, int *len, IndexTuple *additvec, int addlen)
Definition: gistutil.c:114
void gistinitpage(Page page, uint32 f)
Definition: gistutil.c:757
IndexTuple gistunion(Relation r, IndexTuple *itvec, int len, GISTSTATE *giststate)
Definition: gistutil.c:219
void GISTInitBuffer(Buffer b, uint32 f)
Definition: gistutil.c:773
IndexTupleData * gistfillitupvec(IndexTuple *vec, int veclen, int *memlen)
Definition: gistutil.c:127
void gistCompressValues(GISTSTATE *giststate, Relation r, Datum *attdata, bool *isnull, bool isleaf, Datum *compatt)
Definition: gistutil.c:596
void gistcheckpage(Relation rel, Buffer buf)
Definition: gistutil.c:785
int maintenance_work_mem
Definition: globals.c:127
@ HASH_FIND
Definition: hsearch.h:113
@ HASH_ENTER
Definition: hsearch.h:114
#define HASH_CONTEXT
Definition: hsearch.h:102
#define HASH_ELEM
Definition: hsearch.h:95
#define HASH_BLOBS
Definition: hsearch.h:97
RegProcedure index_getprocid(Relation irel, AttrNumber attnum, uint16 procnum)
Definition: indexam.c:777
int i
Definition: isn.c:73
if(TABLE==NULL||TABLE_index==NULL)
Definition: isn.c:77
Pointer Item
Definition: item.h:17
struct ItemIdData ItemIdData
static void ItemPointerSetBlockNumber(ItemPointerData *pointer, BlockNumber blockNumber)
Definition: itemptr.h:147
static BlockNumber ItemPointerGetBlockNumber(const ItemPointerData *pointer)
Definition: itemptr.h:103
IndexTupleData * IndexTuple
Definition: itup.h:53
#define IndexTupleSize(itup)
Definition: itup.h:70
Assert(fmt[strlen(fmt) - 1] !='\n')
List * list_delete_first(List *list)
Definition: list.c:942
List * lcons(void *datum, List *list)
Definition: list.c:494
void list_free_deep(List *list)
Definition: list.c:1559
void MemoryContextReset(MemoryContext context)
Definition: mcxt.c:303
void pfree(void *pointer)
Definition: mcxt.c:1306
void * palloc0(Size size)
Definition: mcxt.c:1230
MemoryContext CurrentMemoryContext
Definition: mcxt.c:124
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:376
void * palloc(Size size)
Definition: mcxt.c:1199
#define START_CRIT_SECTION()
Definition: miscadmin.h:148
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:121
#define END_CRIT_SECTION()
Definition: miscadmin.h:150
#define InvalidOffsetNumber
Definition: off.h:26
#define OffsetNumberNext(offsetNumber)
Definition: off.h:52
uint16 OffsetNumber
Definition: off.h:24
#define FirstOffsetNumber
Definition: off.h:27
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:135
#define INDEX_MAX_KEYS
const void * data
#define lfirst(lc)
Definition: pg_list.h:170
static int list_length(const List *l)
Definition: pg_list.h:150
#define NIL
Definition: pg_list.h:66
#define linitial(l)
Definition: pg_list.h:176
int fillfactor
Definition: pgbench.c:196
uintptr_t Datum
Definition: postgres.h:412
unsigned int Oid
Definition: postgres_ext.h:31
static SMgrRelation RelationGetSmgr(Relation rel)
Definition: rel.h:569
#define RelationGetRelationName(relation)
Definition: rel.h:535
#define RelationNeedsWAL(relation)
Definition: rel.h:626
#define IndexRelationGetNumberOfKeyAttributes(relation)
Definition: rel.h:520
@ MAIN_FORKNUM
Definition: relpath.h:50
BlockNumber smgrnblocks(SMgrRelation reln, ForkNumber forknum)
Definition: smgr.c:579
void smgrwrite(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum, char *buffer, bool skipFsync)
Definition: smgr.c:554
void smgrextend(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum, char *buffer, bool skipFsync)
Definition: smgr.c:493
void smgrimmedsync(SMgrRelation reln, ForkNumber forknum)
Definition: smgr.c:691
List * bufferEmptyingQueue
Definition: gist_private.h:357
List ** buffersOnLevels
Definition: gist_private.h:368
MemoryContext context
Definition: gist_private.h:341
GISTBuildBuffers * gfbb
Definition: gistbuild.c:100
BlockNumber pages_allocated
Definition: gistbuild.c:108
int ready_num_pages
Definition: gistbuild.c:111
Relation indexrel
Definition: gistbuild.c:84
GISTSTATE * giststate
Definition: gistbuild.c:86
HTAB * parentMap
Definition: gistbuild.c:101
int64 indtuples
Definition: gistbuild.c:92
Size freespace
Definition: gistbuild.c:88
Relation heaprel
Definition: gistbuild.c:85
int64 indtuplesSize
Definition: gistbuild.c:99
BlockNumber pages_written
Definition: gistbuild.c:109
Tuplesortstate * sortstate
Definition: gistbuild.c:106
GistBuildMode buildMode
Definition: gistbuild.c:90
BlockNumber nodeBlocknum
Definition: gist_private.h:300
bool queuedForEmptying
Definition: gist_private.h:307
IndexTuple downlink
Definition: gist_private.h:422
MemoryContext tempCxt
Definition: gist_private.h:78
Page pages[GIST_SORTED_BUILD_PAGE_NUM]
Definition: gistbuild.c:131
struct GistSortedBuildLevelState * parent
Definition: gistbuild.c:130
Size keysize
Definition: hsearch.h:75
Size entrysize
Definition: hsearch.h:76
MemoryContext hcxt
Definition: hsearch.h:86
Definition: dynahash.c:220
double heap_tuples
Definition: genam.h:32
double index_tuples
Definition: genam.h:33
ItemPointerData t_tid
Definition: itup.h:37
Definition: pg_list.h:52
BlockNumber parentblkno
Definition: gistbuild.c:1566
BlockNumber childblkno
Definition: gistbuild.c:1565
gistxlogPage block
Definition: gist_private.h:193
IndexTupleData * list
Definition: gist_private.h:194
struct SplitedPageLayout * next
Definition: gist_private.h:200
Definition: type.h:95
Definition: regguts.h:318
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:1748
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
void tuplesort_performsort(Tuplesortstate *state)
Definition: tuplesort.c:1385
void tuplesort_end(Tuplesortstate *state)
Definition: tuplesort.c:972
#define TUPLESORT_NONE
Definition: tuplesort.h:92
IndexTuple tuplesort_getindextuple(Tuplesortstate *state, bool forward)
Tuplesortstate * tuplesort_begin_index_gist(Relation heapRel, Relation indexRel, int workMem, SortCoordinate coordinate, int sortopt)
void tuplesort_putindextuplevalues(Tuplesortstate *state, Relation rel, ItemPointer self, Datum *values, bool *isnull)
XLogRecPtr log_newpage(RelFileLocator *rlocator, ForkNumber forknum, BlockNumber blkno, Page page, bool page_std)
Definition: xloginsert.c:1097
void log_newpages(RelFileLocator *rlocator, ForkNumber forknum, int num_pages, BlockNumber *blknos, Page *pages, bool page_std)
Definition: xloginsert.c:1129
void log_newpage_range(Relation rel, ForkNumber forknum, BlockNumber startblk, BlockNumber endblk, bool page_std)
Definition: xloginsert.c:1224
#define XLR_MAX_BLOCK_ID
Definition: xlogrecord.h:228