PostgreSQL Source Code  git master
nbtree.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * nbtree.c
4  * Implementation of Lehman and Yao's btree management algorithm for
5  * Postgres.
6  *
7  * NOTES
8  * This file contains only the public interface routines.
9  *
10  *
11  * Portions Copyright (c) 1996-2024, PostgreSQL Global Development Group
12  * Portions Copyright (c) 1994, Regents of the University of California
13  *
14  * IDENTIFICATION
15  * src/backend/access/nbtree/nbtree.c
16  *
17  *-------------------------------------------------------------------------
18  */
19 #include "postgres.h"
20 
21 #include "access/nbtree.h"
22 #include "access/relscan.h"
23 #include "access/xloginsert.h"
24 #include "commands/progress.h"
25 #include "commands/vacuum.h"
26 #include "miscadmin.h"
27 #include "nodes/execnodes.h"
28 #include "pgstat.h"
29 #include "storage/bulk_write.h"
31 #include "storage/indexfsm.h"
32 #include "storage/ipc.h"
33 #include "storage/lmgr.h"
34 #include "storage/smgr.h"
35 #include "utils/fmgrprotos.h"
36 #include "utils/index_selfuncs.h"
37 #include "utils/memutils.h"
38 
39 
40 /*
41  * BTPARALLEL_NOT_INITIALIZED indicates that the scan has not started.
42  *
43  * BTPARALLEL_ADVANCING indicates that some process is advancing the scan to
44  * a new page; others must wait.
45  *
46  * BTPARALLEL_IDLE indicates that no backend is currently advancing the scan
47  * to a new page; some process can start doing that.
48  *
49  * BTPARALLEL_DONE indicates that the scan is complete (including error exit).
50  * We reach this state once for every distinct combination of array keys.
51  */
52 typedef enum
53 {
58 } BTPS_State;
59 
60 /*
61  * BTParallelScanDescData contains btree specific shared information required
62  * for parallel scan.
63  */
64 typedef struct BTParallelScanDescData
65 {
66  BlockNumber btps_scanPage; /* latest or next page to be scanned */
67  BTPS_State btps_pageStatus; /* indicates whether next page is
68  * available for scan. see above for
69  * possible states of parallel scan. */
70  int btps_arrayKeyCount; /* count indicating number of array scan
71  * keys processed by parallel scan */
72  slock_t btps_mutex; /* protects above variables */
73  ConditionVariable btps_cv; /* used to synchronize parallel scan */
75 
77 
78 
79 static void btvacuumscan(IndexVacuumInfo *info, IndexBulkDeleteResult *stats,
80  IndexBulkDeleteCallback callback, void *callback_state,
81  BTCycleId cycleid);
82 static void btvacuumpage(BTVacState *vstate, BlockNumber scanblkno);
84  IndexTuple posting,
85  OffsetNumber updatedoffset,
86  int *nremaining);
87 
88 
89 /*
90  * Btree handler function: return IndexAmRoutine with access method parameters
91  * and callbacks.
92  */
93 Datum
95 {
97 
98  amroutine->amstrategies = BTMaxStrategyNumber;
99  amroutine->amsupport = BTNProcs;
100  amroutine->amoptsprocnum = BTOPTIONS_PROC;
101  amroutine->amcanorder = true;
102  amroutine->amcanorderbyop = false;
103  amroutine->amcanbackward = true;
104  amroutine->amcanunique = true;
105  amroutine->amcanmulticol = true;
106  amroutine->amoptionalkey = true;
107  amroutine->amsearcharray = true;
108  amroutine->amsearchnulls = true;
109  amroutine->amstorage = false;
110  amroutine->amclusterable = true;
111  amroutine->ampredlocks = true;
112  amroutine->amcanparallel = true;
113  amroutine->amcanbuildparallel = true;
114  amroutine->amcaninclude = true;
115  amroutine->amusemaintenanceworkmem = false;
116  amroutine->amsummarizing = false;
117  amroutine->amparallelvacuumoptions =
119  amroutine->amkeytype = InvalidOid;
120 
121  amroutine->ambuild = btbuild;
122  amroutine->ambuildempty = btbuildempty;
123  amroutine->aminsert = btinsert;
124  amroutine->aminsertcleanup = NULL;
125  amroutine->ambulkdelete = btbulkdelete;
126  amroutine->amvacuumcleanup = btvacuumcleanup;
127  amroutine->amcanreturn = btcanreturn;
128  amroutine->amcostestimate = btcostestimate;
129  amroutine->amoptions = btoptions;
130  amroutine->amproperty = btproperty;
131  amroutine->ambuildphasename = btbuildphasename;
132  amroutine->amvalidate = btvalidate;
133  amroutine->amadjustmembers = btadjustmembers;
134  amroutine->ambeginscan = btbeginscan;
135  amroutine->amrescan = btrescan;
136  amroutine->amgettuple = btgettuple;
137  amroutine->amgetbitmap = btgetbitmap;
138  amroutine->amendscan = btendscan;
139  amroutine->ammarkpos = btmarkpos;
140  amroutine->amrestrpos = btrestrpos;
143  amroutine->amparallelrescan = btparallelrescan;
144 
145  PG_RETURN_POINTER(amroutine);
146 }
147 
148 /*
149  * btbuildempty() -- build an empty btree index in the initialization fork
150  */
151 void
153 {
154  bool allequalimage = _bt_allequalimage(index, false);
155  BulkWriteState *bulkstate;
156  BulkWriteBuffer metabuf;
157 
158  bulkstate = smgr_bulk_start_rel(index, INIT_FORKNUM);
159 
160  /* Construct metapage. */
161  metabuf = smgr_bulk_get_buf(bulkstate);
162  _bt_initmetapage((Page) metabuf, P_NONE, 0, allequalimage);
163  smgr_bulk_write(bulkstate, BTREE_METAPAGE, metabuf, true);
164 
165  smgr_bulk_finish(bulkstate);
166 }
167 
168 /*
169  * btinsert() -- insert an index tuple into a btree.
170  *
171  * Descend the tree recursively, find the appropriate location for our
172  * new tuple, and put it there.
173  */
174 bool
175 btinsert(Relation rel, Datum *values, bool *isnull,
176  ItemPointer ht_ctid, Relation heapRel,
177  IndexUniqueCheck checkUnique,
178  bool indexUnchanged,
179  IndexInfo *indexInfo)
180 {
181  bool result;
182  IndexTuple itup;
183 
184  /* generate an index tuple */
185  itup = index_form_tuple(RelationGetDescr(rel), values, isnull);
186  itup->t_tid = *ht_ctid;
187 
188  result = _bt_doinsert(rel, itup, checkUnique, indexUnchanged, heapRel);
189 
190  pfree(itup);
191 
192  return result;
193 }
194 
195 /*
196  * btgettuple() -- Get the next tuple in the scan.
197  */
198 bool
200 {
201  BTScanOpaque so = (BTScanOpaque) scan->opaque;
202  bool res;
203 
204  /* btree indexes are never lossy */
205  scan->xs_recheck = false;
206 
207  /*
208  * If we have any array keys, initialize them during first call for a
209  * scan. We can't do this in btrescan because we don't know the scan
210  * direction at that time.
211  */
212  if (so->numArrayKeys && !BTScanPosIsValid(so->currPos))
213  {
214  /* punt if we have any unsatisfiable array keys */
215  if (so->numArrayKeys < 0)
216  return false;
217 
218  _bt_start_array_keys(scan, dir);
219  }
220 
221  /* This loop handles advancing to the next array elements, if any */
222  do
223  {
224  /*
225  * If we've already initialized this scan, we can just advance it in
226  * the appropriate direction. If we haven't done so yet, we call
227  * _bt_first() to get the first item in the scan.
228  */
229  if (!BTScanPosIsValid(so->currPos))
230  res = _bt_first(scan, dir);
231  else
232  {
233  /*
234  * Check to see if we should kill the previously-fetched tuple.
235  */
236  if (scan->kill_prior_tuple)
237  {
238  /*
239  * Yes, remember it for later. (We'll deal with all such
240  * tuples at once right before leaving the index page.) The
241  * test for numKilled overrun is not just paranoia: if the
242  * caller reverses direction in the indexscan then the same
243  * item might get entered multiple times. It's not worth
244  * trying to optimize that, so we don't detect it, but instead
245  * just forget any excess entries.
246  */
247  if (so->killedItems == NULL)
248  so->killedItems = (int *)
249  palloc(MaxTIDsPerBTreePage * sizeof(int));
250  if (so->numKilled < MaxTIDsPerBTreePage)
251  so->killedItems[so->numKilled++] = so->currPos.itemIndex;
252  }
253 
254  /*
255  * Now continue the scan.
256  */
257  res = _bt_next(scan, dir);
258  }
259 
260  /* If we have a tuple, return it ... */
261  if (res)
262  break;
263  /* ... otherwise see if we have more array keys to deal with */
264  } while (so->numArrayKeys && _bt_advance_array_keys(scan, dir));
265 
266  return res;
267 }
268 
269 /*
270  * btgetbitmap() -- gets all matching tuples, and adds them to a bitmap
271  */
272 int64
274 {
275  BTScanOpaque so = (BTScanOpaque) scan->opaque;
276  int64 ntids = 0;
277  ItemPointer heapTid;
278 
279  /*
280  * If we have any array keys, initialize them.
281  */
282  if (so->numArrayKeys)
283  {
284  /* punt if we have any unsatisfiable array keys */
285  if (so->numArrayKeys < 0)
286  return ntids;
287 
289  }
290 
291  /* This loop handles advancing to the next array elements, if any */
292  do
293  {
294  /* Fetch the first page & tuple */
295  if (_bt_first(scan, ForwardScanDirection))
296  {
297  /* Save tuple ID, and continue scanning */
298  heapTid = &scan->xs_heaptid;
299  tbm_add_tuples(tbm, heapTid, 1, false);
300  ntids++;
301 
302  for (;;)
303  {
304  /*
305  * Advance to next tuple within page. This is the same as the
306  * easy case in _bt_next().
307  */
308  if (++so->currPos.itemIndex > so->currPos.lastItem)
309  {
310  /* let _bt_next do the heavy lifting */
311  if (!_bt_next(scan, ForwardScanDirection))
312  break;
313  }
314 
315  /* Save tuple ID, and continue scanning */
316  heapTid = &so->currPos.items[so->currPos.itemIndex].heapTid;
317  tbm_add_tuples(tbm, heapTid, 1, false);
318  ntids++;
319  }
320  }
321  /* Now see if we have more array keys to deal with */
323 
324  return ntids;
325 }
326 
327 /*
328  * btbeginscan() -- start a scan on a btree index
329  */
331 btbeginscan(Relation rel, int nkeys, int norderbys)
332 {
333  IndexScanDesc scan;
334  BTScanOpaque so;
335 
336  /* no order by operators allowed */
337  Assert(norderbys == 0);
338 
339  /* get the scan */
340  scan = RelationGetIndexScan(rel, nkeys, norderbys);
341 
342  /* allocate private workspace */
343  so = (BTScanOpaque) palloc(sizeof(BTScanOpaqueData));
346  if (scan->numberOfKeys > 0)
347  so->keyData = (ScanKey) palloc(scan->numberOfKeys * sizeof(ScanKeyData));
348  else
349  so->keyData = NULL;
350 
351  so->arrayKeyData = NULL; /* assume no array keys for now */
352  so->arraysStarted = false;
353  so->numArrayKeys = 0;
354  so->arrayKeys = NULL;
355  so->arrayContext = NULL;
356 
357  so->killedItems = NULL; /* until needed */
358  so->numKilled = 0;
359 
360  /*
361  * We don't know yet whether the scan will be index-only, so we do not
362  * allocate the tuple workspace arrays until btrescan. However, we set up
363  * scan->xs_itupdesc whether we'll need it or not, since that's so cheap.
364  */
365  so->currTuples = so->markTuples = NULL;
366 
367  scan->xs_itupdesc = RelationGetDescr(rel);
368 
369  scan->opaque = so;
370 
371  return scan;
372 }
373 
374 /*
375  * btrescan() -- rescan an index relation
376  */
377 void
378 btrescan(IndexScanDesc scan, ScanKey scankey, int nscankeys,
379  ScanKey orderbys, int norderbys)
380 {
381  BTScanOpaque so = (BTScanOpaque) scan->opaque;
382 
383  /* we aren't holding any read locks, but gotta drop the pins */
385  {
386  /* Before leaving current page, deal with any killed items */
387  if (so->numKilled > 0)
388  _bt_killitems(scan);
391  }
392 
393  so->markItemIndex = -1;
394  so->arrayKeyCount = 0;
397 
398  /*
399  * Allocate tuple workspace arrays, if needed for an index-only scan and
400  * not already done in a previous rescan call. To save on palloc
401  * overhead, both workspaces are allocated as one palloc block; only this
402  * function and btendscan know that.
403  *
404  * NOTE: this data structure also makes it safe to return data from a
405  * "name" column, even though btree name_ops uses an underlying storage
406  * datatype of cstring. The risk there is that "name" is supposed to be
407  * padded to NAMEDATALEN, but the actual index tuple is probably shorter.
408  * However, since we only return data out of tuples sitting in the
409  * currTuples array, a fetch of NAMEDATALEN bytes can at worst pull some
410  * data out of the markTuples array --- running off the end of memory for
411  * a SIGSEGV is not possible. Yeah, this is ugly as sin, but it beats
412  * adding special-case treatment for name_ops elsewhere.
413  */
414  if (scan->xs_want_itup && so->currTuples == NULL)
415  {
416  so->currTuples = (char *) palloc(BLCKSZ * 2);
417  so->markTuples = so->currTuples + BLCKSZ;
418  }
419 
420  /*
421  * Reset the scan keys
422  */
423  if (scankey && scan->numberOfKeys > 0)
424  memmove(scan->keyData,
425  scankey,
426  scan->numberOfKeys * sizeof(ScanKeyData));
427  so->numberOfKeys = 0; /* until _bt_preprocess_keys sets it */
428 
429  /* If any keys are SK_SEARCHARRAY type, set up array-key info */
431 }
432 
433 /*
434  * btendscan() -- close down a scan
435  */
436 void
438 {
439  BTScanOpaque so = (BTScanOpaque) scan->opaque;
440 
441  /* we aren't holding any read locks, but gotta drop the pins */
443  {
444  /* Before leaving current page, deal with any killed items */
445  if (so->numKilled > 0)
446  _bt_killitems(scan);
448  }
449 
450  so->markItemIndex = -1;
452 
453  /* No need to invalidate positions, the RAM is about to be freed. */
454 
455  /* Release storage */
456  if (so->keyData != NULL)
457  pfree(so->keyData);
458  /* so->arrayKeyData and so->arrayKeys are in arrayContext */
459  if (so->arrayContext != NULL)
461  if (so->killedItems != NULL)
462  pfree(so->killedItems);
463  if (so->currTuples != NULL)
464  pfree(so->currTuples);
465  /* so->markTuples should not be pfree'd, see btrescan */
466  pfree(so);
467 }
468 
469 /*
470  * btmarkpos() -- save current scan position
471  */
472 void
474 {
475  BTScanOpaque so = (BTScanOpaque) scan->opaque;
476 
477  /* There may be an old mark with a pin (but no lock). */
479 
480  /*
481  * Just record the current itemIndex. If we later step to next page
482  * before releasing the marked position, _bt_steppage makes a full copy of
483  * the currPos struct in markPos. If (as often happens) the mark is moved
484  * before we leave the page, we don't have to do that work.
485  */
486  if (BTScanPosIsValid(so->currPos))
487  so->markItemIndex = so->currPos.itemIndex;
488  else
489  {
491  so->markItemIndex = -1;
492  }
493 
494  /* Also record the current positions of any array keys */
495  if (so->numArrayKeys)
496  _bt_mark_array_keys(scan);
497 }
498 
499 /*
500  * btrestrpos() -- restore scan to last saved position
501  */
502 void
504 {
505  BTScanOpaque so = (BTScanOpaque) scan->opaque;
506 
507  /* Restore the marked positions of any array keys */
508  if (so->numArrayKeys)
510 
511  if (so->markItemIndex >= 0)
512  {
513  /*
514  * The scan has never moved to a new page since the last mark. Just
515  * restore the itemIndex.
516  *
517  * NB: In this case we can't count on anything in so->markPos to be
518  * accurate.
519  */
520  so->currPos.itemIndex = so->markItemIndex;
521  }
522  else
523  {
524  /*
525  * The scan moved to a new page after last mark or restore, and we are
526  * now restoring to the marked page. We aren't holding any read
527  * locks, but if we're still holding the pin for the current position,
528  * we must drop it.
529  */
530  if (BTScanPosIsValid(so->currPos))
531  {
532  /* Before leaving current page, deal with any killed items */
533  if (so->numKilled > 0)
534  _bt_killitems(scan);
536  }
537 
538  if (BTScanPosIsValid(so->markPos))
539  {
540  /* bump pin on mark buffer for assignment to current buffer */
541  if (BTScanPosIsPinned(so->markPos))
543  memcpy(&so->currPos, &so->markPos,
544  offsetof(BTScanPosData, items[1]) +
545  so->markPos.lastItem * sizeof(BTScanPosItem));
546  if (so->currTuples)
547  memcpy(so->currTuples, so->markTuples,
549  }
550  else
552  }
553 }
554 
555 /*
556  * btestimateparallelscan -- estimate storage for BTParallelScanDescData
557  */
558 Size
560 {
561  return sizeof(BTParallelScanDescData);
562 }
563 
564 /*
565  * btinitparallelscan -- initialize BTParallelScanDesc for parallel btree scan
566  */
567 void
568 btinitparallelscan(void *target)
569 {
570  BTParallelScanDesc bt_target = (BTParallelScanDesc) target;
571 
572  SpinLockInit(&bt_target->btps_mutex);
573  bt_target->btps_scanPage = InvalidBlockNumber;
575  bt_target->btps_arrayKeyCount = 0;
576  ConditionVariableInit(&bt_target->btps_cv);
577 }
578 
579 /*
580  * btparallelrescan() -- reset parallel scan
581  */
582 void
584 {
585  BTParallelScanDesc btscan;
586  ParallelIndexScanDesc parallel_scan = scan->parallel_scan;
587 
588  Assert(parallel_scan);
589 
590  btscan = (BTParallelScanDesc) OffsetToPointer((void *) parallel_scan,
591  parallel_scan->ps_offset);
592 
593  /*
594  * In theory, we don't need to acquire the spinlock here, because there
595  * shouldn't be any other workers running at this point, but we do so for
596  * consistency.
597  */
598  SpinLockAcquire(&btscan->btps_mutex);
601  btscan->btps_arrayKeyCount = 0;
602  SpinLockRelease(&btscan->btps_mutex);
603 }
604 
605 /*
606  * _bt_parallel_seize() -- Begin the process of advancing the scan to a new
607  * page. Other scans must wait until we call _bt_parallel_release()
608  * or _bt_parallel_done().
609  *
610  * The return value is true if we successfully seized the scan and false
611  * if we did not. The latter case occurs if no pages remain for the current
612  * set of scankeys.
613  *
614  * If the return value is true, *pageno returns the next or current page
615  * of the scan (depending on the scan direction). An invalid block number
616  * means the scan hasn't yet started, and P_NONE means we've reached the end.
617  * The first time a participating process reaches the last page, it will return
618  * true and set *pageno to P_NONE; after that, further attempts to seize the
619  * scan will return false.
620  *
621  * Callers should ignore the value of pageno if the return value is false.
622  */
623 bool
625 {
626  BTScanOpaque so = (BTScanOpaque) scan->opaque;
627  BTPS_State pageStatus;
628  bool exit_loop = false;
629  bool status = true;
630  ParallelIndexScanDesc parallel_scan = scan->parallel_scan;
631  BTParallelScanDesc btscan;
632 
633  *pageno = P_NONE;
634 
635  btscan = (BTParallelScanDesc) OffsetToPointer((void *) parallel_scan,
636  parallel_scan->ps_offset);
637 
638  while (1)
639  {
640  SpinLockAcquire(&btscan->btps_mutex);
641  pageStatus = btscan->btps_pageStatus;
642 
643  if (so->arrayKeyCount < btscan->btps_arrayKeyCount)
644  {
645  /* Parallel scan has already advanced to a new set of scankeys. */
646  status = false;
647  }
648  else if (pageStatus == BTPARALLEL_DONE)
649  {
650  /*
651  * We're done with this set of scankeys. This may be the end, or
652  * there could be more sets to try.
653  */
654  status = false;
655  }
656  else if (pageStatus != BTPARALLEL_ADVANCING)
657  {
658  /*
659  * We have successfully seized control of the scan for the purpose
660  * of advancing it to a new page!
661  */
662  btscan->btps_pageStatus = BTPARALLEL_ADVANCING;
663  *pageno = btscan->btps_scanPage;
664  exit_loop = true;
665  }
666  SpinLockRelease(&btscan->btps_mutex);
667  if (exit_loop || !status)
668  break;
669  ConditionVariableSleep(&btscan->btps_cv, WAIT_EVENT_BTREE_PAGE);
670  }
672 
673  return status;
674 }
675 
676 /*
677  * _bt_parallel_release() -- Complete the process of advancing the scan to a
678  * new page. We now have the new value btps_scanPage; some other backend
679  * can now begin advancing the scan.
680  */
681 void
683 {
684  ParallelIndexScanDesc parallel_scan = scan->parallel_scan;
685  BTParallelScanDesc btscan;
686 
687  btscan = (BTParallelScanDesc) OffsetToPointer((void *) parallel_scan,
688  parallel_scan->ps_offset);
689 
690  SpinLockAcquire(&btscan->btps_mutex);
691  btscan->btps_scanPage = scan_page;
693  SpinLockRelease(&btscan->btps_mutex);
695 }
696 
697 /*
698  * _bt_parallel_done() -- Mark the parallel scan as complete.
699  *
700  * When there are no pages left to scan, this function should be called to
701  * notify other workers. Otherwise, they might wait forever for the scan to
702  * advance to the next page.
703  */
704 void
706 {
707  BTScanOpaque so = (BTScanOpaque) scan->opaque;
708  ParallelIndexScanDesc parallel_scan = scan->parallel_scan;
709  BTParallelScanDesc btscan;
710  bool status_changed = false;
711 
712  /* Do nothing, for non-parallel scans */
713  if (parallel_scan == NULL)
714  return;
715 
716  btscan = (BTParallelScanDesc) OffsetToPointer((void *) parallel_scan,
717  parallel_scan->ps_offset);
718 
719  /*
720  * Mark the parallel scan as done for this combination of scan keys,
721  * unless some other process already did so. See also
722  * _bt_advance_array_keys.
723  */
724  SpinLockAcquire(&btscan->btps_mutex);
725  if (so->arrayKeyCount >= btscan->btps_arrayKeyCount &&
726  btscan->btps_pageStatus != BTPARALLEL_DONE)
727  {
728  btscan->btps_pageStatus = BTPARALLEL_DONE;
729  status_changed = true;
730  }
731  SpinLockRelease(&btscan->btps_mutex);
732 
733  /* wake up all the workers associated with this parallel scan */
734  if (status_changed)
735  ConditionVariableBroadcast(&btscan->btps_cv);
736 }
737 
738 /*
739  * _bt_parallel_advance_array_keys() -- Advances the parallel scan for array
740  * keys.
741  *
742  * Updates the count of array keys processed for both local and parallel
743  * scans.
744  */
745 void
747 {
748  BTScanOpaque so = (BTScanOpaque) scan->opaque;
749  ParallelIndexScanDesc parallel_scan = scan->parallel_scan;
750  BTParallelScanDesc btscan;
751 
752  btscan = (BTParallelScanDesc) OffsetToPointer((void *) parallel_scan,
753  parallel_scan->ps_offset);
754 
755  so->arrayKeyCount++;
756  SpinLockAcquire(&btscan->btps_mutex);
757  if (btscan->btps_pageStatus == BTPARALLEL_DONE)
758  {
759  btscan->btps_scanPage = InvalidBlockNumber;
760  btscan->btps_pageStatus = BTPARALLEL_NOT_INITIALIZED;
761  btscan->btps_arrayKeyCount++;
762  }
763  SpinLockRelease(&btscan->btps_mutex);
764 }
765 
766 /*
767  * Bulk deletion of all index entries pointing to a set of heap tuples.
768  * The set of target tuples is specified via a callback routine that tells
769  * whether any given heap tuple (identified by ItemPointer) is being deleted.
770  *
771  * Result: a palloc'd struct containing statistical info for VACUUM displays.
772  */
775  IndexBulkDeleteCallback callback, void *callback_state)
776 {
777  Relation rel = info->index;
778  BTCycleId cycleid;
779 
780  /* allocate stats if first time through, else re-use existing struct */
781  if (stats == NULL)
783 
784  /* Establish the vacuum cycle ID to use for this scan */
785  /* The ENSURE stuff ensures we clean up shared memory on failure */
787  {
788  cycleid = _bt_start_vacuum(rel);
789 
790  btvacuumscan(info, stats, callback, callback_state, cycleid);
791  }
793  _bt_end_vacuum(rel);
794 
795  return stats;
796 }
797 
798 /*
799  * Post-VACUUM cleanup.
800  *
801  * Result: a palloc'd struct containing statistical info for VACUUM displays.
802  */
805 {
806  BlockNumber num_delpages;
807 
808  /* No-op in ANALYZE ONLY mode */
809  if (info->analyze_only)
810  return stats;
811 
812  /*
813  * If btbulkdelete was called, we need not do anything (we just maintain
814  * the information used within _bt_vacuum_needs_cleanup() by calling
815  * _bt_set_cleanup_info() below).
816  *
817  * If btbulkdelete was _not_ called, then we have a choice to make: we
818  * must decide whether or not a btvacuumscan() call is needed now (i.e.
819  * whether the ongoing VACUUM operation can entirely avoid a physical scan
820  * of the index). A call to _bt_vacuum_needs_cleanup() decides it for us
821  * now.
822  */
823  if (stats == NULL)
824  {
825  /* Check if VACUUM operation can entirely avoid btvacuumscan() call */
826  if (!_bt_vacuum_needs_cleanup(info->index))
827  return NULL;
828 
829  /*
830  * Since we aren't going to actually delete any leaf items, there's no
831  * need to go through all the vacuum-cycle-ID pushups here.
832  *
833  * Posting list tuples are a source of inaccuracy for cleanup-only
834  * scans. btvacuumscan() will assume that the number of index tuples
835  * from each page can be used as num_index_tuples, even though
836  * num_index_tuples is supposed to represent the number of TIDs in the
837  * index. This naive approach can underestimate the number of tuples
838  * in the index significantly.
839  *
840  * We handle the problem by making num_index_tuples an estimate in
841  * cleanup-only case.
842  */
844  btvacuumscan(info, stats, NULL, NULL, 0);
845  stats->estimated_count = true;
846  }
847 
848  /*
849  * Maintain num_delpages value in metapage for _bt_vacuum_needs_cleanup().
850  *
851  * num_delpages is the number of deleted pages now in the index that were
852  * not safe to place in the FSM to be recycled just yet. num_delpages is
853  * greater than 0 only when _bt_pagedel() actually deleted pages during
854  * our call to btvacuumscan(). Even then, _bt_pendingfsm_finalize() must
855  * have failed to place any newly deleted pages in the FSM just moments
856  * ago. (Actually, there are edge cases where recycling of the current
857  * VACUUM's newly deleted pages does not even become safe by the time the
858  * next VACUUM comes around. See nbtree/README.)
859  */
860  Assert(stats->pages_deleted >= stats->pages_free);
861  num_delpages = stats->pages_deleted - stats->pages_free;
862  _bt_set_cleanup_info(info->index, num_delpages);
863 
864  /*
865  * It's quite possible for us to be fooled by concurrent page splits into
866  * double-counting some index tuples, so disbelieve any total that exceeds
867  * the underlying heap's count ... if we know that accurately. Otherwise
868  * this might just make matters worse.
869  */
870  if (!info->estimated_count)
871  {
872  if (stats->num_index_tuples > info->num_heap_tuples)
873  stats->num_index_tuples = info->num_heap_tuples;
874  }
875 
876  return stats;
877 }
878 
879 /*
880  * btvacuumscan --- scan the index for VACUUMing purposes
881  *
882  * This combines the functions of looking for leaf tuples that are deletable
883  * according to the vacuum callback, looking for empty pages that can be
884  * deleted, and looking for old deleted pages that can be recycled. Both
885  * btbulkdelete and btvacuumcleanup invoke this (the latter only if no
886  * btbulkdelete call occurred and _bt_vacuum_needs_cleanup returned true).
887  *
888  * The caller is responsible for initially allocating/zeroing a stats struct
889  * and for obtaining a vacuum cycle ID if necessary.
890  */
891 static void
893  IndexBulkDeleteCallback callback, void *callback_state,
894  BTCycleId cycleid)
895 {
896  Relation rel = info->index;
897  BTVacState vstate;
898  BlockNumber num_pages;
899  BlockNumber scanblkno;
900  bool needLock;
901 
902  /*
903  * Reset fields that track information about the entire index now. This
904  * avoids double-counting in the case where a single VACUUM command
905  * requires multiple scans of the index.
906  *
907  * Avoid resetting the tuples_removed and pages_newly_deleted fields here,
908  * since they track information about the VACUUM command, and so must last
909  * across each call to btvacuumscan().
910  *
911  * (Note that pages_free is treated as state about the whole index, not
912  * the current VACUUM. This is appropriate because RecordFreeIndexPage()
913  * calls are idempotent, and get repeated for the same deleted pages in
914  * some scenarios. The point for us is to track the number of recyclable
915  * pages in the index at the end of the VACUUM command.)
916  */
917  stats->num_pages = 0;
918  stats->num_index_tuples = 0;
919  stats->pages_deleted = 0;
920  stats->pages_free = 0;
921 
922  /* Set up info to pass down to btvacuumpage */
923  vstate.info = info;
924  vstate.stats = stats;
925  vstate.callback = callback;
926  vstate.callback_state = callback_state;
927  vstate.cycleid = cycleid;
928 
929  /* Create a temporary memory context to run _bt_pagedel in */
931  "_bt_pagedel",
933 
934  /* Initialize vstate fields used by _bt_pendingfsm_finalize */
935  vstate.bufsize = 0;
936  vstate.maxbufsize = 0;
937  vstate.pendingpages = NULL;
938  vstate.npendingpages = 0;
939  /* Consider applying _bt_pendingfsm_finalize optimization */
940  _bt_pendingfsm_init(rel, &vstate, (callback == NULL));
941 
942  /*
943  * The outer loop iterates over all index pages except the metapage, in
944  * physical order (we hope the kernel will cooperate in providing
945  * read-ahead for speed). It is critical that we visit all leaf pages,
946  * including ones added after we start the scan, else we might fail to
947  * delete some deletable tuples. Hence, we must repeatedly check the
948  * relation length. We must acquire the relation-extension lock while
949  * doing so to avoid a race condition: if someone else is extending the
950  * relation, there is a window where bufmgr/smgr have created a new
951  * all-zero page but it hasn't yet been write-locked by _bt_getbuf(). If
952  * we manage to scan such a page here, we'll improperly assume it can be
953  * recycled. Taking the lock synchronizes things enough to prevent a
954  * problem: either num_pages won't include the new page, or _bt_getbuf
955  * already has write lock on the buffer and it will be fully initialized
956  * before we can examine it. Also, we need not worry if a page is added
957  * immediately after we look; the page splitting code already has
958  * write-lock on the left page before it adds a right page, so we must
959  * already have processed any tuples due to be moved into such a page.
960  *
961  * XXX: Now that new pages are locked with RBM_ZERO_AND_LOCK, I don't
962  * think the use of the extension lock is still required.
963  *
964  * We can skip locking for new or temp relations, however, since no one
965  * else could be accessing them.
966  */
967  needLock = !RELATION_IS_LOCAL(rel);
968 
969  scanblkno = BTREE_METAPAGE + 1;
970  for (;;)
971  {
972  /* Get the current relation length */
973  if (needLock)
975  num_pages = RelationGetNumberOfBlocks(rel);
976  if (needLock)
978 
979  if (info->report_progress)
981  num_pages);
982 
983  /* Quit if we've scanned the whole relation */
984  if (scanblkno >= num_pages)
985  break;
986  /* Iterate over pages, then loop back to recheck length */
987  for (; scanblkno < num_pages; scanblkno++)
988  {
989  btvacuumpage(&vstate, scanblkno);
990  if (info->report_progress)
992  scanblkno);
993  }
994  }
995 
996  /* Set statistics num_pages field to final size of index */
997  stats->num_pages = num_pages;
998 
1000 
1001  /*
1002  * If there were any calls to _bt_pagedel() during scan of the index then
1003  * see if any of the resulting pages can be placed in the FSM now. When
1004  * it's not safe we'll have to leave it up to a future VACUUM operation.
1005  *
1006  * Finally, if we placed any pages in the FSM (either just now or during
1007  * the scan), forcibly update the upper-level FSM pages to ensure that
1008  * searchers can find them.
1009  */
1010  _bt_pendingfsm_finalize(rel, &vstate);
1011  if (stats->pages_free > 0)
1013 }
1014 
1015 /*
1016  * btvacuumpage --- VACUUM one page
1017  *
1018  * This processes a single page for btvacuumscan(). In some cases we must
1019  * backtrack to re-examine and VACUUM pages that were the scanblkno during
1020  * a previous call here. This is how we handle page splits (that happened
1021  * after our cycleid was acquired) whose right half page happened to reuse
1022  * a block that we might have processed at some point before it was
1023  * recycled (i.e. before the page split).
1024  */
1025 static void
1027 {
1028  IndexVacuumInfo *info = vstate->info;
1029  IndexBulkDeleteResult *stats = vstate->stats;
1031  void *callback_state = vstate->callback_state;
1032  Relation rel = info->index;
1033  Relation heaprel = info->heaprel;
1034  bool attempt_pagedel;
1035  BlockNumber blkno,
1036  backtrack_to;
1037  Buffer buf;
1038  Page page;
1039  BTPageOpaque opaque;
1040 
1041  blkno = scanblkno;
1042 
1043 backtrack:
1044 
1045  attempt_pagedel = false;
1046  backtrack_to = P_NONE;
1047 
1048  /* call vacuum_delay_point while not holding any buffer lock */
1050 
1051  /*
1052  * We can't use _bt_getbuf() here because it always applies
1053  * _bt_checkpage(), which will barf on an all-zero page. We want to
1054  * recycle all-zero pages, not fail. Also, we want to use a nondefault
1055  * buffer access strategy.
1056  */
1058  info->strategy);
1059  _bt_lockbuf(rel, buf, BT_READ);
1060  page = BufferGetPage(buf);
1061  opaque = NULL;
1062  if (!PageIsNew(page))
1063  {
1064  _bt_checkpage(rel, buf);
1065  opaque = BTPageGetOpaque(page);
1066  }
1067 
1068  Assert(blkno <= scanblkno);
1069  if (blkno != scanblkno)
1070  {
1071  /*
1072  * We're backtracking.
1073  *
1074  * We followed a right link to a sibling leaf page (a page that
1075  * happens to be from a block located before scanblkno). The only
1076  * case we want to do anything with is a live leaf page having the
1077  * current vacuum cycle ID.
1078  *
1079  * The page had better be in a state that's consistent with what we
1080  * expect. Check for conditions that imply corruption in passing. It
1081  * can't be half-dead because only an interrupted VACUUM process can
1082  * leave pages in that state, so we'd definitely have dealt with it
1083  * back when the page was the scanblkno page (half-dead pages are
1084  * always marked fully deleted by _bt_pagedel(), barring corruption).
1085  */
1086  if (!opaque || !P_ISLEAF(opaque) || P_ISHALFDEAD(opaque))
1087  {
1088  Assert(false);
1089  ereport(LOG,
1090  (errcode(ERRCODE_INDEX_CORRUPTED),
1091  errmsg_internal("right sibling %u of scanblkno %u unexpectedly in an inconsistent state in index \"%s\"",
1092  blkno, scanblkno, RelationGetRelationName(rel))));
1093  _bt_relbuf(rel, buf);
1094  return;
1095  }
1096 
1097  /*
1098  * We may have already processed the page in an earlier call, when the
1099  * page was scanblkno. This happens when the leaf page split occurred
1100  * after the scan began, but before the right sibling page became the
1101  * scanblkno.
1102  *
1103  * Page may also have been deleted by current btvacuumpage() call,
1104  * since _bt_pagedel() sometimes deletes the right sibling page of
1105  * scanblkno in passing (it does so after we decided where to
1106  * backtrack to). We don't need to process this page as a deleted
1107  * page a second time now (in fact, it would be wrong to count it as a
1108  * deleted page in the bulk delete statistics a second time).
1109  */
1110  if (opaque->btpo_cycleid != vstate->cycleid || P_ISDELETED(opaque))
1111  {
1112  /* Done with current scanblkno (and all lower split pages) */
1113  _bt_relbuf(rel, buf);
1114  return;
1115  }
1116  }
1117 
1118  if (!opaque || BTPageIsRecyclable(page, heaprel))
1119  {
1120  /* Okay to recycle this page (which could be leaf or internal) */
1121  RecordFreeIndexPage(rel, blkno);
1122  stats->pages_deleted++;
1123  stats->pages_free++;
1124  }
1125  else if (P_ISDELETED(opaque))
1126  {
1127  /*
1128  * Already deleted page (which could be leaf or internal). Can't
1129  * recycle yet.
1130  */
1131  stats->pages_deleted++;
1132  }
1133  else if (P_ISHALFDEAD(opaque))
1134  {
1135  /* Half-dead leaf page (from interrupted VACUUM) -- finish deleting */
1136  attempt_pagedel = true;
1137 
1138  /*
1139  * _bt_pagedel() will increment both pages_newly_deleted and
1140  * pages_deleted stats in all cases (barring corruption)
1141  */
1142  }
1143  else if (P_ISLEAF(opaque))
1144  {
1146  int ndeletable;
1148  int nupdatable;
1149  OffsetNumber offnum,
1150  minoff,
1151  maxoff;
1152  int nhtidsdead,
1153  nhtidslive;
1154 
1155  /*
1156  * Trade in the initial read lock for a full cleanup lock on this
1157  * page. We must get such a lock on every leaf page over the course
1158  * of the vacuum scan, whether or not it actually contains any
1159  * deletable tuples --- see nbtree/README.
1160  */
1162 
1163  /*
1164  * Check whether we need to backtrack to earlier pages. What we are
1165  * concerned about is a page split that happened since we started the
1166  * vacuum scan. If the split moved tuples on the right half of the
1167  * split (i.e. the tuples that sort high) to a block that we already
1168  * passed over, then we might have missed the tuples. We need to
1169  * backtrack now. (Must do this before possibly clearing btpo_cycleid
1170  * or deleting scanblkno page below!)
1171  */
1172  if (vstate->cycleid != 0 &&
1173  opaque->btpo_cycleid == vstate->cycleid &&
1174  !(opaque->btpo_flags & BTP_SPLIT_END) &&
1175  !P_RIGHTMOST(opaque) &&
1176  opaque->btpo_next < scanblkno)
1177  backtrack_to = opaque->btpo_next;
1178 
1179  ndeletable = 0;
1180  nupdatable = 0;
1181  minoff = P_FIRSTDATAKEY(opaque);
1182  maxoff = PageGetMaxOffsetNumber(page);
1183  nhtidsdead = 0;
1184  nhtidslive = 0;
1185  if (callback)
1186  {
1187  /* btbulkdelete callback tells us what to delete (or update) */
1188  for (offnum = minoff;
1189  offnum <= maxoff;
1190  offnum = OffsetNumberNext(offnum))
1191  {
1192  IndexTuple itup;
1193 
1194  itup = (IndexTuple) PageGetItem(page,
1195  PageGetItemId(page, offnum));
1196 
1197  Assert(!BTreeTupleIsPivot(itup));
1198  if (!BTreeTupleIsPosting(itup))
1199  {
1200  /* Regular tuple, standard table TID representation */
1201  if (callback(&itup->t_tid, callback_state))
1202  {
1203  deletable[ndeletable++] = offnum;
1204  nhtidsdead++;
1205  }
1206  else
1207  nhtidslive++;
1208  }
1209  else
1210  {
1211  BTVacuumPosting vacposting;
1212  int nremaining;
1213 
1214  /* Posting list tuple */
1215  vacposting = btreevacuumposting(vstate, itup, offnum,
1216  &nremaining);
1217  if (vacposting == NULL)
1218  {
1219  /*
1220  * All table TIDs from the posting tuple remain, so no
1221  * delete or update required
1222  */
1223  Assert(nremaining == BTreeTupleGetNPosting(itup));
1224  }
1225  else if (nremaining > 0)
1226  {
1227 
1228  /*
1229  * Store metadata about posting list tuple in
1230  * updatable array for entire page. Existing tuple
1231  * will be updated during the later call to
1232  * _bt_delitems_vacuum().
1233  */
1234  Assert(nremaining < BTreeTupleGetNPosting(itup));
1235  updatable[nupdatable++] = vacposting;
1236  nhtidsdead += BTreeTupleGetNPosting(itup) - nremaining;
1237  }
1238  else
1239  {
1240  /*
1241  * All table TIDs from the posting list must be
1242  * deleted. We'll delete the index tuple completely
1243  * (no update required).
1244  */
1245  Assert(nremaining == 0);
1246  deletable[ndeletable++] = offnum;
1247  nhtidsdead += BTreeTupleGetNPosting(itup);
1248  pfree(vacposting);
1249  }
1250 
1251  nhtidslive += nremaining;
1252  }
1253  }
1254  }
1255 
1256  /*
1257  * Apply any needed deletes or updates. We issue just one
1258  * _bt_delitems_vacuum() call per page, so as to minimize WAL traffic.
1259  */
1260  if (ndeletable > 0 || nupdatable > 0)
1261  {
1262  Assert(nhtidsdead >= ndeletable + nupdatable);
1263  _bt_delitems_vacuum(rel, buf, deletable, ndeletable, updatable,
1264  nupdatable);
1265 
1266  stats->tuples_removed += nhtidsdead;
1267  /* must recompute maxoff */
1268  maxoff = PageGetMaxOffsetNumber(page);
1269 
1270  /* can't leak memory here */
1271  for (int i = 0; i < nupdatable; i++)
1272  pfree(updatable[i]);
1273  }
1274  else
1275  {
1276  /*
1277  * If the leaf page has been split during this vacuum cycle, it
1278  * seems worth expending a write to clear btpo_cycleid even if we
1279  * don't have any deletions to do. (If we do, _bt_delitems_vacuum
1280  * takes care of this.) This ensures we won't process the page
1281  * again.
1282  *
1283  * We treat this like a hint-bit update because there's no need to
1284  * WAL-log it.
1285  */
1286  Assert(nhtidsdead == 0);
1287  if (vstate->cycleid != 0 &&
1288  opaque->btpo_cycleid == vstate->cycleid)
1289  {
1290  opaque->btpo_cycleid = 0;
1291  MarkBufferDirtyHint(buf, true);
1292  }
1293  }
1294 
1295  /*
1296  * If the leaf page is now empty, try to delete it; else count the
1297  * live tuples (live table TIDs in posting lists are counted as
1298  * separate live tuples). We don't delete when backtracking, though,
1299  * since that would require teaching _bt_pagedel() about backtracking
1300  * (doesn't seem worth adding more complexity to deal with that).
1301  *
1302  * We don't count the number of live TIDs during cleanup-only calls to
1303  * btvacuumscan (i.e. when callback is not set). We count the number
1304  * of index tuples directly instead. This avoids the expense of
1305  * directly examining all of the tuples on each page. VACUUM will
1306  * treat num_index_tuples as an estimate in cleanup-only case, so it
1307  * doesn't matter that this underestimates num_index_tuples
1308  * significantly in some cases.
1309  */
1310  if (minoff > maxoff)
1311  attempt_pagedel = (blkno == scanblkno);
1312  else if (callback)
1313  stats->num_index_tuples += nhtidslive;
1314  else
1315  stats->num_index_tuples += maxoff - minoff + 1;
1316 
1317  Assert(!attempt_pagedel || nhtidslive == 0);
1318  }
1319 
1320  if (attempt_pagedel)
1321  {
1322  MemoryContext oldcontext;
1323 
1324  /* Run pagedel in a temp context to avoid memory leakage */
1326  oldcontext = MemoryContextSwitchTo(vstate->pagedelcontext);
1327 
1328  /*
1329  * _bt_pagedel maintains the bulk delete stats on our behalf;
1330  * pages_newly_deleted and pages_deleted are likely to be incremented
1331  * during call
1332  */
1333  Assert(blkno == scanblkno);
1334  _bt_pagedel(rel, buf, vstate);
1335 
1336  MemoryContextSwitchTo(oldcontext);
1337  /* pagedel released buffer, so we shouldn't */
1338  }
1339  else
1340  _bt_relbuf(rel, buf);
1341 
1342  if (backtrack_to != P_NONE)
1343  {
1344  blkno = backtrack_to;
1345  goto backtrack;
1346  }
1347 }
1348 
1349 /*
1350  * btreevacuumposting --- determine TIDs still needed in posting list
1351  *
1352  * Returns metadata describing how to build replacement tuple without the TIDs
1353  * that VACUUM needs to delete. Returned value is NULL in the common case
1354  * where no changes are needed to caller's posting list tuple (we avoid
1355  * allocating memory here as an optimization).
1356  *
1357  * The number of TIDs that should remain in the posting list tuple is set for
1358  * caller in *nremaining.
1359  */
1360 static BTVacuumPosting
1362  OffsetNumber updatedoffset, int *nremaining)
1363 {
1364  int live = 0;
1365  int nitem = BTreeTupleGetNPosting(posting);
1366  ItemPointer items = BTreeTupleGetPosting(posting);
1367  BTVacuumPosting vacposting = NULL;
1368 
1369  for (int i = 0; i < nitem; i++)
1370  {
1371  if (!vstate->callback(items + i, vstate->callback_state))
1372  {
1373  /* Live table TID */
1374  live++;
1375  }
1376  else if (vacposting == NULL)
1377  {
1378  /*
1379  * First dead table TID encountered.
1380  *
1381  * It's now clear that we need to delete one or more dead table
1382  * TIDs, so start maintaining metadata describing how to update
1383  * existing posting list tuple.
1384  */
1385  vacposting = palloc(offsetof(BTVacuumPostingData, deletetids) +
1386  nitem * sizeof(uint16));
1387 
1388  vacposting->itup = posting;
1389  vacposting->updatedoffset = updatedoffset;
1390  vacposting->ndeletedtids = 0;
1391  vacposting->deletetids[vacposting->ndeletedtids++] = i;
1392  }
1393  else
1394  {
1395  /* Second or subsequent dead table TID */
1396  vacposting->deletetids[vacposting->ndeletedtids++] = i;
1397  }
1398  }
1399 
1400  *nremaining = live;
1401  return vacposting;
1402 }
1403 
1404 /*
1405  * btcanreturn() -- Check whether btree indexes support index-only scans.
1406  *
1407  * btrees always do, so this is trivial.
1408  */
1409 bool
1411 {
1412  return true;
1413 }
void pgstat_progress_update_param(int index, int64 val)
uint32 BlockNumber
Definition: block.h:31
#define InvalidBlockNumber
Definition: block.h:33
static Datum values[MAXATTR]
Definition: bootstrap.c:152
int Buffer
Definition: buf.h:23
void IncrBufferRefCount(Buffer buffer)
Definition: bufmgr.c:4592
void MarkBufferDirtyHint(Buffer buffer, bool buffer_std)
Definition: bufmgr.c:4624
Buffer ReadBufferExtended(Relation reln, ForkNumber forkNum, BlockNumber blockNum, ReadBufferMode mode, BufferAccessStrategy strategy)
Definition: bufmgr.c:781
#define RelationGetNumberOfBlocks(reln)
Definition: bufmgr.h:229
static Page BufferGetPage(Buffer buffer)
Definition: bufmgr.h:350
@ RBM_NORMAL
Definition: bufmgr.h:44
Pointer Page
Definition: bufpage.h:78
static Item PageGetItem(Page page, ItemId itemId)
Definition: bufpage.h:351
static ItemId PageGetItemId(Page page, OffsetNumber offsetNumber)
Definition: bufpage.h:240
static bool PageIsNew(Page page)
Definition: bufpage.h:230
static OffsetNumber PageGetMaxOffsetNumber(Page page)
Definition: bufpage.h:369
void smgr_bulk_write(BulkWriteState *bulkstate, BlockNumber blocknum, BulkWriteBuffer buf, bool page_std)
Definition: bulk_write.c:271
BulkWriteBuffer smgr_bulk_get_buf(BulkWriteState *bulkstate)
Definition: bulk_write.c:295
void smgr_bulk_finish(BulkWriteState *bulkstate)
Definition: bulk_write.c:129
BulkWriteState * smgr_bulk_start_rel(Relation rel, ForkNumber forknum)
Definition: bulk_write.c:86
#define OffsetToPointer(base, offset)
Definition: c.h:759
unsigned short uint16
Definition: c.h:492
size_t Size
Definition: c.h:592
bool ConditionVariableCancelSleep(void)
void ConditionVariableBroadcast(ConditionVariable *cv)
void ConditionVariableInit(ConditionVariable *cv)
void ConditionVariableSleep(ConditionVariable *cv, uint32 wait_event_info)
void ConditionVariableSignal(ConditionVariable *cv)
int errmsg_internal(const char *fmt,...)
Definition: elog.c:1159
int errcode(int sqlerrcode)
Definition: elog.c:859
#define LOG
Definition: elog.h:31
#define ereport(elevel,...)
Definition: elog.h:149
#define PG_RETURN_POINTER(x)
Definition: fmgr.h:361
#define PG_FUNCTION_ARGS
Definition: fmgr.h:193
IndexScanDesc RelationGetIndexScan(Relation indexRelation, int nkeys, int norderbys)
Definition: genam.c:78
bool(* IndexBulkDeleteCallback)(ItemPointer itemptr, void *state)
Definition: genam.h:87
IndexUniqueCheck
Definition: genam.h:116
void IndexFreeSpaceMapVacuum(Relation rel)
Definition: indexfsm.c:71
void RecordFreeIndexPage(Relation rel, BlockNumber freeBlock)
Definition: indexfsm.c:52
IndexTuple index_form_tuple(TupleDesc tupleDescriptor, const Datum *values, const bool *isnull)
Definition: indextuple.c:44
#define PG_ENSURE_ERROR_CLEANUP(cleanup_function, arg)
Definition: ipc.h:47
#define PG_END_ENSURE_ERROR_CLEANUP(cleanup_function, arg)
Definition: ipc.h:52
int i
Definition: isn.c:73
if(TABLE==NULL||TABLE_index==NULL)
Definition: isn.c:77
IndexTupleData * IndexTuple
Definition: itup.h:53
#define MaxIndexTuplesPerPage
Definition: itup.h:165
Assert(fmt[strlen(fmt) - 1] !='\n')
void LockRelationForExtension(Relation relation, LOCKMODE lockmode)
Definition: lmgr.c:430
void UnlockRelationForExtension(Relation relation, LOCKMODE lockmode)
Definition: lmgr.c:480
#define ExclusiveLock
Definition: lockdefs.h:42
void MemoryContextReset(MemoryContext context)
Definition: mcxt.c:371
void pfree(void *pointer)
Definition: mcxt.c:1508
void * palloc0(Size size)
Definition: mcxt.c:1334
MemoryContext CurrentMemoryContext
Definition: mcxt.c:131
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:442
void * palloc(Size size)
Definition: mcxt.c:1304
#define AllocSetContextCreate
Definition: memutils.h:129
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:153
bool _bt_doinsert(Relation rel, IndexTuple itup, IndexUniqueCheck checkUnique, bool indexUnchanged, Relation heapRel)
Definition: nbtinsert.c:102
void _bt_relbuf(Relation rel, Buffer buf)
Definition: nbtpage.c:1023
void _bt_pagedel(Relation rel, Buffer leafbuf, BTVacState *vstate)
Definition: nbtpage.c:1802
void _bt_delitems_vacuum(Relation rel, Buffer buf, OffsetNumber *deletable, int ndeletable, BTVacuumPosting *updatable, int nupdatable)
Definition: nbtpage.c:1154
void _bt_checkpage(Relation rel, Buffer buf)
Definition: nbtpage.c:797
void _bt_set_cleanup_info(Relation rel, BlockNumber num_delpages)
Definition: nbtpage.c:232
void _bt_upgradelockbufcleanup(Relation rel, Buffer buf)
Definition: nbtpage.c:1109
void _bt_initmetapage(Page page, BlockNumber rootbknum, uint32 level, bool allequalimage)
Definition: nbtpage.c:67
bool _bt_vacuum_needs_cleanup(Relation rel)
Definition: nbtpage.c:179
void _bt_pendingfsm_finalize(Relation rel, BTVacState *vstate)
Definition: nbtpage.c:2995
void _bt_lockbuf(Relation rel, Buffer buf, int access)
Definition: nbtpage.c:1039
void _bt_pendingfsm_init(Relation rel, BTVacState *vstate, bool cleanuponly)
Definition: nbtpage.c:2954
bool btcanreturn(Relation index, int attno)
Definition: nbtree.c:1410
void _bt_parallel_release(IndexScanDesc scan, BlockNumber scan_page)
Definition: nbtree.c:682
BTPS_State
Definition: nbtree.c:53
@ BTPARALLEL_ADVANCING
Definition: nbtree.c:55
@ BTPARALLEL_NOT_INITIALIZED
Definition: nbtree.c:54
@ BTPARALLEL_IDLE
Definition: nbtree.c:56
@ BTPARALLEL_DONE
Definition: nbtree.c:57
IndexScanDesc btbeginscan(Relation rel, int nkeys, int norderbys)
Definition: nbtree.c:331
void _bt_parallel_done(IndexScanDesc scan)
Definition: nbtree.c:705
IndexBulkDeleteResult * btbulkdelete(IndexVacuumInfo *info, IndexBulkDeleteResult *stats, IndexBulkDeleteCallback callback, void *callback_state)
Definition: nbtree.c:774
void _bt_parallel_advance_array_keys(IndexScanDesc scan)
Definition: nbtree.c:746
static BTVacuumPosting btreevacuumposting(BTVacState *vstate, IndexTuple posting, OffsetNumber updatedoffset, int *nremaining)
Definition: nbtree.c:1361
IndexBulkDeleteResult * btvacuumcleanup(IndexVacuumInfo *info, IndexBulkDeleteResult *stats)
Definition: nbtree.c:804
bool btgettuple(IndexScanDesc scan, ScanDirection dir)
Definition: nbtree.c:199
void btparallelrescan(IndexScanDesc scan)
Definition: nbtree.c:583
struct BTParallelScanDescData BTParallelScanDescData
bool btinsert(Relation rel, Datum *values, bool *isnull, ItemPointer ht_ctid, Relation heapRel, IndexUniqueCheck checkUnique, bool indexUnchanged, IndexInfo *indexInfo)
Definition: nbtree.c:175
void btbuildempty(Relation index)
Definition: nbtree.c:152
bool _bt_parallel_seize(IndexScanDesc scan, BlockNumber *pageno)
Definition: nbtree.c:624
static void btvacuumpage(BTVacState *vstate, BlockNumber scanblkno)
Definition: nbtree.c:1026
Size btestimateparallelscan(void)
Definition: nbtree.c:559
void btinitparallelscan(void *target)
Definition: nbtree.c:568
static void btvacuumscan(IndexVacuumInfo *info, IndexBulkDeleteResult *stats, IndexBulkDeleteCallback callback, void *callback_state, BTCycleId cycleid)
Definition: nbtree.c:892
int64 btgetbitmap(IndexScanDesc scan, TIDBitmap *tbm)
Definition: nbtree.c:273
void btmarkpos(IndexScanDesc scan)
Definition: nbtree.c:473
void btendscan(IndexScanDesc scan)
Definition: nbtree.c:437
void btrescan(IndexScanDesc scan, ScanKey scankey, int nscankeys, ScanKey orderbys, int norderbys)
Definition: nbtree.c:378
struct BTParallelScanDescData * BTParallelScanDesc
Definition: nbtree.c:76
Datum bthandler(PG_FUNCTION_ARGS)
Definition: nbtree.c:94
void btrestrpos(IndexScanDesc scan)
Definition: nbtree.c:503
#define P_ISHALFDEAD(opaque)
Definition: nbtree.h:224
#define BTScanPosIsPinned(scanpos)
Definition: nbtree.h:990
static uint16 BTreeTupleGetNPosting(IndexTuple posting)
Definition: nbtree.h:518
static bool BTreeTupleIsPivot(IndexTuple itup)
Definition: nbtree.h:480
#define P_ISLEAF(opaque)
Definition: nbtree.h:220
#define BTPageGetOpaque(page)
Definition: nbtree.h:73
#define P_ISDELETED(opaque)
Definition: nbtree.h:222
static ItemPointer BTreeTupleGetPosting(IndexTuple posting)
Definition: nbtree.h:537
#define BTNProcs
Definition: nbtree.h:712
#define MaxTIDsPerBTreePage
Definition: nbtree.h:185
#define BTScanPosIsValid(scanpos)
Definition: nbtree.h:1007
#define P_FIRSTDATAKEY(opaque)
Definition: nbtree.h:369
uint16 BTCycleId
Definition: nbtree.h:29
#define P_NONE
Definition: nbtree.h:212
#define P_RIGHTMOST(opaque)
Definition: nbtree.h:219
#define BTREE_METAPAGE
Definition: nbtree.h:148
#define BT_READ
Definition: nbtree.h:719
static bool BTPageIsRecyclable(Page page, Relation heaprel)
Definition: nbtree.h:291
static bool BTreeTupleIsPosting(IndexTuple itup)
Definition: nbtree.h:492
#define BTScanPosInvalidate(scanpos)
Definition: nbtree.h:1013
#define BTScanPosUnpinIfPinned(scanpos)
Definition: nbtree.h:1001
#define BTP_SPLIT_END
Definition: nbtree.h:81
#define BTOPTIONS_PROC
Definition: nbtree.h:711
BTScanOpaqueData * BTScanOpaque
Definition: nbtree.h:1076
bool _bt_first(IndexScanDesc scan, ScanDirection dir)
Definition: nbtsearch.c:876
bool _bt_next(IndexScanDesc scan, ScanDirection dir)
Definition: nbtsearch.c:1459
IndexBuildResult * btbuild(Relation heap, Relation index, IndexInfo *indexInfo)
Definition: nbtsort.c:293
void _bt_end_vacuum(Relation rel)
Definition: nbtutils.c:2084
char * btbuildphasename(int64 phasenum)
Definition: nbtutils.c:2208
void _bt_end_vacuum_callback(int code, Datum arg)
Definition: nbtutils.c:2112
bytea * btoptions(Datum reloptions, bool validate)
Definition: nbtutils.c:2162
bool _bt_advance_array_keys(IndexScanDesc scan, ScanDirection dir)
Definition: nbtutils.c:544
void _bt_killitems(IndexScanDesc scan)
Definition: nbtutils.c:1776
void _bt_preprocess_array_keys(IndexScanDesc scan)
Definition: nbtutils.c:201
void _bt_restore_array_keys(IndexScanDesc scan)
Definition: nbtutils.c:630
void _bt_mark_array_keys(IndexScanDesc scan)
Definition: nbtutils.c:611
bool btproperty(Oid index_oid, int attno, IndexAMProperty prop, const char *propname, bool *res, bool *isnull)
Definition: nbtutils.c:2185
bool _bt_allequalimage(Relation rel, bool debugmessage)
Definition: nbtutils.c:2740
void _bt_start_array_keys(IndexScanDesc scan, ScanDirection dir)
Definition: nbtutils.c:516
BTCycleId _bt_start_vacuum(Relation rel)
Definition: nbtutils.c:2027
bool btvalidate(Oid opclassoid)
Definition: nbtvalidate.c:41
void btadjustmembers(Oid opfamilyoid, Oid opclassoid, List *operators, List *functions)
Definition: nbtvalidate.c:293
#define makeNode(_type_)
Definition: nodes.h:155
#define OffsetNumberNext(offsetNumber)
Definition: off.h:52
uint16 OffsetNumber
Definition: off.h:24
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:124
static char * buf
Definition: pg_test_fsync.c:73
static Datum PointerGetDatum(const void *X)
Definition: postgres.h:322
uintptr_t Datum
Definition: postgres.h:64
#define InvalidOid
Definition: postgres_ext.h:36
#define PROGRESS_SCAN_BLOCKS_DONE
Definition: progress.h:122
#define PROGRESS_SCAN_BLOCKS_TOTAL
Definition: progress.h:121
#define RELATION_IS_LOCAL(relation)
Definition: rel.h:648
#define RelationGetDescr(relation)
Definition: rel.h:531
#define RelationGetRelationName(relation)
Definition: rel.h:539
@ MAIN_FORKNUM
Definition: relpath.h:50
@ INIT_FORKNUM
Definition: relpath.h:53
int slock_t
Definition: s_lock.h:735
ScanDirection
Definition: sdir.h:25
@ ForwardScanDirection
Definition: sdir.h:28
void btcostestimate(PlannerInfo *root, IndexPath *path, double loop_count, Cost *indexStartupCost, Cost *indexTotalCost, Selectivity *indexSelectivity, double *indexCorrelation, double *indexPages)
Definition: selfuncs.c:6783
ScanKeyData * ScanKey
Definition: skey.h:75
#define SpinLockInit(lock)
Definition: spin.h:60
#define SpinLockRelease(lock)
Definition: spin.h:64
#define SpinLockAcquire(lock)
Definition: spin.h:62
#define BTMaxStrategyNumber
Definition: stratnum.h:35
BlockNumber btpo_next
Definition: nbtree.h:65
uint16 btpo_flags
Definition: nbtree.h:67
BTCycleId btpo_cycleid
Definition: nbtree.h:68
slock_t btps_mutex
Definition: nbtree.c:72
BTPS_State btps_pageStatus
Definition: nbtree.c:67
ConditionVariable btps_cv
Definition: nbtree.c:73
BlockNumber btps_scanPage
Definition: nbtree.c:66
BTArrayKeyInfo * arrayKeys
Definition: nbtree.h:1047
bool arraysStarted
Definition: nbtree.h:1041
char * markTuples
Definition: nbtree.h:1060
BTScanPosData currPos
Definition: nbtree.h:1072
int * killedItems
Definition: nbtree.h:1051
char * currTuples
Definition: nbtree.h:1059
ScanKey arrayKeyData
Definition: nbtree.h:1040
BTScanPosData markPos
Definition: nbtree.h:1073
ScanKey keyData
Definition: nbtree.h:1037
MemoryContext arrayContext
Definition: nbtree.h:1048
Buffer buf
Definition: nbtree.h:953
int nextTupleOffset
Definition: nbtree.h:972
int lastItem
Definition: nbtree.h:982
BTScanPosItem items[MaxTIDsPerBTreePage]
Definition: nbtree.h:985
int itemIndex
Definition: nbtree.h:983
ItemPointerData heapTid
Definition: nbtree.h:946
IndexBulkDeleteResult * stats
Definition: nbtree.h:333
BTCycleId cycleid
Definition: nbtree.h:336
BTPendingFSM * pendingpages
Definition: nbtree.h:344
int npendingpages
Definition: nbtree.h:345
IndexBulkDeleteCallback callback
Definition: nbtree.h:334
MemoryContext pagedelcontext
Definition: nbtree.h:337
IndexVacuumInfo * info
Definition: nbtree.h:332
int bufsize
Definition: nbtree.h:342
int maxbufsize
Definition: nbtree.h:343
void * callback_state
Definition: nbtree.h:335
uint16 deletetids[FLEXIBLE_ARRAY_MEMBER]
Definition: nbtree.h:911
uint16 ndeletedtids
Definition: nbtree.h:910
IndexTuple itup
Definition: nbtree.h:906
OffsetNumber updatedoffset
Definition: nbtree.h:907
ambuildphasename_function ambuildphasename
Definition: amapi.h:276
ambuildempty_function ambuildempty
Definition: amapi.h:267
amvacuumcleanup_function amvacuumcleanup
Definition: amapi.h:271
bool amclusterable
Definition: amapi.h:241
amoptions_function amoptions
Definition: amapi.h:274
amestimateparallelscan_function amestimateparallelscan
Definition: amapi.h:288
amrestrpos_function amrestrpos
Definition: amapi.h:285
aminsert_function aminsert
Definition: amapi.h:268
amendscan_function amendscan
Definition: amapi.h:283
uint16 amoptsprocnum
Definition: amapi.h:221
amparallelrescan_function amparallelrescan
Definition: amapi.h:290
Oid amkeytype
Definition: amapi.h:257
bool ampredlocks
Definition: amapi.h:243
uint16 amsupport
Definition: amapi.h:219
amcostestimate_function amcostestimate
Definition: amapi.h:273
bool amcanorderbyop
Definition: amapi.h:225
amadjustmembers_function amadjustmembers
Definition: amapi.h:278
ambuild_function ambuild
Definition: amapi.h:266
bool amstorage
Definition: amapi.h:239
uint16 amstrategies
Definition: amapi.h:217
bool amoptionalkey
Definition: amapi.h:233
amgettuple_function amgettuple
Definition: amapi.h:281
amcanreturn_function amcanreturn
Definition: amapi.h:272
bool amcanunique
Definition: amapi.h:229
amgetbitmap_function amgetbitmap
Definition: amapi.h:282
amproperty_function amproperty
Definition: amapi.h:275
ambulkdelete_function ambulkdelete
Definition: amapi.h:270
bool amsearcharray
Definition: amapi.h:235
bool amsummarizing
Definition: amapi.h:253
amvalidate_function amvalidate
Definition: amapi.h:277
ammarkpos_function ammarkpos
Definition: amapi.h:284
bool amcanmulticol
Definition: amapi.h:231
bool amusemaintenanceworkmem
Definition: amapi.h:251
ambeginscan_function ambeginscan
Definition: amapi.h:279
bool amcanparallel
Definition: amapi.h:245
amrescan_function amrescan
Definition: amapi.h:280
bool amcanorder
Definition: amapi.h:223
bool amcanbuildparallel
Definition: amapi.h:247
aminitparallelscan_function aminitparallelscan
Definition: amapi.h:289
uint8 amparallelvacuumoptions
Definition: amapi.h:255
aminsertcleanup_function aminsertcleanup
Definition: amapi.h:269
bool amcanbackward
Definition: amapi.h:227
bool amcaninclude
Definition: amapi.h:249
bool amsearchnulls
Definition: amapi.h:237
bool estimated_count
Definition: genam.h:78
BlockNumber pages_deleted
Definition: genam.h:82
BlockNumber pages_free
Definition: genam.h:83
BlockNumber num_pages
Definition: genam.h:77
double tuples_removed
Definition: genam.h:80
double num_index_tuples
Definition: genam.h:79
struct ScanKeyData * keyData
Definition: relscan.h:122
struct ParallelIndexScanDescData * parallel_scan
Definition: relscan.h:166
bool kill_prior_tuple
Definition: relscan.h:128
struct TupleDescData * xs_itupdesc
Definition: relscan.h:143
ItemPointerData xs_heaptid
Definition: relscan.h:147
ItemPointerData t_tid
Definition: itup.h:37
Relation index
Definition: genam.h:46
double num_heap_tuples
Definition: genam.h:52
bool analyze_only
Definition: genam.h:48
BufferAccessStrategy strategy
Definition: genam.h:53
Relation heaprel
Definition: genam.h:47
bool report_progress
Definition: genam.h:49
bool estimated_count
Definition: genam.h:50
Definition: type.h:95
static void callback(struct sockaddr *addr, struct sockaddr *mask, void *unused)
Definition: test_ifaddrs.c:46
void tbm_add_tuples(TIDBitmap *tbm, const ItemPointer tids, int ntids, bool recheck)
Definition: tidbitmap.c:377
void vacuum_delay_point(void)
Definition: vacuum.c:2337
#define VACUUM_OPTION_PARALLEL_BULKDEL
Definition: vacuum.h:47
#define VACUUM_OPTION_PARALLEL_COND_CLEANUP
Definition: vacuum.h:54