PostgreSQL Source Code  git master
nbtsort.c File Reference
#include "postgres.h"
#include "access/nbtree.h"
#include "access/parallel.h"
#include "access/relscan.h"
#include "access/table.h"
#include "access/tableam.h"
#include "access/xact.h"
#include "access/xlog.h"
#include "access/xloginsert.h"
#include "catalog/index.h"
#include "commands/progress.h"
#include "executor/instrument.h"
#include "miscadmin.h"
#include "pgstat.h"
#include "storage/smgr.h"
#include "tcop/tcopprot.h"
#include "utils/rel.h"
#include "utils/sortsupport.h"
#include "utils/tuplesort.h"
Include dependency graph for nbtsort.c:

Go to the source code of this file.

Data Structures

struct  BTSpool
 
struct  BTShared
 
struct  BTLeader
 
struct  BTBuildState
 
struct  BTPageState
 
struct  BTWriteState
 

Macros

#define PARALLEL_KEY_BTREE_SHARED   UINT64CONST(0xA000000000000001)
 
#define PARALLEL_KEY_TUPLESORT   UINT64CONST(0xA000000000000002)
 
#define PARALLEL_KEY_TUPLESORT_SPOOL2   UINT64CONST(0xA000000000000003)
 
#define PARALLEL_KEY_QUERY_TEXT   UINT64CONST(0xA000000000000004)
 
#define PARALLEL_KEY_WAL_USAGE   UINT64CONST(0xA000000000000005)
 
#define PARALLEL_KEY_BUFFER_USAGE   UINT64CONST(0xA000000000000006)
 
#define ParallelTableScanFromBTShared(shared)   (ParallelTableScanDesc) ((char *) (shared) + BUFFERALIGN(sizeof(BTShared)))
 

Typedefs

typedef struct BTSpool BTSpool
 
typedef struct BTShared BTShared
 
typedef struct BTLeader BTLeader
 
typedef struct BTBuildState BTBuildState
 
typedef struct BTPageState BTPageState
 
typedef struct BTWriteState BTWriteState
 

Functions

static double _bt_spools_heapscan (Relation heap, Relation index, BTBuildState *buildstate, IndexInfo *indexInfo)
 
static void _bt_spooldestroy (BTSpool *btspool)
 
static void _bt_spool (BTSpool *btspool, ItemPointer self, Datum *values, bool *isnull)
 
static void _bt_leafbuild (BTSpool *btspool, BTSpool *btspool2)
 
static void _bt_build_callback (Relation index, ItemPointer tid, Datum *values, bool *isnull, bool tupleIsAlive, void *state)
 
static Page _bt_blnewpage (uint32 level)
 
static BTPageState_bt_pagestate (BTWriteState *wstate, uint32 level)
 
static void _bt_slideleft (Page page)
 
static void _bt_sortaddtup (Page page, Size itemsize, IndexTuple itup, OffsetNumber itup_off, bool newfirstdataitem)
 
static void _bt_buildadd (BTWriteState *wstate, BTPageState *state, IndexTuple itup, Size truncextra)
 
static void _bt_sort_dedup_finish_pending (BTWriteState *wstate, BTPageState *state, BTDedupState dstate)
 
static void _bt_uppershutdown (BTWriteState *wstate, BTPageState *state)
 
static void _bt_load (BTWriteState *wstate, BTSpool *btspool, BTSpool *btspool2)
 
static void _bt_begin_parallel (BTBuildState *buildstate, bool isconcurrent, int request)
 
static void _bt_end_parallel (BTLeader *btleader)
 
static Size _bt_parallel_estimate_shared (Relation heap, Snapshot snapshot)
 
static double _bt_parallel_heapscan (BTBuildState *buildstate, bool *brokenhotchain)
 
static void _bt_leader_participate_as_worker (BTBuildState *buildstate)
 
static void _bt_parallel_scan_and_sort (BTSpool *btspool, BTSpool *btspool2, BTShared *btshared, Sharedsort *sharedsort, Sharedsort *sharedsort2, int sortmem, bool progress)
 
IndexBuildResultbtbuild (Relation heap, Relation index, IndexInfo *indexInfo)
 
static void _bt_blwritepage (BTWriteState *wstate, Page page, BlockNumber blkno)
 
void _bt_parallel_build_main (dsm_segment *seg, shm_toc *toc)
 

Macro Definition Documentation

◆ PARALLEL_KEY_BTREE_SHARED

#define PARALLEL_KEY_BTREE_SHARED   UINT64CONST(0xA000000000000001)

Definition at line 69 of file nbtsort.c.

Referenced by _bt_begin_parallel(), and _bt_parallel_build_main().

◆ PARALLEL_KEY_BUFFER_USAGE

#define PARALLEL_KEY_BUFFER_USAGE   UINT64CONST(0xA000000000000006)

Definition at line 74 of file nbtsort.c.

Referenced by _bt_begin_parallel(), and _bt_parallel_build_main().

◆ PARALLEL_KEY_QUERY_TEXT

#define PARALLEL_KEY_QUERY_TEXT   UINT64CONST(0xA000000000000004)

Definition at line 72 of file nbtsort.c.

Referenced by _bt_begin_parallel(), and _bt_parallel_build_main().

◆ PARALLEL_KEY_TUPLESORT

#define PARALLEL_KEY_TUPLESORT   UINT64CONST(0xA000000000000002)

Definition at line 70 of file nbtsort.c.

Referenced by _bt_begin_parallel(), and _bt_parallel_build_main().

◆ PARALLEL_KEY_TUPLESORT_SPOOL2

#define PARALLEL_KEY_TUPLESORT_SPOOL2   UINT64CONST(0xA000000000000003)

Definition at line 71 of file nbtsort.c.

Referenced by _bt_begin_parallel(), and _bt_parallel_build_main().

◆ PARALLEL_KEY_WAL_USAGE

#define PARALLEL_KEY_WAL_USAGE   UINT64CONST(0xA000000000000005)

Definition at line 73 of file nbtsort.c.

Referenced by _bt_begin_parallel(), and _bt_parallel_build_main().

◆ ParallelTableScanFromBTShared

#define ParallelTableScanFromBTShared (   shared)    (ParallelTableScanDesc) ((char *) (shared) + BUFFERALIGN(sizeof(BTShared)))

Definition at line 164 of file nbtsort.c.

Referenced by _bt_begin_parallel(), and _bt_parallel_scan_and_sort().

Typedef Documentation

◆ BTBuildState

typedef struct BTBuildState BTBuildState

◆ BTLeader

typedef struct BTLeader BTLeader

◆ BTPageState

typedef struct BTPageState BTPageState

◆ BTShared

typedef struct BTShared BTShared

◆ BTSpool

typedef struct BTSpool BTSpool

◆ BTWriteState

typedef struct BTWriteState BTWriteState

Function Documentation

◆ _bt_begin_parallel()

static void _bt_begin_parallel ( BTBuildState buildstate,
bool  isconcurrent,
int  request 
)
static

Definition at line 1453 of file nbtsort.c.

References _bt_end_parallel(), _bt_leader_participate_as_worker(), _bt_parallel_estimate_shared(), Assert, BTShared::brokenhotchain, BTBuildState::btleader, BTLeader::btshared, BTLeader::bufferusage, ConditionVariableInit(), CreateParallelContext(), debug_query_string, DestroyParallelContext(), EnterParallelMode(), ParallelContext::estimator, ExitParallelMode(), GetTransactionSnapshot(), BTShared::havedead, BTSpool::heap, BTShared::heaprelid, BTSpool::index, BTShared::indexrelid, BTShared::indtuples, InitializeParallelDSM(), BTShared::isconcurrent, IsMVCCSnapshot, BTSpool::isunique, BTShared::isunique, LaunchParallelWorkers(), mul_size(), BTShared::mutex, BTShared::nparticipantsdone, BTLeader::nparticipanttuplesorts, ParallelContext::nworkers, ParallelContext::nworkers_launched, palloc0(), PARALLEL_KEY_BTREE_SHARED, PARALLEL_KEY_BUFFER_USAGE, PARALLEL_KEY_QUERY_TEXT, PARALLEL_KEY_TUPLESORT, PARALLEL_KEY_TUPLESORT_SPOOL2, PARALLEL_KEY_WAL_USAGE, ParallelTableScanFromBTShared, BTLeader::pcxt, RegisterSnapshot(), RelationGetRelid, BTShared::reltuples, BTShared::scantuplesortstates, ParallelContext::seg, BTLeader::sharedsort, BTLeader::sharedsort2, shm_toc_allocate(), shm_toc_estimate_chunk, shm_toc_estimate_keys, shm_toc_insert(), BTLeader::snapshot, SnapshotAny, SpinLockInit, BTBuildState::spool, table_parallelscan_initialize(), ParallelContext::toc, tuplesort_estimate_shared(), tuplesort_initialize_shared(), UnregisterSnapshot(), WaitForParallelWorkersToAttach(), BTLeader::walusage, and BTShared::workersdonecv.

Referenced by _bt_spools_heapscan().

1454 {
1455  ParallelContext *pcxt;
1456  int scantuplesortstates;
1457  Snapshot snapshot;
1458  Size estbtshared;
1459  Size estsort;
1460  BTShared *btshared;
1461  Sharedsort *sharedsort;
1462  Sharedsort *sharedsort2;
1463  BTSpool *btspool = buildstate->spool;
1464  BTLeader *btleader = (BTLeader *) palloc0(sizeof(BTLeader));
1465  WalUsage *walusage;
1466  BufferUsage *bufferusage;
1467  bool leaderparticipates = true;
1468  char *sharedquery;
1469  int querylen;
1470 
1471 #ifdef DISABLE_LEADER_PARTICIPATION
1472  leaderparticipates = false;
1473 #endif
1474 
1475  /*
1476  * Enter parallel mode, and create context for parallel build of btree
1477  * index
1478  */
1480  Assert(request > 0);
1481  pcxt = CreateParallelContext("postgres", "_bt_parallel_build_main",
1482  request);
1483 
1484  scantuplesortstates = leaderparticipates ? request + 1 : request;
1485 
1486  /*
1487  * Prepare for scan of the base relation. In a normal index build, we use
1488  * SnapshotAny because we must retrieve all tuples and do our own time
1489  * qual checks (because we have to index RECENTLY_DEAD tuples). In a
1490  * concurrent build, we take a regular MVCC snapshot and index whatever's
1491  * live according to that.
1492  */
1493  if (!isconcurrent)
1494  snapshot = SnapshotAny;
1495  else
1497 
1498  /*
1499  * Estimate size for our own PARALLEL_KEY_BTREE_SHARED workspace, and
1500  * PARALLEL_KEY_TUPLESORT tuplesort workspace
1501  */
1502  estbtshared = _bt_parallel_estimate_shared(btspool->heap, snapshot);
1503  shm_toc_estimate_chunk(&pcxt->estimator, estbtshared);
1504  estsort = tuplesort_estimate_shared(scantuplesortstates);
1505  shm_toc_estimate_chunk(&pcxt->estimator, estsort);
1506 
1507  /*
1508  * Unique case requires a second spool, and so we may have to account for
1509  * another shared workspace for that -- PARALLEL_KEY_TUPLESORT_SPOOL2
1510  */
1511  if (!btspool->isunique)
1512  shm_toc_estimate_keys(&pcxt->estimator, 2);
1513  else
1514  {
1515  shm_toc_estimate_chunk(&pcxt->estimator, estsort);
1516  shm_toc_estimate_keys(&pcxt->estimator, 3);
1517  }
1518 
1519  /*
1520  * Estimate space for WalUsage and BufferUsage -- PARALLEL_KEY_WAL_USAGE
1521  * and PARALLEL_KEY_BUFFER_USAGE.
1522  *
1523  * If there are no extensions loaded that care, we could skip this. We
1524  * have no way of knowing whether anyone's looking at pgWalUsage or
1525  * pgBufferUsage, so do it unconditionally.
1526  */
1528  mul_size(sizeof(WalUsage), pcxt->nworkers));
1529  shm_toc_estimate_keys(&pcxt->estimator, 1);
1531  mul_size(sizeof(BufferUsage), pcxt->nworkers));
1532  shm_toc_estimate_keys(&pcxt->estimator, 1);
1533 
1534  /* Finally, estimate PARALLEL_KEY_QUERY_TEXT space */
1535  querylen = strlen(debug_query_string);
1536  shm_toc_estimate_chunk(&pcxt->estimator, querylen + 1);
1537  shm_toc_estimate_keys(&pcxt->estimator, 1);
1538 
1539  /* Everyone's had a chance to ask for space, so now create the DSM */
1540  InitializeParallelDSM(pcxt);
1541 
1542  /* If no DSM segment was available, back out (do serial build) */
1543  if (pcxt->seg == NULL)
1544  {
1545  if (IsMVCCSnapshot(snapshot))
1546  UnregisterSnapshot(snapshot);
1547  DestroyParallelContext(pcxt);
1548  ExitParallelMode();
1549  return;
1550  }
1551 
1552  /* Store shared build state, for which we reserved space */
1553  btshared = (BTShared *) shm_toc_allocate(pcxt->toc, estbtshared);
1554  /* Initialize immutable state */
1555  btshared->heaprelid = RelationGetRelid(btspool->heap);
1556  btshared->indexrelid = RelationGetRelid(btspool->index);
1557  btshared->isunique = btspool->isunique;
1558  btshared->isconcurrent = isconcurrent;
1559  btshared->scantuplesortstates = scantuplesortstates;
1561  SpinLockInit(&btshared->mutex);
1562  /* Initialize mutable state */
1563  btshared->nparticipantsdone = 0;
1564  btshared->reltuples = 0.0;
1565  btshared->havedead = false;
1566  btshared->indtuples = 0.0;
1567  btshared->brokenhotchain = false;
1570  snapshot);
1571 
1572  /*
1573  * Store shared tuplesort-private state, for which we reserved space.
1574  * Then, initialize opaque state using tuplesort routine.
1575  */
1576  sharedsort = (Sharedsort *) shm_toc_allocate(pcxt->toc, estsort);
1577  tuplesort_initialize_shared(sharedsort, scantuplesortstates,
1578  pcxt->seg);
1579 
1580  shm_toc_insert(pcxt->toc, PARALLEL_KEY_BTREE_SHARED, btshared);
1581  shm_toc_insert(pcxt->toc, PARALLEL_KEY_TUPLESORT, sharedsort);
1582 
1583  /* Unique case requires a second spool, and associated shared state */
1584  if (!btspool->isunique)
1585  sharedsort2 = NULL;
1586  else
1587  {
1588  /*
1589  * Store additional shared tuplesort-private state, for which we
1590  * reserved space. Then, initialize opaque state using tuplesort
1591  * routine.
1592  */
1593  sharedsort2 = (Sharedsort *) shm_toc_allocate(pcxt->toc, estsort);
1594  tuplesort_initialize_shared(sharedsort2, scantuplesortstates,
1595  pcxt->seg);
1596 
1597  shm_toc_insert(pcxt->toc, PARALLEL_KEY_TUPLESORT_SPOOL2, sharedsort2);
1598  }
1599 
1600  /* Store query string for workers */
1601  sharedquery = (char *) shm_toc_allocate(pcxt->toc, querylen + 1);
1602  memcpy(sharedquery, debug_query_string, querylen + 1);
1603  shm_toc_insert(pcxt->toc, PARALLEL_KEY_QUERY_TEXT, sharedquery);
1604 
1605  /*
1606  * Allocate space for each worker's WalUsage and BufferUsage; no need to
1607  * initialize.
1608  */
1609  walusage = shm_toc_allocate(pcxt->toc,
1610  mul_size(sizeof(WalUsage), pcxt->nworkers));
1611  shm_toc_insert(pcxt->toc, PARALLEL_KEY_WAL_USAGE, walusage);
1612  bufferusage = shm_toc_allocate(pcxt->toc,
1613  mul_size(sizeof(BufferUsage), pcxt->nworkers));
1614  shm_toc_insert(pcxt->toc, PARALLEL_KEY_BUFFER_USAGE, bufferusage);
1615 
1616  /* Launch workers, saving status for leader/caller */
1617  LaunchParallelWorkers(pcxt);
1618  btleader->pcxt = pcxt;
1619  btleader->nparticipanttuplesorts = pcxt->nworkers_launched;
1620  if (leaderparticipates)
1621  btleader->nparticipanttuplesorts++;
1622  btleader->btshared = btshared;
1623  btleader->sharedsort = sharedsort;
1624  btleader->sharedsort2 = sharedsort2;
1625  btleader->snapshot = snapshot;
1626  btleader->walusage = walusage;
1627  btleader->bufferusage = bufferusage;
1628 
1629  /* If no workers were successfully launched, back out (do serial build) */
1630  if (pcxt->nworkers_launched == 0)
1631  {
1632  _bt_end_parallel(btleader);
1633  return;
1634  }
1635 
1636  /* Save leader state now that it's clear build will be parallel */
1637  buildstate->btleader = btleader;
1638 
1639  /* Join heap scan ourselves */
1640  if (leaderparticipates)
1642 
1643  /*
1644  * Caller needs to wait for all launched workers when we return. Make
1645  * sure that the failure-to-start case will not hang forever.
1646  */
1648 }
Sharedsort * sharedsort2
Definition: nbtsort.c:195
int scantuplesortstates
Definition: nbtsort.c:111
#define PARALLEL_KEY_TUPLESORT
Definition: nbtsort.c:70
ParallelContext * CreateParallelContext(const char *library_name, const char *function_name, int nworkers)
Definition: parallel.c:164
BTShared * btshared
Definition: nbtsort.c:193
int nparticipantsdone
Definition: nbtsort.c:145
Snapshot RegisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:865
Oid indexrelid
Definition: nbtsort.c:108
dsm_segment * seg
Definition: parallel.h:43
Sharedsort * sharedsort
Definition: nbtsort.c:194
shm_toc_estimator estimator
Definition: parallel.h:42
#define SpinLockInit(lock)
Definition: spin.h:60
Snapshot snapshot
Definition: nbtsort.c:196
bool isunique
Definition: nbtsort.c:109
#define ParallelTableScanFromBTShared(shared)
Definition: nbtsort.c:164
bool isconcurrent
Definition: nbtsort.c:110
static void _bt_end_parallel(BTLeader *btleader)
Definition: nbtsort.c:1654
void tuplesort_initialize_shared(Sharedsort *shared, int nWorkers, dsm_segment *seg)
Definition: tuplesort.c:4502
#define shm_toc_estimate_chunk(e, sz)
Definition: shm_toc.h:51
BTSpool * spool
Definition: nbtsort.c:212
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:306
ParallelContext * pcxt
Definition: nbtsort.c:173
Relation heap
Definition: nbtsort.c:90
void ConditionVariableInit(ConditionVariable *cv)
void DestroyParallelContext(ParallelContext *pcxt)
Definition: parallel.c:904
#define PARALLEL_KEY_BUFFER_USAGE
Definition: nbtsort.c:74
bool isunique
Definition: nbtsort.c:92
void ExitParallelMode(void)
Definition: xact.c:977
Oid heaprelid
Definition: nbtsort.c:107
BufferUsage * bufferusage
Definition: nbtsort.c:198
#define PARALLEL_KEY_QUERY_TEXT
Definition: nbtsort.c:72
#define PARALLEL_KEY_TUPLESORT_SPOOL2
Definition: nbtsort.c:71
int nworkers_launched
Definition: parallel.h:38
bool brokenhotchain
Definition: nbtsort.c:149
void LaunchParallelWorkers(ParallelContext *pcxt)
Definition: parallel.c:527
void UnregisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:907
Relation index
Definition: nbtsort.c:91
const char * debug_query_string
Definition: postgres.c:88
void InitializeParallelDSM(ParallelContext *pcxt)
Definition: parallel.c:202
Size mul_size(Size s1, Size s2)
Definition: shmem.c:515
void * palloc0(Size size)
Definition: mcxt.c:980
BTLeader * btleader
Definition: nbtsort.c:226
double reltuples
Definition: nbtsort.c:146
double indtuples
Definition: nbtsort.c:148
#define IsMVCCSnapshot(snapshot)
Definition: snapmgr.h:97
slock_t mutex
Definition: nbtsort.c:127
WalUsage * walusage
Definition: nbtsort.c:197
bool havedead
Definition: nbtsort.c:147
#define Assert(condition)
Definition: c.h:738
int nparticipanttuplesorts
Definition: nbtsort.c:181
size_t Size
Definition: c.h:466
static Size _bt_parallel_estimate_shared(Relation heap, Snapshot snapshot)
Definition: nbtsort.c:1680
#define shm_toc_estimate_keys(e, cnt)
Definition: shm_toc.h:53
void EnterParallelMode(void)
Definition: xact.c:964
void * shm_toc_allocate(shm_toc *toc, Size nbytes)
Definition: shm_toc.c:88
static void _bt_leader_participate_as_worker(BTBuildState *buildstate)
Definition: nbtsort.c:1734
Size tuplesort_estimate_shared(int nWorkers)
Definition: tuplesort.c:4481
#define SnapshotAny
Definition: snapmgr.h:69
#define PARALLEL_KEY_WAL_USAGE
Definition: nbtsort.c:73
void shm_toc_insert(shm_toc *toc, uint64 key, void *address)
Definition: shm_toc.c:171
ConditionVariable workersdonecv
Definition: nbtsort.c:119
#define PARALLEL_KEY_BTREE_SHARED
Definition: nbtsort.c:69
void table_parallelscan_initialize(Relation rel, ParallelTableScanDesc pscan, Snapshot snapshot)
Definition: tableam.c:141
void WaitForParallelWorkersToAttach(ParallelContext *pcxt)
Definition: parallel.c:647
#define RelationGetRelid(relation)
Definition: rel.h:456
shm_toc * toc
Definition: parallel.h:45

◆ _bt_blnewpage()

static Page _bt_blnewpage ( uint32  level)
static

Definition at line 611 of file nbtsort.c.

References _bt_pageinit(), BTP_LEAF, BTPageOpaqueData::btpo, BTPageOpaqueData::btpo_cycleid, BTPageOpaqueData::btpo_flags, BTPageOpaqueData::btpo_next, BTPageOpaqueData::btpo_prev, BTPageOpaqueData::level, P_NONE, PageGetSpecialPointer, and palloc().

Referenced by _bt_buildadd(), and _bt_pagestate().

612 {
613  Page page;
614  BTPageOpaque opaque;
615 
616  page = (Page) palloc(BLCKSZ);
617 
618  /* Zero the page and set up standard page header info */
619  _bt_pageinit(page, BLCKSZ);
620 
621  /* Initialize BT opaque state */
622  opaque = (BTPageOpaque) PageGetSpecialPointer(page);
623  opaque->btpo_prev = opaque->btpo_next = P_NONE;
624  opaque->btpo.level = level;
625  opaque->btpo_flags = (level > 0) ? 0 : BTP_LEAF;
626  opaque->btpo_cycleid = 0;
627 
628  /* Make the P_HIKEY line pointer appear allocated */
629  ((PageHeader) page)->pd_lower += sizeof(ItemIdData);
630 
631  return page;
632 }
BlockNumber btpo_next
Definition: nbtree.h:59
#define BTP_LEAF
Definition: nbtree.h:72
union BTPageOpaqueData::@45 btpo
#define P_NONE
Definition: nbtree.h:206
BTPageOpaqueData * BTPageOpaque
Definition: nbtree.h:69
BTCycleId btpo_cycleid
Definition: nbtree.h:66
BlockNumber btpo_prev
Definition: nbtree.h:58
struct ItemIdData ItemIdData
uint32 level
Definition: nbtree.h:62
PageHeaderData * PageHeader
Definition: bufpage.h:166
#define PageGetSpecialPointer(page)
Definition: bufpage.h:326
void * palloc(Size size)
Definition: mcxt.c:949
void _bt_pageinit(Page page, Size size)
Definition: nbtpage.c:959
uint16 btpo_flags
Definition: nbtree.h:65
Pointer Page
Definition: bufpage.h:78

◆ _bt_blwritepage()

static void _bt_blwritepage ( BTWriteState wstate,
Page  page,
BlockNumber  blkno 
)
static

Definition at line 638 of file nbtsort.c.

References BTWriteState::btws_pages_written, BTWriteState::btws_use_wal, BTWriteState::btws_zeropage, BTWriteState::index, log_newpage(), MAIN_FORKNUM, PageSetChecksumInplace(), palloc0(), pfree(), RelationData::rd_node, RelationData::rd_smgr, RelationOpenSmgr, smgrextend(), and smgrwrite().

Referenced by _bt_buildadd(), and _bt_uppershutdown().

639 {
640  /* Ensure rd_smgr is open (could have been closed by relcache flush!) */
641  RelationOpenSmgr(wstate->index);
642 
643  /* XLOG stuff */
644  if (wstate->btws_use_wal)
645  {
646  /* We use the XLOG_FPI record type for this */
647  log_newpage(&wstate->index->rd_node, MAIN_FORKNUM, blkno, page, true);
648  }
649 
650  /*
651  * If we have to write pages nonsequentially, fill in the space with
652  * zeroes until we come back and overwrite. This is not logically
653  * necessary on standard Unix filesystems (unwritten space will read as
654  * zeroes anyway), but it should help to avoid fragmentation. The dummy
655  * pages aren't WAL-logged though.
656  */
657  while (blkno > wstate->btws_pages_written)
658  {
659  if (!wstate->btws_zeropage)
660  wstate->btws_zeropage = (Page) palloc0(BLCKSZ);
661  /* don't set checksum for all-zero page */
663  wstate->btws_pages_written++,
664  (char *) wstate->btws_zeropage,
665  true);
666  }
667 
668  PageSetChecksumInplace(page, blkno);
669 
670  /*
671  * Now write the page. There's no need for smgr to schedule an fsync for
672  * this write; we'll do it ourselves before ending the build.
673  */
674  if (blkno == wstate->btws_pages_written)
675  {
676  /* extending the file... */
677  smgrextend(wstate->index->rd_smgr, MAIN_FORKNUM, blkno,
678  (char *) page, true);
679  wstate->btws_pages_written++;
680  }
681  else
682  {
683  /* overwriting a block we zero-filled before */
684  smgrwrite(wstate->index->rd_smgr, MAIN_FORKNUM, blkno,
685  (char *) page, true);
686  }
687 
688  pfree(page);
689 }
Page btws_zeropage
Definition: nbtsort.c:256
struct SMgrRelationData * rd_smgr
Definition: rel.h:57
bool btws_use_wal
Definition: nbtsort.c:253
#define RelationOpenSmgr(relation)
Definition: rel.h:513
void pfree(void *pointer)
Definition: mcxt.c:1056
void smgrwrite(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum, char *buffer, bool skipFsync)
Definition: smgr.c:513
Relation index
Definition: nbtsort.c:251
BlockNumber btws_pages_written
Definition: nbtsort.c:255
void * palloc0(Size size)
Definition: mcxt.c:980
RelFileNode rd_node
Definition: rel.h:55
void PageSetChecksumInplace(Page page, BlockNumber blkno)
Definition: bufpage.c:1194
void smgrextend(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum, char *buffer, bool skipFsync)
Definition: smgr.c:462
XLogRecPtr log_newpage(RelFileNode *rnode, ForkNumber forkNum, BlockNumber blkno, Page page, bool page_std)
Definition: xloginsert.c:977
Pointer Page
Definition: bufpage.h:78

◆ _bt_build_callback()

static void _bt_build_callback ( Relation  index,
ItemPointer  tid,
Datum values,
bool isnull,
bool  tupleIsAlive,
void *  state 
)
static

Definition at line 582 of file nbtsort.c.

References _bt_spool(), BTBuildState::havedead, BTBuildState::indtuples, BTBuildState::spool, and BTBuildState::spool2.

Referenced by _bt_parallel_scan_and_sort(), and _bt_spools_heapscan().

588 {
589  BTBuildState *buildstate = (BTBuildState *) state;
590 
591  /*
592  * insert the index tuple into the appropriate spool file for subsequent
593  * processing
594  */
595  if (tupleIsAlive || buildstate->spool2 == NULL)
596  _bt_spool(buildstate->spool, tid, values, isnull);
597  else
598  {
599  /* dead tuples are put into spool2 */
600  buildstate->havedead = true;
601  _bt_spool(buildstate->spool2, tid, values, isnull);
602  }
603 
604  buildstate->indtuples += 1;
605 }
bool havedead
Definition: nbtsort.c:210
BTSpool * spool
Definition: nbtsort.c:212
BTSpool * spool2
Definition: nbtsort.c:218
double indtuples
Definition: nbtsort.c:219
Definition: regguts.h:298
static Datum values[MAXATTR]
Definition: bootstrap.c:167
static void _bt_spool(BTSpool *btspool, ItemPointer self, Datum *values, bool *isnull)
Definition: nbtsort.c:528

◆ _bt_buildadd()

static void _bt_buildadd ( BTWriteState wstate,
BTPageState state,
IndexTuple  itup,
Size  truncextra 
)
static

Definition at line 833 of file nbtsort.c.

References _bt_blnewpage(), _bt_blwritepage(), _bt_check_third_page(), _bt_pagestate(), _bt_sortaddtup(), _bt_truncate(), Assert, BTMaxItemSize, BTPageOpaqueData::btpo_next, BTPageOpaqueData::btpo_prev, BTPageState::btps_blkno, BTPageState::btps_lastextra, BTPageState::btps_lastoff, BTPageState::btps_level, BTPageState::btps_lowkey, BTPageState::btps_next, BTPageState::btps_page, BTreeTupleGetNAtts, BTreeTupleSetDownLink(), BTreeTupleSetNAtts(), BTWriteState::btws_pages_alloced, CHECK_FOR_INTERRUPTS, CopyIndexTuple(), elog, ERROR, BTWriteState::heap, BTWriteState::index, IndexRelationGetNumberOfKeyAttributes, IndexTupleSize, BTWriteState::inskey, ItemIdGetLength, ItemIdSetUnused, MAXALIGN, OffsetNumberNext, OffsetNumberPrev, P_FIRSTKEY, P_HIKEY, P_LEFTMOST, P_NONE, PageGetFreeSpace(), PageGetItem, PageGetItemId, PageGetSpecialPointer, PageIndexTupleOverwrite(), palloc0(), pfree(), IndexTupleData::t_info, and unlikely.

Referenced by _bt_load(), _bt_sort_dedup_finish_pending(), and _bt_uppershutdown().

835 {
836  Page npage;
837  BlockNumber nblkno;
838  OffsetNumber last_off;
839  Size last_truncextra;
840  Size pgspc;
841  Size itupsz;
842  bool isleaf;
843 
844  /*
845  * This is a handy place to check for cancel interrupts during the btree
846  * load phase of index creation.
847  */
849 
850  npage = state->btps_page;
851  nblkno = state->btps_blkno;
852  last_off = state->btps_lastoff;
853  last_truncextra = state->btps_lastextra;
854  state->btps_lastextra = truncextra;
855 
856  pgspc = PageGetFreeSpace(npage);
857  itupsz = IndexTupleSize(itup);
858  itupsz = MAXALIGN(itupsz);
859  /* Leaf case has slightly different rules due to suffix truncation */
860  isleaf = (state->btps_level == 0);
861 
862  /*
863  * Check whether the new item can fit on a btree page on current level at
864  * all.
865  *
866  * Every newly built index will treat heap TID as part of the keyspace,
867  * which imposes the requirement that new high keys must occasionally have
868  * a heap TID appended within _bt_truncate(). That may leave a new pivot
869  * tuple one or two MAXALIGN() quantums larger than the original
870  * firstright tuple it's derived from. v4 deals with the problem by
871  * decreasing the limit on the size of tuples inserted on the leaf level
872  * by the same small amount. Enforce the new v4+ limit on the leaf level,
873  * and the old limit on internal levels, since pivot tuples may need to
874  * make use of the reserved space. This should never fail on internal
875  * pages.
876  */
877  if (unlikely(itupsz > BTMaxItemSize(npage)))
878  _bt_check_third_page(wstate->index, wstate->heap, isleaf, npage,
879  itup);
880 
881  /*
882  * Check to see if current page will fit new item, with space left over to
883  * append a heap TID during suffix truncation when page is a leaf page.
884  *
885  * It is guaranteed that we can fit at least 2 non-pivot tuples plus a
886  * high key with heap TID when finishing off a leaf page, since we rely on
887  * _bt_check_third_page() rejecting oversized non-pivot tuples. On
888  * internal pages we can always fit 3 pivot tuples with larger internal
889  * page tuple limit (includes page high key).
890  *
891  * Most of the time, a page is only "full" in the sense that the soft
892  * fillfactor-wise limit has been exceeded. However, we must always leave
893  * at least two items plus a high key on each page before starting a new
894  * page. Disregard fillfactor and insert on "full" current page if we
895  * don't have the minimum number of items yet. (Note that we deliberately
896  * assume that suffix truncation neither enlarges nor shrinks new high key
897  * when applying soft limit, except when last tuple has a posting list.)
898  */
899  Assert(last_truncextra == 0 || isleaf);
900  if (pgspc < itupsz + (isleaf ? MAXALIGN(sizeof(ItemPointerData)) : 0) ||
901  (pgspc + last_truncextra < state->btps_full && last_off > P_FIRSTKEY))
902  {
903  /*
904  * Finish off the page and write it out.
905  */
906  Page opage = npage;
907  BlockNumber oblkno = nblkno;
908  ItemId ii;
909  ItemId hii;
910  IndexTuple oitup;
911 
912  /* Create new page of same level */
913  npage = _bt_blnewpage(state->btps_level);
914 
915  /* and assign it a page position */
916  nblkno = wstate->btws_pages_alloced++;
917 
918  /*
919  * We copy the last item on the page into the new page, and then
920  * rearrange the old page so that the 'last item' becomes its high key
921  * rather than a true data item. There had better be at least two
922  * items on the page already, else the page would be empty of useful
923  * data.
924  */
925  Assert(last_off > P_FIRSTKEY);
926  ii = PageGetItemId(opage, last_off);
927  oitup = (IndexTuple) PageGetItem(opage, ii);
928  _bt_sortaddtup(npage, ItemIdGetLength(ii), oitup, P_FIRSTKEY,
929  !isleaf);
930 
931  /*
932  * Move 'last' into the high key position on opage. _bt_blnewpage()
933  * allocated empty space for a line pointer when opage was first
934  * created, so this is a matter of rearranging already-allocated space
935  * on page, and initializing high key line pointer. (Actually, leaf
936  * pages must also swap oitup with a truncated version of oitup, which
937  * is sometimes larger than oitup, though never by more than the space
938  * needed to append a heap TID.)
939  */
940  hii = PageGetItemId(opage, P_HIKEY);
941  *hii = *ii;
942  ItemIdSetUnused(ii); /* redundant */
943  ((PageHeader) opage)->pd_lower -= sizeof(ItemIdData);
944 
945  if (isleaf)
946  {
947  IndexTuple lastleft;
948  IndexTuple truncated;
949 
950  /*
951  * Truncate away any unneeded attributes from high key on leaf
952  * level. This is only done at the leaf level because downlinks
953  * in internal pages are either negative infinity items, or get
954  * their contents from copying from one level down. See also:
955  * _bt_split().
956  *
957  * We don't try to bias our choice of split point to make it more
958  * likely that _bt_truncate() can truncate away more attributes,
959  * whereas the split point used within _bt_split() is chosen much
960  * more delicately. Even still, the lastleft and firstright
961  * tuples passed to _bt_truncate() here are at least not fully
962  * equal to each other when deduplication is used, unless there is
963  * a large group of duplicates (also, unique index builds usually
964  * have few or no spool2 duplicates). When the split point is
965  * between two unequal tuples, _bt_truncate() will avoid including
966  * a heap TID in the new high key, which is the most important
967  * benefit of suffix truncation.
968  *
969  * Overwrite the old item with new truncated high key directly.
970  * oitup is already located at the physical beginning of tuple
971  * space, so this should directly reuse the existing tuple space.
972  */
973  ii = PageGetItemId(opage, OffsetNumberPrev(last_off));
974  lastleft = (IndexTuple) PageGetItem(opage, ii);
975 
976  Assert(IndexTupleSize(oitup) > last_truncextra);
977  truncated = _bt_truncate(wstate->index, lastleft, oitup,
978  wstate->inskey);
979  if (!PageIndexTupleOverwrite(opage, P_HIKEY, (Item) truncated,
980  IndexTupleSize(truncated)))
981  elog(ERROR, "failed to add high key to the index page");
982  pfree(truncated);
983 
984  /* oitup should continue to point to the page's high key */
985  hii = PageGetItemId(opage, P_HIKEY);
986  oitup = (IndexTuple) PageGetItem(opage, hii);
987  }
988 
989  /*
990  * Link the old page into its parent, using its low key. If we don't
991  * have a parent, we have to create one; this adds a new btree level.
992  */
993  if (state->btps_next == NULL)
994  state->btps_next = _bt_pagestate(wstate, state->btps_level + 1);
995 
996  Assert((BTreeTupleGetNAtts(state->btps_lowkey, wstate->index) <=
998  BTreeTupleGetNAtts(state->btps_lowkey, wstate->index) > 0) ||
1000  Assert(BTreeTupleGetNAtts(state->btps_lowkey, wstate->index) == 0 ||
1002  BTreeTupleSetDownLink(state->btps_lowkey, oblkno);
1003  _bt_buildadd(wstate, state->btps_next, state->btps_lowkey, 0);
1004  pfree(state->btps_lowkey);
1005 
1006  /*
1007  * Save a copy of the high key from the old page. It is also the low
1008  * key for the new page.
1009  */
1010  state->btps_lowkey = CopyIndexTuple(oitup);
1011 
1012  /*
1013  * Set the sibling links for both pages.
1014  */
1015  {
1016  BTPageOpaque oopaque = (BTPageOpaque) PageGetSpecialPointer(opage);
1017  BTPageOpaque nopaque = (BTPageOpaque) PageGetSpecialPointer(npage);
1018 
1019  oopaque->btpo_next = nblkno;
1020  nopaque->btpo_prev = oblkno;
1021  nopaque->btpo_next = P_NONE; /* redundant */
1022  }
1023 
1024  /*
1025  * Write out the old page. We never need to touch it again, so we can
1026  * free the opage workspace too.
1027  */
1028  _bt_blwritepage(wstate, opage, oblkno);
1029 
1030  /*
1031  * Reset last_off to point to new page
1032  */
1033  last_off = P_FIRSTKEY;
1034  }
1035 
1036  /*
1037  * By here, either original page is still the current page, or a new page
1038  * was created that became the current page. Either way, the current page
1039  * definitely has space for new item.
1040  *
1041  * If the new item is the first for its page, it must also be the first
1042  * item on its entire level. On later same-level pages, a low key for a
1043  * page will be copied from the prior page in the code above. Generate a
1044  * minus infinity low key here instead.
1045  */
1046  if (last_off == P_HIKEY)
1047  {
1048  Assert(state->btps_lowkey == NULL);
1049  state->btps_lowkey = palloc0(sizeof(IndexTupleData));
1050  state->btps_lowkey->t_info = sizeof(IndexTupleData);
1051  BTreeTupleSetNAtts(state->btps_lowkey, 0, false);
1052  }
1053 
1054  /*
1055  * Add the new item into the current page.
1056  */
1057  last_off = OffsetNumberNext(last_off);
1058  _bt_sortaddtup(npage, itupsz, itup, last_off,
1059  !isleaf && last_off == P_FIRSTKEY);
1060 
1061  state->btps_page = npage;
1062  state->btps_blkno = nblkno;
1063  state->btps_lastoff = last_off;
1064 }
BlockNumber btpo_next
Definition: nbtree.h:59
BlockNumber btws_pages_alloced
Definition: nbtsort.c:254
Pointer Item
Definition: item.h:17
#define P_NONE
Definition: nbtree.h:206
uint32 BlockNumber
Definition: block.h:31
BlockNumber btps_blkno
Definition: nbtsort.c:236
#define BTreeTupleGetNAtts(itup, rel)
Definition: nbtree.h:445
static void _bt_blwritepage(BTWriteState *wstate, Page page, BlockNumber blkno)
Definition: nbtsort.c:638
BTPageOpaqueData * BTPageOpaque
Definition: nbtree.h:69
Size PageGetFreeSpace(Page page)
Definition: bufpage.c:574
uint16 OffsetNumber
Definition: off.h:24
static void BTreeTupleSetNAtts(IndexTuple itup, uint16 nkeyatts, bool heaptid)
Definition: nbtree.h:463
IndexTuple _bt_truncate(Relation rel, IndexTuple lastleft, IndexTuple firstright, BTScanInsert itup_key)
Definition: nbtutils.c:2199
Page btps_page
Definition: nbtsort.c:235
void pfree(void *pointer)
Definition: mcxt.c:1056
#define ItemIdGetLength(itemId)
Definition: itemid.h:59
#define ERROR
Definition: elog.h:43
bool PageIndexTupleOverwrite(Page page, OffsetNumber offnum, Item newtup, Size newsize)
Definition: bufpage.c:1060
BlockNumber btpo_prev
Definition: nbtree.h:58
IndexTuple CopyIndexTuple(IndexTuple source)
Definition: indextuple.c:510
OffsetNumber btps_lastoff
Definition: nbtsort.c:238
static void _bt_sortaddtup(Page page, Size itemsize, IndexTuple itup, OffsetNumber itup_off, bool newfirstdataitem)
Definition: nbtsort.c:763
IndexTupleData * IndexTuple
Definition: itup.h:53
#define P_FIRSTKEY
Definition: nbtree.h:243
#define P_LEFTMOST(opaque)
Definition: nbtree.h:212
struct ItemIdData ItemIdData
static void BTreeTupleSetDownLink(IndexTuple pivot, BlockNumber blkno)
Definition: nbtree.h:430
#define IndexRelationGetNumberOfKeyAttributes(relation)
Definition: rel.h:475
Size btps_lastextra
Definition: nbtsort.c:239
Relation index
Definition: nbtsort.c:251
#define PageGetItemId(page, offsetNumber)
Definition: bufpage.h:235
void * palloc0(Size size)
Definition: mcxt.c:980
uint32 btps_level
Definition: nbtsort.c:240
struct IndexTupleData IndexTupleData
static BTPageState * _bt_pagestate(BTWriteState *wstate, uint32 level)
Definition: nbtsort.c:696
struct BTPageState * btps_next
Definition: nbtsort.c:242
BTScanInsert inskey
Definition: nbtsort.c:252
IndexTuple btps_lowkey
Definition: nbtsort.c:237
static void _bt_buildadd(BTWriteState *wstate, BTPageState *state, IndexTuple itup, Size truncextra)
Definition: nbtsort.c:833
PageHeaderData * PageHeader
Definition: bufpage.h:166
#define Assert(condition)
Definition: c.h:738
#define OffsetNumberNext(offsetNumber)
Definition: off.h:52
size_t Size
Definition: c.h:466
#define PageGetSpecialPointer(page)
Definition: bufpage.h:326
#define OffsetNumberPrev(offsetNumber)
Definition: off.h:54
#define MAXALIGN(LEN)
Definition: c.h:691
void _bt_check_third_page(Relation rel, Relation heap, bool needheaptidspace, Page page, IndexTuple newtup)
Definition: nbtutils.c:2633
#define BTMaxItemSize(page)
Definition: nbtree.h:157
#define P_HIKEY
Definition: nbtree.h:242
static Page _bt_blnewpage(uint32 level)
Definition: nbtsort.c:611
#define elog(elevel,...)
Definition: elog.h:214
#define unlikely(x)
Definition: c.h:206
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:99
unsigned short t_info
Definition: itup.h:49
Relation heap
Definition: nbtsort.c:250
#define ItemIdSetUnused(itemId)
Definition: itemid.h:128
#define PageGetItem(page, itemId)
Definition: bufpage.h:340
Pointer Page
Definition: bufpage.h:78
#define IndexTupleSize(itup)
Definition: itup.h:71

◆ _bt_end_parallel()

static void _bt_end_parallel ( BTLeader btleader)
static

Definition at line 1654 of file nbtsort.c.

References BTLeader::bufferusage, DestroyParallelContext(), ExitParallelMode(), i, InstrAccumParallelQuery(), IsMVCCSnapshot, ParallelContext::nworkers_launched, BTLeader::pcxt, BTLeader::snapshot, UnregisterSnapshot(), WaitForParallelWorkersToFinish(), and BTLeader::walusage.

Referenced by _bt_begin_parallel(), and btbuild().

1655 {
1656  int i;
1657 
1658  /* Shutdown worker processes */
1660 
1661  /*
1662  * Next, accumulate WAL usage. (This must wait for the workers to finish,
1663  * or we might get incomplete data.)
1664  */
1665  for (i = 0; i < btleader->pcxt->nworkers_launched; i++)
1666  InstrAccumParallelQuery(&btleader->bufferusage[i], &btleader->walusage[i]);
1667 
1668  /* Free last reference to MVCC snapshot, if one was used */
1669  if (IsMVCCSnapshot(btleader->snapshot))
1670  UnregisterSnapshot(btleader->snapshot);
1671  DestroyParallelContext(btleader->pcxt);
1672  ExitParallelMode();
1673 }
Snapshot snapshot
Definition: nbtsort.c:196
ParallelContext * pcxt
Definition: nbtsort.c:173
void WaitForParallelWorkersToFinish(ParallelContext *pcxt)
Definition: parallel.c:750
void DestroyParallelContext(ParallelContext *pcxt)
Definition: parallel.c:904
void ExitParallelMode(void)
Definition: xact.c:977
BufferUsage * bufferusage
Definition: nbtsort.c:198
int nworkers_launched
Definition: parallel.h:38
void InstrAccumParallelQuery(BufferUsage *bufusage, WalUsage *walusage)
Definition: instrument.c:199
void UnregisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:907
#define IsMVCCSnapshot(snapshot)
Definition: snapmgr.h:97
WalUsage * walusage
Definition: nbtsort.c:197
int i

◆ _bt_leader_participate_as_worker()

static void _bt_leader_participate_as_worker ( BTBuildState buildstate)
static

Definition at line 1734 of file nbtsort.c.

References _bt_parallel_scan_and_sort(), BTBuildState::btleader, BTLeader::btshared, BTSpool::heap, BTSpool::index, BTSpool::isunique, BTShared::isunique, log_btree_build_stats, maintenance_work_mem, BTLeader::nparticipanttuplesorts, palloc0(), ResetUsage(), BTLeader::sharedsort, BTLeader::sharedsort2, ShowUsage(), and BTBuildState::spool.

Referenced by _bt_begin_parallel().

1735 {
1736  BTLeader *btleader = buildstate->btleader;
1737  BTSpool *leaderworker;
1738  BTSpool *leaderworker2;
1739  int sortmem;
1740 
1741  /* Allocate memory and initialize private spool */
1742  leaderworker = (BTSpool *) palloc0(sizeof(BTSpool));
1743  leaderworker->heap = buildstate->spool->heap;
1744  leaderworker->index = buildstate->spool->index;
1745  leaderworker->isunique = buildstate->spool->isunique;
1746 
1747  /* Initialize second spool, if required */
1748  if (!btleader->btshared->isunique)
1749  leaderworker2 = NULL;
1750  else
1751  {
1752  /* Allocate memory for worker's own private secondary spool */
1753  leaderworker2 = (BTSpool *) palloc0(sizeof(BTSpool));
1754 
1755  /* Initialize worker's own secondary spool */
1756  leaderworker2->heap = leaderworker->heap;
1757  leaderworker2->index = leaderworker->index;
1758  leaderworker2->isunique = false;
1759  }
1760 
1761  /*
1762  * Might as well use reliable figure when doling out maintenance_work_mem
1763  * (when requested number of workers were not launched, this will be
1764  * somewhat higher than it is for other workers).
1765  */
1766  sortmem = maintenance_work_mem / btleader->nparticipanttuplesorts;
1767 
1768  /* Perform work common to all participants */
1769  _bt_parallel_scan_and_sort(leaderworker, leaderworker2, btleader->btshared,
1770  btleader->sharedsort, btleader->sharedsort2,
1771  sortmem, true);
1772 
1773 #ifdef BTREE_BUILD_STATS
1775  {
1776  ShowUsage("BTREE BUILD (Leader Partial Spool) STATISTICS");
1777  ResetUsage();
1778  }
1779 #endif /* BTREE_BUILD_STATS */
1780 }
Sharedsort * sharedsort2
Definition: nbtsort.c:195
BTShared * btshared
Definition: nbtsort.c:193
void ShowUsage(const char *title)
Definition: postgres.c:4618
Sharedsort * sharedsort
Definition: nbtsort.c:194
bool isunique
Definition: nbtsort.c:109
BTSpool * spool
Definition: nbtsort.c:212
Relation heap
Definition: nbtsort.c:90
void ResetUsage(void)
Definition: postgres.c:4611
bool isunique
Definition: nbtsort.c:92
Relation index
Definition: nbtsort.c:91
void * palloc0(Size size)
Definition: mcxt.c:980
bool log_btree_build_stats
Definition: guc.c:520
BTLeader * btleader
Definition: nbtsort.c:226
static void _bt_parallel_scan_and_sort(BTSpool *btspool, BTSpool *btspool2, BTShared *btshared, Sharedsort *sharedsort, Sharedsort *sharedsort2, int sortmem, bool progress)
Definition: nbtsort.c:1900
int maintenance_work_mem
Definition: globals.c:122
int nparticipanttuplesorts
Definition: nbtsort.c:181

◆ _bt_leafbuild()

static void _bt_leafbuild ( BTSpool btspool,
BTSpool btspool2 
)
static

Definition at line 539 of file nbtsort.c.

References _bt_allequalimage(), _bt_load(), _bt_mkscankey(), BTScanInsertData::allequalimage, BTREE_METAPAGE, BTWriteState::btws_pages_alloced, BTWriteState::btws_pages_written, BTWriteState::btws_use_wal, BTWriteState::btws_zeropage, BTSpool::heap, BTWriteState::heap, BTSpool::index, BTWriteState::index, BTWriteState::inskey, log_btree_build_stats, pgstat_progress_update_param(), PROGRESS_BTREE_PHASE_LEAF_LOAD, PROGRESS_BTREE_PHASE_PERFORMSORT_1, PROGRESS_BTREE_PHASE_PERFORMSORT_2, PROGRESS_CREATEIDX_SUBPHASE, RelationNeedsWAL, ResetUsage(), ShowUsage(), BTSpool::sortstate, and tuplesort_performsort().

Referenced by btbuild().

540 {
541  BTWriteState wstate;
542 
543 #ifdef BTREE_BUILD_STATS
545  {
546  ShowUsage("BTREE BUILD (Spool) STATISTICS");
547  ResetUsage();
548  }
549 #endif /* BTREE_BUILD_STATS */
550 
554  if (btspool2)
555  {
558  tuplesort_performsort(btspool2->sortstate);
559  }
560 
561  wstate.heap = btspool->heap;
562  wstate.index = btspool->index;
563  wstate.inskey = _bt_mkscankey(wstate.index, NULL);
564  /* _bt_mkscankey() won't set allequalimage without metapage */
565  wstate.inskey->allequalimage = _bt_allequalimage(wstate.index, true);
566  wstate.btws_use_wal = RelationNeedsWAL(wstate.index);
567 
568  /* reserve the metapage */
569  wstate.btws_pages_alloced = BTREE_METAPAGE + 1;
570  wstate.btws_pages_written = 0;
571  wstate.btws_zeropage = NULL; /* until needed */
572 
575  _bt_load(&wstate, btspool, btspool2);
576 }
void tuplesort_performsort(Tuplesortstate *state)
Definition: tuplesort.c:1964
Page btws_zeropage
Definition: nbtsort.c:256
static void _bt_load(BTWriteState *wstate, BTSpool *btspool, BTSpool *btspool2)
Definition: nbtsort.c:1180
BTScanInsert _bt_mkscankey(Relation rel, IndexTuple itup)
Definition: nbtutils.c:90
#define PROGRESS_BTREE_PHASE_PERFORMSORT_1
Definition: nbtree.h:988
void ShowUsage(const char *title)
Definition: postgres.c:4618
BlockNumber btws_pages_alloced
Definition: nbtsort.c:254
void pgstat_progress_update_param(int index, int64 val)
Definition: pgstat.c:3231
bool allequalimage
Definition: nbtree.h:660
Tuplesortstate * sortstate
Definition: nbtsort.c:89
bool btws_use_wal
Definition: nbtsort.c:253
Relation heap
Definition: nbtsort.c:90
void ResetUsage(void)
Definition: postgres.c:4611
#define PROGRESS_BTREE_PHASE_PERFORMSORT_2
Definition: nbtree.h:989
#define BTREE_METAPAGE
Definition: nbtree.h:141
Relation index
Definition: nbtsort.c:91
Relation index
Definition: nbtsort.c:251
BlockNumber btws_pages_written
Definition: nbtsort.c:255
bool log_btree_build_stats
Definition: guc.c:520
BTScanInsert inskey
Definition: nbtsort.c:252
#define RelationNeedsWAL(relation)
Definition: rel.h:562
#define PROGRESS_BTREE_PHASE_LEAF_LOAD
Definition: nbtree.h:990
#define PROGRESS_CREATEIDX_SUBPHASE
Definition: progress.h:83
Relation heap
Definition: nbtsort.c:250
bool _bt_allequalimage(Relation rel, bool debugmessage)
Definition: nbtutils.c:2691

◆ _bt_load()

static void _bt_load ( BTWriteState wstate,
BTSpool btspool,
BTSpool btspool2 
)
static

Definition at line 1180 of file nbtsort.c.

References _bt_buildadd(), _bt_dedup_save_htid(), _bt_dedup_start_pending(), _bt_keep_natts_fast(), _bt_pagestate(), _bt_sort_dedup_finish_pending(), _bt_uppershutdown(), SortSupportData::abbreviate, BTScanInsertData::allequalimage, ApplySortComparator(), Assert, AssertState, BTDedupStateData::base, BTDedupStateData::baseoff, BTDedupStateData::basetupsize, BTGetDeduplicateItems, BTGreaterStrategyNumber, BTLessStrategyNumber, BTMaxItemSize, BTPageState::btps_page, BTWriteState::btws_use_wal, compare(), CopyIndexTuple(), CurrentMemoryContext, BTDedupStateData::deduplicate, BTDedupStateData::htids, i, BTWriteState::index, index_getattr, INDEX_SIZE_MASK, IndexRelationGetNumberOfKeyAttributes, BTWriteState::inskey, InvalidOffsetNumber, ItemPointerCompare(), MAIN_FORKNUM, MAXALIGN_DOWN, BTDedupStateData::maxpostingsize, merge(), BTDedupStateData::nhtids, BTDedupStateData::nintervals, BTDedupStateData::nitems, BTDedupStateData::nmaxitems, palloc(), palloc0(), pfree(), pgstat_progress_update_param(), BTDedupStateData::phystupsize, PrepareSortSupportFromIndexRel(), PROGRESS_CREATEIDX_TUPLES_DONE, RelationData::rd_smgr, RelationGetDescr, RelationOpenSmgr, BTScanInsertData::scankeys, ScanKeyData::sk_attno, SK_BT_DESC, SK_BT_NULLS_FIRST, ScanKeyData::sk_collation, ScanKeyData::sk_flags, smgrimmedsync(), BTSpool::sortstate, SortSupportData::ssup_attno, SortSupportData::ssup_collation, SortSupportData::ssup_cxt, SortSupportData::ssup_nulls_first, IndexTupleData::t_tid, and tuplesort_getindextuple().

Referenced by _bt_leafbuild().

1181 {
1182  BTPageState *state = NULL;
1183  bool merge = (btspool2 != NULL);
1184  IndexTuple itup,
1185  itup2 = NULL;
1186  bool load1;
1187  TupleDesc tupdes = RelationGetDescr(wstate->index);
1188  int i,
1190  SortSupport sortKeys;
1191  int64 tuples_done = 0;
1192  bool deduplicate;
1193 
1194  deduplicate = wstate->inskey->allequalimage &&
1195  BTGetDeduplicateItems(wstate->index);
1196 
1197  if (merge)
1198  {
1199  /*
1200  * Another BTSpool for dead tuples exists. Now we have to merge
1201  * btspool and btspool2.
1202  */
1203 
1204  /* the preparation of merge */
1205  itup = tuplesort_getindextuple(btspool->sortstate, true);
1206  itup2 = tuplesort_getindextuple(btspool2->sortstate, true);
1207 
1208  /* Prepare SortSupport data for each column */
1209  sortKeys = (SortSupport) palloc0(keysz * sizeof(SortSupportData));
1210 
1211  for (i = 0; i < keysz; i++)
1212  {
1213  SortSupport sortKey = sortKeys + i;
1214  ScanKey scanKey = wstate->inskey->scankeys + i;
1215  int16 strategy;
1216 
1217  sortKey->ssup_cxt = CurrentMemoryContext;
1218  sortKey->ssup_collation = scanKey->sk_collation;
1219  sortKey->ssup_nulls_first =
1220  (scanKey->sk_flags & SK_BT_NULLS_FIRST) != 0;
1221  sortKey->ssup_attno = scanKey->sk_attno;
1222  /* Abbreviation is not supported here */
1223  sortKey->abbreviate = false;
1224 
1225  AssertState(sortKey->ssup_attno != 0);
1226 
1227  strategy = (scanKey->sk_flags & SK_BT_DESC) != 0 ?
1229 
1230  PrepareSortSupportFromIndexRel(wstate->index, strategy, sortKey);
1231  }
1232 
1233  for (;;)
1234  {
1235  load1 = true; /* load BTSpool next ? */
1236  if (itup2 == NULL)
1237  {
1238  if (itup == NULL)
1239  break;
1240  }
1241  else if (itup != NULL)
1242  {
1243  int32 compare = 0;
1244 
1245  for (i = 1; i <= keysz; i++)
1246  {
1247  SortSupport entry;
1248  Datum attrDatum1,
1249  attrDatum2;
1250  bool isNull1,
1251  isNull2;
1252 
1253  entry = sortKeys + i - 1;
1254  attrDatum1 = index_getattr(itup, i, tupdes, &isNull1);
1255  attrDatum2 = index_getattr(itup2, i, tupdes, &isNull2);
1256 
1257  compare = ApplySortComparator(attrDatum1, isNull1,
1258  attrDatum2, isNull2,
1259  entry);
1260  if (compare > 0)
1261  {
1262  load1 = false;
1263  break;
1264  }
1265  else if (compare < 0)
1266  break;
1267  }
1268 
1269  /*
1270  * If key values are equal, we sort on ItemPointer. This is
1271  * required for btree indexes, since heap TID is treated as an
1272  * implicit last key attribute in order to ensure that all
1273  * keys in the index are physically unique.
1274  */
1275  if (compare == 0)
1276  {
1277  compare = ItemPointerCompare(&itup->t_tid, &itup2->t_tid);
1278  Assert(compare != 0);
1279  if (compare > 0)
1280  load1 = false;
1281  }
1282  }
1283  else
1284  load1 = false;
1285 
1286  /* When we see first tuple, create first index page */
1287  if (state == NULL)
1288  state = _bt_pagestate(wstate, 0);
1289 
1290  if (load1)
1291  {
1292  _bt_buildadd(wstate, state, itup, 0);
1293  itup = tuplesort_getindextuple(btspool->sortstate, true);
1294  }
1295  else
1296  {
1297  _bt_buildadd(wstate, state, itup2, 0);
1298  itup2 = tuplesort_getindextuple(btspool2->sortstate, true);
1299  }
1300 
1301  /* Report progress */
1303  ++tuples_done);
1304  }
1305  pfree(sortKeys);
1306  }
1307  else if (deduplicate)
1308  {
1309  /* merge is unnecessary, deduplicate into posting lists */
1310  BTDedupState dstate;
1311 
1312  dstate = (BTDedupState) palloc(sizeof(BTDedupStateData));
1313  dstate->deduplicate = true; /* unused */
1314  dstate->nmaxitems = 0; /* unused */
1315  dstate->maxpostingsize = 0; /* set later */
1316  /* Metadata about base tuple of current pending posting list */
1317  dstate->base = NULL;
1318  dstate->baseoff = InvalidOffsetNumber; /* unused */
1319  dstate->basetupsize = 0;
1320  /* Metadata about current pending posting list TIDs */
1321  dstate->htids = NULL;
1322  dstate->nhtids = 0;
1323  dstate->nitems = 0;
1324  dstate->phystupsize = 0; /* unused */
1325  dstate->nintervals = 0; /* unused */
1326 
1327  while ((itup = tuplesort_getindextuple(btspool->sortstate,
1328  true)) != NULL)
1329  {
1330  /* When we see first tuple, create first index page */
1331  if (state == NULL)
1332  {
1333  state = _bt_pagestate(wstate, 0);
1334 
1335  /*
1336  * Limit size of posting list tuples to 1/10 space we want to
1337  * leave behind on the page, plus space for final item's line
1338  * pointer. This is equal to the space that we'd like to
1339  * leave behind on each leaf page when fillfactor is 90,
1340  * allowing us to get close to fillfactor% space utilization
1341  * when there happen to be a great many duplicates. (This
1342  * makes higher leaf fillfactor settings ineffective when
1343  * building indexes that have many duplicates, but packing
1344  * leaf pages full with few very large tuples doesn't seem
1345  * like a useful goal.)
1346  */
1347  dstate->maxpostingsize = MAXALIGN_DOWN((BLCKSZ * 10 / 100)) -
1348  sizeof(ItemIdData);
1349  Assert(dstate->maxpostingsize <= BTMaxItemSize(state->btps_page) &&
1350  dstate->maxpostingsize <= INDEX_SIZE_MASK);
1351  dstate->htids = palloc(dstate->maxpostingsize);
1352 
1353  /* start new pending posting list with itup copy */
1356  }
1357  else if (_bt_keep_natts_fast(wstate->index, dstate->base,
1358  itup) > keysz &&
1359  _bt_dedup_save_htid(dstate, itup))
1360  {
1361  /*
1362  * Tuple is equal to base tuple of pending posting list. Heap
1363  * TID from itup has been saved in state.
1364  */
1365  }
1366  else
1367  {
1368  /*
1369  * Tuple is not equal to pending posting list tuple, or
1370  * _bt_dedup_save_htid() opted to not merge current item into
1371  * pending posting list.
1372  */
1373  _bt_sort_dedup_finish_pending(wstate, state, dstate);
1374  pfree(dstate->base);
1375 
1376  /* start new pending posting list with itup copy */
1379  }
1380 
1381  /* Report progress */
1383  ++tuples_done);
1384  }
1385 
1386  if (state)
1387  {
1388  /*
1389  * Handle the last item (there must be a last item when the
1390  * tuplesort returned one or more tuples)
1391  */
1392  _bt_sort_dedup_finish_pending(wstate, state, dstate);
1393  pfree(dstate->base);
1394  pfree(dstate->htids);
1395  }
1396 
1397  pfree(dstate);
1398  }
1399  else
1400  {
1401  /* merging and deduplication are both unnecessary */
1402  while ((itup = tuplesort_getindextuple(btspool->sortstate,
1403  true)) != NULL)
1404  {
1405  /* When we see first tuple, create first index page */
1406  if (state == NULL)
1407  state = _bt_pagestate(wstate, 0);
1408 
1409  _bt_buildadd(wstate, state, itup, 0);
1410 
1411  /* Report progress */
1413  ++tuples_done);
1414  }
1415  }
1416 
1417  /* Close down final pages and write the metapage */
1418  _bt_uppershutdown(wstate, state);
1419 
1420  /*
1421  * When we WAL-logged index pages, we must nonetheless fsync index files.
1422  * Since we're building outside shared buffers, a CHECKPOINT occurring
1423  * during the build has no way to flush the previously written data to
1424  * disk (indeed it won't know the index even exists). A crash later on
1425  * would replay WAL from the checkpoint, therefore it wouldn't replay our
1426  * earlier WAL entries. If we do not fsync those pages here, they might
1427  * still not be on disk when the crash occurs.
1428  */
1429  if (wstate->btws_use_wal)
1430  {
1431  RelationOpenSmgr(wstate->index);
1433  }
1434 }
struct SortSupportData * SortSupport
Definition: sortsupport.h:58
IndexTuple tuplesort_getindextuple(Tuplesortstate *state, bool forward)
Definition: tuplesort.c:2389
int32 ItemPointerCompare(ItemPointer arg1, ItemPointer arg2)
Definition: itemptr.c:52
signed short int16
Definition: c.h:354
bool ssup_nulls_first
Definition: sortsupport.h:75
IndexTuple base
Definition: nbtree.h:746
#define BTGreaterStrategyNumber
Definition: stratnum.h:33
#define AssertState(condition)
Definition: c.h:741
OffsetNumber baseoff
Definition: nbtree.h:747
#define RelationGetDescr(relation)
Definition: rel.h:482
#define BTGetDeduplicateItems(relation)
Definition: nbtree.h:976
static void _bt_sort_dedup_finish_pending(BTWriteState *wstate, BTPageState *state, BTDedupState dstate)
Definition: nbtsort.c:1074
struct SMgrRelationData * rd_smgr
Definition: rel.h:57
void pgstat_progress_update_param(int index, int64 val)
Definition: pgstat.c:3231
ItemPointerData t_tid
Definition: itup.h:37
#define INDEX_SIZE_MASK
Definition: itup.h:65
bool allequalimage
Definition: nbtree.h:660
void _bt_dedup_start_pending(BTDedupState state, IndexTuple base, OffsetNumber baseoff)
Definition: nbtdedup.c:324
Tuplesortstate * sortstate
Definition: nbtsort.c:89
bool btws_use_wal
Definition: nbtsort.c:253
static pairingheap_node * merge(pairingheap *heap, pairingheap_node *a, pairingheap_node *b)
Definition: pairingheap.c:79
signed int int32
Definition: c.h:355
#define RelationOpenSmgr(relation)
Definition: rel.h:513
ItemPointer htids
Definition: nbtree.h:751
Page btps_page
Definition: nbtsort.c:235
void pfree(void *pointer)
Definition: mcxt.c:1056
Size phystupsize
Definition: nbtree.h:754
static int compare(const void *arg1, const void *arg2)
Definition: geqo_pool.c:145
MemoryContext ssup_cxt
Definition: sortsupport.h:66
IndexTuple CopyIndexTuple(IndexTuple source)
Definition: indextuple.c:510
bool _bt_dedup_save_htid(BTDedupState state, IndexTuple itup)
Definition: nbtdedup.c:375
struct ItemIdData ItemIdData
MemoryContext CurrentMemoryContext
Definition: mcxt.c:38
#define IndexRelationGetNumberOfKeyAttributes(relation)
Definition: rel.h:475
void PrepareSortSupportFromIndexRel(Relation indexRel, int16 strategy, SortSupport ssup)
Definition: sortsupport.c:161
Relation index
Definition: nbtsort.c:251
#define SK_BT_NULLS_FIRST
Definition: nbtree.h:957
void * palloc0(Size size)
Definition: mcxt.c:980
uintptr_t Datum
Definition: postgres.h:367
static BTPageState * _bt_pagestate(BTWriteState *wstate, uint32 level)
Definition: nbtsort.c:696
AttrNumber ssup_attno
Definition: sortsupport.h:81
BTScanInsert inskey
Definition: nbtsort.c:252
#define InvalidOffsetNumber
Definition: off.h:26
static void _bt_buildadd(BTWriteState *wstate, BTPageState *state, IndexTuple itup, Size truncextra)
Definition: nbtsort.c:833
int sk_flags
Definition: skey.h:66
#define Assert(condition)
Definition: c.h:738
#define SK_BT_DESC
Definition: nbtree.h:956
Definition: regguts.h:298
#define index_getattr(tup, attnum, tupleDesc, isnull)
Definition: itup.h:100
Size basetupsize
Definition: nbtree.h:748
ScanKeyData scankeys[INDEX_MAX_KEYS]
Definition: nbtree.h:666
Size maxpostingsize
Definition: nbtree.h:743
#define BTMaxItemSize(page)
Definition: nbtree.h:157
int _bt_keep_natts_fast(Relation rel, IndexTuple lastleft, IndexTuple firstright)
Definition: nbtutils.c:2418
void * palloc(Size size)
Definition: mcxt.c:949
#define PROGRESS_CREATEIDX_TUPLES_DONE
Definition: progress.h:85
bool deduplicate
Definition: nbtree.h:741
Oid sk_collation
Definition: skey.h:70
int i
static void _bt_uppershutdown(BTWriteState *wstate, BTPageState *state)
Definition: nbtsort.c:1108
BTDedupStateData * BTDedupState
Definition: nbtree.h:766
#define BTLessStrategyNumber
Definition: stratnum.h:29
static int ApplySortComparator(Datum datum1, bool isNull1, Datum datum2, bool isNull2, SortSupport ssup)
Definition: sortsupport.h:200
void smgrimmedsync(SMgrRelation reln, ForkNumber forknum)
Definition: smgr.c:620
AttrNumber sk_attno
Definition: skey.h:67
#define MAXALIGN_DOWN(LEN)
Definition: c.h:703

◆ _bt_pagestate()

static BTPageState * _bt_pagestate ( BTWriteState wstate,
uint32  level 
)
static

Definition at line 696 of file nbtsort.c.

References _bt_blnewpage(), BTGetTargetPageFreeSpace, BTPageState::btps_blkno, BTPageState::btps_full, BTPageState::btps_lastextra, BTPageState::btps_lastoff, BTPageState::btps_level, BTPageState::btps_lowkey, BTPageState::btps_next, BTPageState::btps_page, BTREE_NONLEAF_FILLFACTOR, BTWriteState::btws_pages_alloced, BTWriteState::index, P_HIKEY, and palloc0().

Referenced by _bt_buildadd(), and _bt_load().

697 {
699 
700  /* create initial page for level */
701  state->btps_page = _bt_blnewpage(level);
702 
703  /* and assign it a page position */
704  state->btps_blkno = wstate->btws_pages_alloced++;
705 
706  state->btps_lowkey = NULL;
707  /* initialize lastoff so first item goes into P_FIRSTKEY */
708  state->btps_lastoff = P_HIKEY;
709  state->btps_lastextra = 0;
710  state->btps_level = level;
711  /* set "full" threshold based on level. See notes at head of file. */
712  if (level > 0)
713  state->btps_full = (BLCKSZ * (100 - BTREE_NONLEAF_FILLFACTOR) / 100);
714  else
715  state->btps_full = BTGetTargetPageFreeSpace(wstate->index);
716 
717  /* no parent level, yet */
718  state->btps_next = NULL;
719 
720  return state;
721 }
#define BTGetTargetPageFreeSpace(relation)
Definition: nbtree.h:974
BlockNumber btws_pages_alloced
Definition: nbtsort.c:254
BlockNumber btps_blkno
Definition: nbtsort.c:236
Page btps_page
Definition: nbtsort.c:235
#define BTREE_NONLEAF_FILLFACTOR
Definition: nbtree.h:195
Size btps_full
Definition: nbtsort.c:241
OffsetNumber btps_lastoff
Definition: nbtsort.c:238
Size btps_lastextra
Definition: nbtsort.c:239
Relation index
Definition: nbtsort.c:251
void * palloc0(Size size)
Definition: mcxt.c:980
uint32 btps_level
Definition: nbtsort.c:240
struct BTPageState * btps_next
Definition: nbtsort.c:242
IndexTuple btps_lowkey
Definition: nbtsort.c:237
Definition: regguts.h:298
#define P_HIKEY
Definition: nbtree.h:242
static Page _bt_blnewpage(uint32 level)
Definition: nbtsort.c:611

◆ _bt_parallel_build_main()

void _bt_parallel_build_main ( dsm_segment seg,
shm_toc toc 
)

Definition at line 1786 of file nbtsort.c.

References _bt_parallel_scan_and_sort(), AccessExclusiveLock, debug_query_string, BTSpool::heap, BTShared::heaprelid, BTSpool::index, index_close(), index_open(), BTShared::indexrelid, InstrEndParallelQuery(), InstrStartParallelQuery(), BTShared::isconcurrent, BTSpool::isunique, BTShared::isunique, log_btree_build_stats, maintenance_work_mem, palloc0(), PARALLEL_KEY_BTREE_SHARED, PARALLEL_KEY_BUFFER_USAGE, PARALLEL_KEY_QUERY_TEXT, PARALLEL_KEY_TUPLESORT, PARALLEL_KEY_TUPLESORT_SPOOL2, PARALLEL_KEY_WAL_USAGE, ParallelWorkerNumber, pgstat_report_activity(), ResetUsage(), RowExclusiveLock, BTShared::scantuplesortstates, ShareLock, ShareUpdateExclusiveLock, shm_toc_lookup(), ShowUsage(), STATE_RUNNING, table_close(), table_open(), and tuplesort_attach_shared().

1787 {
1788  char *sharedquery;
1789  BTSpool *btspool;
1790  BTSpool *btspool2;
1791  BTShared *btshared;
1792  Sharedsort *sharedsort;
1793  Sharedsort *sharedsort2;
1794  Relation heapRel;
1795  Relation indexRel;
1796  LOCKMODE heapLockmode;
1797  LOCKMODE indexLockmode;
1798  WalUsage *walusage;
1799  BufferUsage *bufferusage;
1800  int sortmem;
1801 
1802 #ifdef BTREE_BUILD_STATS
1804  ResetUsage();
1805 #endif /* BTREE_BUILD_STATS */
1806 
1807  /* Set debug_query_string for individual workers first */
1808  sharedquery = shm_toc_lookup(toc, PARALLEL_KEY_QUERY_TEXT, false);
1809  debug_query_string = sharedquery;
1810 
1811  /* Report the query string from leader */
1813 
1814  /* Look up nbtree shared state */
1815  btshared = shm_toc_lookup(toc, PARALLEL_KEY_BTREE_SHARED, false);
1816 
1817  /* Open relations using lock modes known to be obtained by index.c */
1818  if (!btshared->isconcurrent)
1819  {
1820  heapLockmode = ShareLock;
1821  indexLockmode = AccessExclusiveLock;
1822  }
1823  else
1824  {
1825  heapLockmode = ShareUpdateExclusiveLock;
1826  indexLockmode = RowExclusiveLock;
1827  }
1828 
1829  /* Open relations within worker */
1830  heapRel = table_open(btshared->heaprelid, heapLockmode);
1831  indexRel = index_open(btshared->indexrelid, indexLockmode);
1832 
1833  /* Initialize worker's own spool */
1834  btspool = (BTSpool *) palloc0(sizeof(BTSpool));
1835  btspool->heap = heapRel;
1836  btspool->index = indexRel;
1837  btspool->isunique = btshared->isunique;
1838 
1839  /* Look up shared state private to tuplesort.c */
1840  sharedsort = shm_toc_lookup(toc, PARALLEL_KEY_TUPLESORT, false);
1841  tuplesort_attach_shared(sharedsort, seg);
1842  if (!btshared->isunique)
1843  {
1844  btspool2 = NULL;
1845  sharedsort2 = NULL;
1846  }
1847  else
1848  {
1849  /* Allocate memory for worker's own private secondary spool */
1850  btspool2 = (BTSpool *) palloc0(sizeof(BTSpool));
1851 
1852  /* Initialize worker's own secondary spool */
1853  btspool2->heap = btspool->heap;
1854  btspool2->index = btspool->index;
1855  btspool2->isunique = false;
1856  /* Look up shared state private to tuplesort.c */
1857  sharedsort2 = shm_toc_lookup(toc, PARALLEL_KEY_TUPLESORT_SPOOL2, false);
1858  tuplesort_attach_shared(sharedsort2, seg);
1859  }
1860 
1861  /* Prepare to track buffer usage during parallel execution */
1863 
1864  /* Perform sorting of spool, and possibly a spool2 */
1865  sortmem = maintenance_work_mem / btshared->scantuplesortstates;
1866  _bt_parallel_scan_and_sort(btspool, btspool2, btshared, sharedsort,
1867  sharedsort2, sortmem, false);
1868 
1869  /* Report WAL/buffer usage during parallel execution */
1870  bufferusage = shm_toc_lookup(toc, PARALLEL_KEY_BUFFER_USAGE, false);
1871  walusage = shm_toc_lookup(toc, PARALLEL_KEY_WAL_USAGE, false);
1873  &walusage[ParallelWorkerNumber]);
1874 
1875 #ifdef BTREE_BUILD_STATS
1877  {
1878  ShowUsage("BTREE BUILD (Worker Partial Spool) STATISTICS");
1879  ResetUsage();
1880  }
1881 #endif /* BTREE_BUILD_STATS */
1882 
1883  index_close(indexRel, indexLockmode);
1884  table_close(heapRel, heapLockmode);
1885 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
int scantuplesortstates
Definition: nbtsort.c:111
#define PARALLEL_KEY_TUPLESORT
Definition: nbtsort.c:70
int LOCKMODE
Definition: lockdefs.h:26
Oid indexrelid
Definition: nbtsort.c:108
void pgstat_report_activity(BackendState state, const char *cmd_str)
Definition: pgstat.c:3132
void ShowUsage(const char *title)
Definition: postgres.c:4618
bool isunique
Definition: nbtsort.c:109
bool isconcurrent
Definition: nbtsort.c:110
void InstrEndParallelQuery(BufferUsage *bufusage, WalUsage *walusage)
Definition: instrument.c:189
Relation heap
Definition: nbtsort.c:90
void ResetUsage(void)
Definition: postgres.c:4611
#define PARALLEL_KEY_BUFFER_USAGE
Definition: nbtsort.c:74
bool isunique
Definition: nbtsort.c:92
Oid heaprelid
Definition: nbtsort.c:107
#define RowExclusiveLock
Definition: lockdefs.h:38
#define PARALLEL_KEY_QUERY_TEXT
Definition: nbtsort.c:72
int ParallelWorkerNumber
Definition: parallel.c:112
#define PARALLEL_KEY_TUPLESORT_SPOOL2
Definition: nbtsort.c:71
Relation index
Definition: nbtsort.c:91
const char * debug_query_string
Definition: postgres.c:88
void InstrStartParallelQuery(void)
Definition: instrument.c:181
void * palloc0(Size size)
Definition: mcxt.c:980
bool log_btree_build_stats
Definition: guc.c:520
static void _bt_parallel_scan_and_sort(BTSpool *btspool, BTSpool *btspool2, BTShared *btshared, Sharedsort *sharedsort, Sharedsort *sharedsort2, int sortmem, bool progress)
Definition: nbtsort.c:1900
int maintenance_work_mem
Definition: globals.c:122
void tuplesort_attach_shared(Sharedsort *shared, dsm_segment *seg)
Definition: tuplesort.c:4525
#define ShareUpdateExclusiveLock
Definition: lockdefs.h:39
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:158
#define AccessExclusiveLock
Definition: lockdefs.h:45
#define PARALLEL_KEY_WAL_USAGE
Definition: nbtsort.c:73
#define ShareLock
Definition: lockdefs.h:41
#define PARALLEL_KEY_BTREE_SHARED
Definition: nbtsort.c:69
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
void * shm_toc_lookup(shm_toc *toc, uint64 key, bool noError)
Definition: shm_toc.c:232
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:132

◆ _bt_parallel_estimate_shared()

static Size _bt_parallel_estimate_shared ( Relation  heap,
Snapshot  snapshot 
)
static

Definition at line 1680 of file nbtsort.c.

References add_size(), BUFFERALIGN, and table_parallelscan_estimate().

Referenced by _bt_begin_parallel().

1681 {
1682  /* c.f. shm_toc_allocate as to why BUFFERALIGN is used */
1683  return add_size(BUFFERALIGN(sizeof(BTShared)),
1684  table_parallelscan_estimate(heap, snapshot));
1685 }
Size add_size(Size s1, Size s2)
Definition: shmem.c:498
Size table_parallelscan_estimate(Relation rel, Snapshot snapshot)
Definition: tableam.c:126
#define BUFFERALIGN(LEN)
Definition: c.h:693

◆ _bt_parallel_heapscan()

static double _bt_parallel_heapscan ( BTBuildState buildstate,
bool brokenhotchain 
)
static

Definition at line 1700 of file nbtsort.c.

References BTShared::brokenhotchain, BTBuildState::btleader, BTLeader::btshared, ConditionVariableCancelSleep(), ConditionVariableSleep(), BTShared::havedead, BTBuildState::havedead, BTShared::indtuples, BTBuildState::indtuples, BTShared::mutex, BTShared::nparticipantsdone, BTLeader::nparticipanttuplesorts, BTShared::reltuples, SpinLockAcquire, SpinLockRelease, WAIT_EVENT_PARALLEL_CREATE_INDEX_SCAN, and BTShared::workersdonecv.

Referenced by _bt_spools_heapscan().

1701 {
1702  BTShared *btshared = buildstate->btleader->btshared;
1703  int nparticipanttuplesorts;
1704  double reltuples;
1705 
1706  nparticipanttuplesorts = buildstate->btleader->nparticipanttuplesorts;
1707  for (;;)
1708  {
1709  SpinLockAcquire(&btshared->mutex);
1710  if (btshared->nparticipantsdone == nparticipanttuplesorts)
1711  {
1712  buildstate->havedead = btshared->havedead;
1713  buildstate->indtuples = btshared->indtuples;
1714  *brokenhotchain = btshared->brokenhotchain;
1715  reltuples = btshared->reltuples;
1716  SpinLockRelease(&btshared->mutex);
1717  break;
1718  }
1719  SpinLockRelease(&btshared->mutex);
1720 
1723  }
1724 
1726 
1727  return reltuples;
1728 }
BTShared * btshared
Definition: nbtsort.c:193
int nparticipantsdone
Definition: nbtsort.c:145
bool havedead
Definition: nbtsort.c:210
#define SpinLockAcquire(lock)
Definition: spin.h:62
void ConditionVariableCancelSleep(void)
double indtuples
Definition: nbtsort.c:219
bool brokenhotchain
Definition: nbtsort.c:149
#define SpinLockRelease(lock)
Definition: spin.h:64
BTLeader * btleader
Definition: nbtsort.c:226
double reltuples
Definition: nbtsort.c:146
double indtuples
Definition: nbtsort.c:148
slock_t mutex
Definition: nbtsort.c:127
bool havedead
Definition: nbtsort.c:147
void ConditionVariableSleep(ConditionVariable *cv, uint32 wait_event_info)
int nparticipanttuplesorts
Definition: nbtsort.c:181
ConditionVariable workersdonecv
Definition: nbtsort.c:119

◆ _bt_parallel_scan_and_sort()

static void _bt_parallel_scan_and_sort ( BTSpool btspool,
BTSpool btspool2,
BTShared btshared,
Sharedsort sharedsort,
Sharedsort sharedsort2,
int  sortmem,
bool  progress 
)
static

Definition at line 1900 of file nbtsort.c.

References _bt_build_callback(), BTShared::brokenhotchain, BTBuildState::btleader, BuildIndexInfo(), ConditionVariableSignal(), BTShared::havedead, BTBuildState::havedead, BTSpool::heap, BTBuildState::heap, IndexInfo::ii_BrokenHotChain, IndexInfo::ii_Concurrent, BTSpool::index, BTShared::indtuples, BTBuildState::indtuples, BTShared::isconcurrent, BTSpool::isunique, BTShared::isunique, BTBuildState::isunique, SortCoordinateData::isWorker, Min, BTShared::mutex, SortCoordinateData::nParticipants, BTShared::nparticipantsdone, palloc0(), ParallelTableScanFromBTShared, BTShared::reltuples, SortCoordinateData::sharedsort, BTSpool::sortstate, SpinLockAcquire, SpinLockRelease, BTBuildState::spool, BTBuildState::spool2, table_beginscan_parallel(), table_index_build_scan(), tuplesort_begin_index_btree(), tuplesort_end(), tuplesort_performsort(), work_mem, and BTShared::workersdonecv.

Referenced by _bt_leader_participate_as_worker(), and _bt_parallel_build_main().

1903 {
1904  SortCoordinate coordinate;
1905  BTBuildState buildstate;
1906  TableScanDesc scan;
1907  double reltuples;
1908  IndexInfo *indexInfo;
1909 
1910  /* Initialize local tuplesort coordination state */
1911  coordinate = palloc0(sizeof(SortCoordinateData));
1912  coordinate->isWorker = true;
1913  coordinate->nParticipants = -1;
1914  coordinate->sharedsort = sharedsort;
1915 
1916  /* Begin "partial" tuplesort */
1917  btspool->sortstate = tuplesort_begin_index_btree(btspool->heap,
1918  btspool->index,
1919  btspool->isunique,
1920  sortmem, coordinate,
1921  false);
1922 
1923  /*
1924  * Just as with serial case, there may be a second spool. If so, a
1925  * second, dedicated spool2 partial tuplesort is required.
1926  */
1927  if (btspool2)
1928  {
1929  SortCoordinate coordinate2;
1930 
1931  /*
1932  * We expect that the second one (for dead tuples) won't get very
1933  * full, so we give it only work_mem (unless sortmem is less for
1934  * worker). Worker processes are generally permitted to allocate
1935  * work_mem independently.
1936  */
1937  coordinate2 = palloc0(sizeof(SortCoordinateData));
1938  coordinate2->isWorker = true;
1939  coordinate2->nParticipants = -1;
1940  coordinate2->sharedsort = sharedsort2;
1941  btspool2->sortstate =
1942  tuplesort_begin_index_btree(btspool->heap, btspool->index, false,
1943  Min(sortmem, work_mem), coordinate2,
1944  false);
1945  }
1946 
1947  /* Fill in buildstate for _bt_build_callback() */
1948  buildstate.isunique = btshared->isunique;
1949  buildstate.havedead = false;
1950  buildstate.heap = btspool->heap;
1951  buildstate.spool = btspool;
1952  buildstate.spool2 = btspool2;
1953  buildstate.indtuples = 0;
1954  buildstate.btleader = NULL;
1955 
1956  /* Join parallel scan */
1957  indexInfo = BuildIndexInfo(btspool->index);
1958  indexInfo->ii_Concurrent = btshared->isconcurrent;
1959  scan = table_beginscan_parallel(btspool->heap,
1960  ParallelTableScanFromBTShared(btshared));
1961  reltuples = table_index_build_scan(btspool->heap, btspool->index, indexInfo,
1963  (void *) &buildstate, scan);
1964 
1965  /*
1966  * Execute this worker's part of the sort.
1967  *
1968  * Unlike leader and serial cases, we cannot avoid calling
1969  * tuplesort_performsort() for spool2 if it ends up containing no dead
1970  * tuples (this is disallowed for workers by tuplesort).
1971  */
1972  tuplesort_performsort(btspool->sortstate);
1973  if (btspool2)
1974  tuplesort_performsort(btspool2->sortstate);
1975 
1976  /*
1977  * Done. Record ambuild statistics, and whether we encountered a broken
1978  * HOT chain.
1979  */
1980  SpinLockAcquire(&btshared->mutex);
1981  btshared->nparticipantsdone++;
1982  btshared->reltuples += reltuples;
1983  if (buildstate.havedead)
1984  btshared->havedead = true;
1985  btshared->indtuples += buildstate.indtuples;
1986  if (indexInfo->ii_BrokenHotChain)
1987  btshared->brokenhotchain = true;
1988  SpinLockRelease(&btshared->mutex);
1989 
1990  /* Notify leader */
1992 
1993  /* We can end tuplesorts immediately */
1994  tuplesort_end(btspool->sortstate);
1995  if (btspool2)
1996  tuplesort_end(btspool2->sortstate);
1997 }
void tuplesort_performsort(Tuplesortstate *state)
Definition: tuplesort.c:1964
Relation heap
Definition: nbtsort.c:211
int nparticipantsdone
Definition: nbtsort.c:145
#define Min(x, y)
Definition: c.h:920
bool havedead
Definition: nbtsort.c:210
Sharedsort * sharedsort
Definition: tuplesort.h:55
bool isunique
Definition: nbtsort.c:109
#define ParallelTableScanFromBTShared(shared)
Definition: nbtsort.c:164
bool isconcurrent
Definition: nbtsort.c:110
Tuplesortstate * sortstate
Definition: nbtsort.c:89
IndexInfo * BuildIndexInfo(Relation index)
Definition: index.c:2298
BTSpool * spool
Definition: nbtsort.c:212
Relation heap
Definition: nbtsort.c:90
#define SpinLockAcquire(lock)
Definition: spin.h:62
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:1526
bool isunique
Definition: nbtsort.c:92
void ConditionVariableSignal(ConditionVariable *cv)
BTSpool * spool2
Definition: nbtsort.c:218
double indtuples
Definition: nbtsort.c:219
bool isunique
Definition: nbtsort.c:209
bool ii_BrokenHotChain
Definition: execnodes.h:175
bool brokenhotchain
Definition: nbtsort.c:149
Relation index
Definition: nbtsort.c:91
TableScanDesc table_beginscan_parallel(Relation relation, ParallelTableScanDesc parallel_scan)
Definition: tableam.c:161
int progress
Definition: pgbench.c:234
#define SpinLockRelease(lock)
Definition: spin.h:64
void * palloc0(Size size)
Definition: mcxt.c:980
static void _bt_build_callback(Relation index, ItemPointer tid, Datum *values, bool *isnull, bool tupleIsAlive, void *state)
Definition: nbtsort.c:582
BTLeader * btleader
Definition: nbtsort.c:226
int work_mem
Definition: globals.c:121
double reltuples
Definition: nbtsort.c:146
double indtuples
Definition: nbtsort.c:148
slock_t mutex
Definition: nbtsort.c:127
bool havedead
Definition: nbtsort.c:147
bool ii_Concurrent
Definition: execnodes.h:174
Tuplesortstate * tuplesort_begin_index_btree(Relation heapRel, Relation indexRel, bool enforceUnique, int workMem, SortCoordinate coordinate, bool randomAccess)
Definition: tuplesort.c:1047
ConditionVariable workersdonecv
Definition: nbtsort.c:119
void tuplesort_end(Tuplesortstate *state)
Definition: tuplesort.c:1388

◆ _bt_slideleft()

static void _bt_slideleft ( Page  page)
static

Definition at line 730 of file nbtsort.c.

References OffsetNumberNext, P_FIRSTKEY, P_HIKEY, PageGetItemId, PageGetMaxOffsetNumber, and PageIsEmpty.

Referenced by _bt_uppershutdown().

731 {
732  OffsetNumber off;
733  OffsetNumber maxoff;
734  ItemId previi;
735  ItemId thisii;
736 
737  if (!PageIsEmpty(page))
738  {
739  maxoff = PageGetMaxOffsetNumber(page);
740  previi = PageGetItemId(page, P_HIKEY);
741  for (off = P_FIRSTKEY; off <= maxoff; off = OffsetNumberNext(off))
742  {
743  thisii = PageGetItemId(page, off);
744  *previi = *thisii;
745  previi = thisii;
746  }
747  ((PageHeader) page)->pd_lower -= sizeof(ItemIdData);
748  }
749 }
#define PageIsEmpty(page)
Definition: bufpage.h:222
#define PageGetMaxOffsetNumber(page)
Definition: bufpage.h:357
uint16 OffsetNumber
Definition: off.h:24
#define P_FIRSTKEY
Definition: nbtree.h:243
struct ItemIdData ItemIdData
#define PageGetItemId(page, offsetNumber)
Definition: bufpage.h:235
PageHeaderData * PageHeader
Definition: bufpage.h:166
#define OffsetNumberNext(offsetNumber)
Definition: off.h:52
#define P_HIKEY
Definition: nbtree.h:242

◆ _bt_sort_dedup_finish_pending()

static void _bt_sort_dedup_finish_pending ( BTWriteState wstate,
BTPageState state,
BTDedupState  dstate 
)
static

Definition at line 1074 of file nbtsort.c.

References _bt_buildadd(), _bt_form_posting(), Assert, BTDedupStateData::base, BTreeTupleGetPostingOffset(), BTDedupStateData::htids, IndexTupleSize, BTDedupStateData::nhtids, BTDedupStateData::nitems, BTDedupStateData::nmaxitems, pfree(), and BTDedupStateData::phystupsize.

Referenced by _bt_load().

1076 {
1077  Assert(dstate->nitems > 0);
1078 
1079  if (dstate->nitems == 1)
1080  _bt_buildadd(wstate, state, dstate->base, 0);
1081  else
1082  {
1083  IndexTuple postingtuple;
1084  Size truncextra;
1085 
1086  /* form a tuple with a posting list */
1087  postingtuple = _bt_form_posting(dstate->base,
1088  dstate->htids,
1089  dstate->nhtids);
1090  /* Calculate posting list overhead */
1091  truncextra = IndexTupleSize(postingtuple) -
1092  BTreeTupleGetPostingOffset(postingtuple);
1093 
1094  _bt_buildadd(wstate, state, postingtuple, truncextra);
1095  pfree(postingtuple);
1096  }
1097 
1098  dstate->nmaxitems = 0;
1099  dstate->nhtids = 0;
1100  dstate->nitems = 0;
1101  dstate->phystupsize = 0;
1102 }
IndexTuple base
Definition: nbtree.h:746
IndexTuple _bt_form_posting(IndexTuple base, ItemPointer htids, int nhtids)
Definition: nbtdedup.c:616
ItemPointer htids
Definition: nbtree.h:751
void pfree(void *pointer)
Definition: mcxt.c:1056
Size phystupsize
Definition: nbtree.h:754
static void _bt_buildadd(BTWriteState *wstate, BTPageState *state, IndexTuple itup, Size truncextra)
Definition: nbtsort.c:833
static uint32 BTreeTupleGetPostingOffset(IndexTuple posting)
Definition: nbtree.h:397
#define Assert(condition)
Definition: c.h:738
size_t Size
Definition: c.h:466
#define IndexTupleSize(itup)
Definition: itup.h:71

◆ _bt_sortaddtup()

static void _bt_sortaddtup ( Page  page,
Size  itemsize,
IndexTuple  itup,
OffsetNumber  itup_off,
bool  newfirstdataitem 
)
static

Definition at line 763 of file nbtsort.c.

References BTreeTupleSetNAtts(), elog, ERROR, InvalidOffsetNumber, PageAddItem, and IndexTupleData::t_info.

Referenced by _bt_buildadd().

768 {
769  IndexTupleData trunctuple;
770 
771  if (newfirstdataitem)
772  {
773  trunctuple = *itup;
774  trunctuple.t_info = sizeof(IndexTupleData);
775  BTreeTupleSetNAtts(&trunctuple, 0, false);
776  itup = &trunctuple;
777  itemsize = sizeof(IndexTupleData);
778  }
779 
780  if (PageAddItem(page, (Item) itup, itemsize, itup_off,
781  false, false) == InvalidOffsetNumber)
782  elog(ERROR, "failed to add item to the index page");
783 }
Pointer Item
Definition: item.h:17
#define PageAddItem(page, item, size, offsetNumber, overwrite, is_heap)
Definition: bufpage.h:416
static void BTreeTupleSetNAtts(IndexTuple itup, uint16 nkeyatts, bool heaptid)
Definition: nbtree.h:463
#define ERROR
Definition: elog.h:43
struct IndexTupleData IndexTupleData
#define InvalidOffsetNumber
Definition: off.h:26
#define elog(elevel,...)
Definition: elog.h:214
unsigned short t_info
Definition: itup.h:49

◆ _bt_spool()

static void _bt_spool ( BTSpool btspool,
ItemPointer  self,
Datum values,
bool isnull 
)
static

Definition at line 528 of file nbtsort.c.

References BTSpool::index, BTSpool::sortstate, and tuplesort_putindextuplevalues().

Referenced by _bt_build_callback().

529 {
530  tuplesort_putindextuplevalues(btspool->sortstate, btspool->index,
531  self, values, isnull);
532 }
Tuplesortstate * sortstate
Definition: nbtsort.c:89
Relation index
Definition: nbtsort.c:91
void tuplesort_putindextuplevalues(Tuplesortstate *state, Relation rel, ItemPointer self, Datum *values, bool *isnull)
Definition: tuplesort.c:1651
static Datum values[MAXATTR]
Definition: bootstrap.c:167

◆ _bt_spooldestroy()

static void _bt_spooldestroy ( BTSpool btspool)
static

Definition at line 518 of file nbtsort.c.

References pfree(), BTSpool::sortstate, and tuplesort_end().

Referenced by _bt_spools_heapscan(), and btbuild().

519 {
520  tuplesort_end(btspool->sortstate);
521  pfree(btspool);
522 }
Tuplesortstate * sortstate
Definition: nbtsort.c:89
void pfree(void *pointer)
Definition: mcxt.c:1056
void tuplesort_end(Tuplesortstate *state)
Definition: tuplesort.c:1388

◆ _bt_spools_heapscan()

static double _bt_spools_heapscan ( Relation  heap,
Relation  index,
BTBuildState buildstate,
IndexInfo indexInfo 
)
static

Definition at line 368 of file nbtsort.c.

References _bt_begin_parallel(), _bt_build_callback(), _bt_parallel_heapscan(), _bt_spooldestroy(), BTBuildState::btleader, BTSpool::heap, IndexInfo::ii_BrokenHotChain, IndexInfo::ii_Concurrent, IndexInfo::ii_ParallelWorkers, IndexInfo::ii_Unique, BTSpool::index, BTSpool::isunique, BTBuildState::isunique, SortCoordinateData::isWorker, maintenance_work_mem, SortCoordinateData::nParticipants, BTLeader::nparticipanttuplesorts, palloc0(), pgstat_progress_update_multi_param(), pgstat_progress_update_param(), PROGRESS_BTREE_PHASE_INDEXBUILD_TABLESCAN, PROGRESS_CREATEIDX_SUBPHASE, PROGRESS_CREATEIDX_TUPLES_TOTAL, PROGRESS_SCAN_BLOCKS_DONE, PROGRESS_SCAN_BLOCKS_TOTAL, SortCoordinateData::sharedsort, BTLeader::sharedsort, BTLeader::sharedsort2, BTSpool::sortstate, BTBuildState::spool, BTBuildState::spool2, table_index_build_scan(), tuplesort_begin_index_btree(), val, and work_mem.

Referenced by btbuild().

370 {
371  BTSpool *btspool = (BTSpool *) palloc0(sizeof(BTSpool));
372  SortCoordinate coordinate = NULL;
373  double reltuples = 0;
374 
375  /*
376  * We size the sort area as maintenance_work_mem rather than work_mem to
377  * speed index creation. This should be OK since a single backend can't
378  * run multiple index creations in parallel (see also: notes on
379  * parallelism and maintenance_work_mem below).
380  */
381  btspool->heap = heap;
382  btspool->index = index;
383  btspool->isunique = indexInfo->ii_Unique;
384 
385  /* Save as primary spool */
386  buildstate->spool = btspool;
387 
388  /* Report table scan phase started */
391 
392  /* Attempt to launch parallel worker scan when required */
393  if (indexInfo->ii_ParallelWorkers > 0)
394  _bt_begin_parallel(buildstate, indexInfo->ii_Concurrent,
395  indexInfo->ii_ParallelWorkers);
396 
397  /*
398  * If parallel build requested and at least one worker process was
399  * successfully launched, set up coordination state
400  */
401  if (buildstate->btleader)
402  {
403  coordinate = (SortCoordinate) palloc0(sizeof(SortCoordinateData));
404  coordinate->isWorker = false;
405  coordinate->nParticipants =
406  buildstate->btleader->nparticipanttuplesorts;
407  coordinate->sharedsort = buildstate->btleader->sharedsort;
408  }
409 
410  /*
411  * Begin serial/leader tuplesort.
412  *
413  * In cases where parallelism is involved, the leader receives the same
414  * share of maintenance_work_mem as a serial sort (it is generally treated
415  * in the same way as a serial sort once we return). Parallel worker
416  * Tuplesortstates will have received only a fraction of
417  * maintenance_work_mem, though.
418  *
419  * We rely on the lifetime of the Leader Tuplesortstate almost not
420  * overlapping with any worker Tuplesortstate's lifetime. There may be
421  * some small overlap, but that's okay because we rely on leader
422  * Tuplesortstate only allocating a small, fixed amount of memory here.
423  * When its tuplesort_performsort() is called (by our caller), and
424  * significant amounts of memory are likely to be used, all workers must
425  * have already freed almost all memory held by their Tuplesortstates
426  * (they are about to go away completely, too). The overall effect is
427  * that maintenance_work_mem always represents an absolute high watermark
428  * on the amount of memory used by a CREATE INDEX operation, regardless of
429  * the use of parallelism or any other factor.
430  */
431  buildstate->spool->sortstate =
432  tuplesort_begin_index_btree(heap, index, buildstate->isunique,
433  maintenance_work_mem, coordinate,
434  false);
435 
436  /*
437  * If building a unique index, put dead tuples in a second spool to keep
438  * them out of the uniqueness check. We expect that the second spool (for
439  * dead tuples) won't get very full, so we give it only work_mem.
440  */
441  if (indexInfo->ii_Unique)
442  {
443  BTSpool *btspool2 = (BTSpool *) palloc0(sizeof(BTSpool));
444  SortCoordinate coordinate2 = NULL;
445 
446  /* Initialize secondary spool */
447  btspool2->heap = heap;
448  btspool2->index = index;
449  btspool2->isunique = false;
450  /* Save as secondary spool */
451  buildstate->spool2 = btspool2;
452 
453  if (buildstate->btleader)
454  {
455  /*
456  * Set up non-private state that is passed to
457  * tuplesort_begin_index_btree() about the basic high level
458  * coordination of a parallel sort.
459  */
460  coordinate2 = (SortCoordinate) palloc0(sizeof(SortCoordinateData));
461  coordinate2->isWorker = false;
462  coordinate2->nParticipants =
463  buildstate->btleader->nparticipanttuplesorts;
464  coordinate2->sharedsort = buildstate->btleader->sharedsort2;
465  }
466 
467  /*
468  * We expect that the second one (for dead tuples) won't get very
469  * full, so we give it only work_mem
470  */
471  buildstate->spool2->sortstate =
472  tuplesort_begin_index_btree(heap, index, false, work_mem,
473  coordinate2, false);
474  }
475 
476  /* Fill spool using either serial or parallel heap scan */
477  if (!buildstate->btleader)
478  reltuples = table_index_build_scan(heap, index, indexInfo, true, true,
479  _bt_build_callback, (void *) buildstate,
480  NULL);
481  else
482  reltuples = _bt_parallel_heapscan(buildstate,
483  &indexInfo->ii_BrokenHotChain);
484 
485  /*
486  * Set the progress target for the next phase. Reset the block number
487  * values set by table_index_build_scan
488  */
489  {
490  const int index[] = {
494  };
495  const int64 val[] = {
496  buildstate->indtuples,
497  0, 0
498  };
499 
500  pgstat_progress_update_multi_param(3, index, val);
501  }
502 
503  /* okay, all heap tuples are spooled */
504  if (buildstate->spool2 && !buildstate->havedead)
505  {
506  /* spool2 turns out to be unnecessary */
507  _bt_spooldestroy(buildstate->spool2);
508  buildstate->spool2 = NULL;
509  }
510 
511  return reltuples;
512 }
static void _bt_begin_parallel(BTBuildState *buildstate, bool isconcurrent, int request)
Definition: nbtsort.c:1453
Sharedsort * sharedsort2
Definition: nbtsort.c:195
#define PROGRESS_BTREE_PHASE_INDEXBUILD_TABLESCAN
Definition: nbtree.h:987
void pgstat_progress_update_param(int index, int64 val)
Definition: pgstat.c:3231
Sharedsort * sharedsort
Definition: nbtsort.c:194
bool havedead
Definition: nbtsort.c:210
Sharedsort * sharedsort
Definition: tuplesort.h:55
#define PROGRESS_CREATEIDX_TUPLES_TOTAL
Definition: progress.h:84
Tuplesortstate * sortstate
Definition: nbtsort.c:89
BTSpool * spool
Definition: nbtsort.c:212
Relation heap
Definition: nbtsort.c:90
static double _bt_parallel_heapscan(BTBuildState *buildstate, bool *brokenhotchain)
Definition: nbtsort.c:1700
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:1526
bool isunique
Definition: nbtsort.c:92
BTSpool * spool2
Definition: nbtsort.c:218
double indtuples
Definition: nbtsort.c:219
bool isunique
Definition: nbtsort.c:209
bool ii_BrokenHotChain
Definition: execnodes.h:175
Relation index
Definition: nbtsort.c:91
void * palloc0(Size size)
Definition: mcxt.c:980
struct SortCoordinateData * SortCoordinate
Definition: tuplesort.h:58
#define PROGRESS_SCAN_BLOCKS_DONE
Definition: progress.h:120
static void _bt_build_callback(Relation index, ItemPointer tid, Datum *values, bool *isnull, bool tupleIsAlive, void *state)
Definition: nbtsort.c:582
BTLeader * btleader
Definition: nbtsort.c:226
int work_mem
Definition: globals.c:121
int maintenance_work_mem
Definition: globals.c:122
bool ii_Unique
Definition: execnodes.h:172
int nparticipanttuplesorts
Definition: nbtsort.c:181
void pgstat_progress_update_multi_param(int nparam, const int *index, const int64 *val)
Definition: pgstat.c:3253
int ii_ParallelWorkers
Definition: execnodes.h:176
#define PROGRESS_SCAN_BLOCKS_TOTAL
Definition: progress.h:119
bool ii_Concurrent
Definition: execnodes.h:174
static void _bt_spooldestroy(BTSpool *btspool)
Definition: nbtsort.c:518
#define PROGRESS_CREATEIDX_SUBPHASE
Definition: progress.h:83
Tuplesortstate * tuplesort_begin_index_btree(Relation heapRel, Relation indexRel, bool enforceUnique, int workMem, SortCoordinate coordinate, bool randomAccess)
Definition: tuplesort.c:1047
long val
Definition: informix.c:664

◆ _bt_uppershutdown()

static void _bt_uppershutdown ( BTWriteState wstate,
BTPageState state 
)
static

Definition at line 1108 of file nbtsort.c.

References _bt_blwritepage(), _bt_buildadd(), _bt_initmetapage(), _bt_slideleft(), BTScanInsertData::allequalimage, Assert, BTP_ROOT, BTPageOpaqueData::btpo_flags, BTPageState::btps_blkno, BTPageState::btps_level, BTPageState::btps_lowkey, BTPageState::btps_next, BTPageState::btps_page, BTREE_METAPAGE, BTreeTupleGetNAtts, BTreeTupleSetDownLink(), BTWriteState::index, IndexRelationGetNumberOfKeyAttributes, BTWriteState::inskey, P_LEFTMOST, P_NONE, PageGetSpecialPointer, palloc(), and pfree().

Referenced by _bt_load().

1109 {
1110  BTPageState *s;
1111  BlockNumber rootblkno = P_NONE;
1112  uint32 rootlevel = 0;
1113  Page metapage;
1114 
1115  /*
1116  * Each iteration of this loop completes one more level of the tree.
1117  */
1118  for (s = state; s != NULL; s = s->btps_next)
1119  {
1120  BlockNumber blkno;
1121  BTPageOpaque opaque;
1122 
1123  blkno = s->btps_blkno;
1125 
1126  /*
1127  * We have to link the last page on this level to somewhere.
1128  *
1129  * If we're at the top, it's the root, so attach it to the metapage.
1130  * Otherwise, add an entry for it to its parent using its low key.
1131  * This may cause the last page of the parent level to split, but
1132  * that's not a problem -- we haven't gotten to it yet.
1133  */
1134  if (s->btps_next == NULL)
1135  {
1136  opaque->btpo_flags |= BTP_ROOT;
1137  rootblkno = blkno;
1138  rootlevel = s->btps_level;
1139  }
1140  else
1141  {
1142  Assert((BTreeTupleGetNAtts(s->btps_lowkey, wstate->index) <=
1144  BTreeTupleGetNAtts(s->btps_lowkey, wstate->index) > 0) ||
1145  P_LEFTMOST(opaque));
1146  Assert(BTreeTupleGetNAtts(s->btps_lowkey, wstate->index) == 0 ||
1147  !P_LEFTMOST(opaque));
1149  _bt_buildadd(wstate, s->btps_next, s->btps_lowkey, 0);
1150  pfree(s->btps_lowkey);
1151  s->btps_lowkey = NULL;
1152  }
1153 
1154  /*
1155  * This is the rightmost page, so the ItemId array needs to be slid
1156  * back one slot. Then we can dump out the page.
1157  */
1159  _bt_blwritepage(wstate, s->btps_page, s->btps_blkno);
1160  s->btps_page = NULL; /* writepage freed the workspace */
1161  }
1162 
1163  /*
1164  * As the last step in the process, construct the metapage and make it
1165  * point to the new root (unless we had no data at all, in which case it's
1166  * set to point to "P_NONE"). This changes the index to the "valid" state
1167  * by filling in a valid magic number in the metapage.
1168  */
1169  metapage = (Page) palloc(BLCKSZ);
1170  _bt_initmetapage(metapage, rootblkno, rootlevel,
1171  wstate->inskey->allequalimage);
1172  _bt_blwritepage(wstate, metapage, BTREE_METAPAGE);
1173 }
#define BTP_ROOT
Definition: nbtree.h:73
#define P_NONE
Definition: nbtree.h:206
bool allequalimage
Definition: nbtree.h:660
void _bt_initmetapage(Page page, BlockNumber rootbknum, uint32 level, bool allequalimage)
Definition: nbtpage.c:60
uint32 BlockNumber
Definition: block.h:31
BlockNumber btps_blkno
Definition: nbtsort.c:236
#define BTreeTupleGetNAtts(itup, rel)
Definition: nbtree.h:445
static void _bt_blwritepage(BTWriteState *wstate, Page page, BlockNumber blkno)
Definition: nbtsort.c:638
BTPageOpaqueData * BTPageOpaque
Definition: nbtree.h:69
Page btps_page
Definition: nbtsort.c:235
void pfree(void *pointer)
Definition: mcxt.c:1056
#define P_LEFTMOST(opaque)
Definition: nbtree.h:212
unsigned int uint32
Definition: c.h:367
static void BTreeTupleSetDownLink(IndexTuple pivot, BlockNumber blkno)
Definition: nbtree.h:430
#define IndexRelationGetNumberOfKeyAttributes(relation)
Definition: rel.h:475
#define BTREE_METAPAGE
Definition: nbtree.h:141
Relation index
Definition: nbtsort.c:251
uint32 btps_level
Definition: nbtsort.c:240
struct BTPageState * btps_next
Definition: nbtsort.c:242
BTScanInsert inskey
Definition: nbtsort.c:252
IndexTuple btps_lowkey
Definition: nbtsort.c:237
static void _bt_buildadd(BTWriteState *wstate, BTPageState *state, IndexTuple itup, Size truncextra)
Definition: nbtsort.c:833
#define Assert(condition)
Definition: c.h:738
#define PageGetSpecialPointer(page)
Definition: bufpage.h:326
static void _bt_slideleft(Page page)
Definition: nbtsort.c:730
void * palloc(Size size)
Definition: mcxt.c:949
uint16 btpo_flags
Definition: nbtree.h:65
Pointer Page
Definition: bufpage.h:78

◆ btbuild()

IndexBuildResult* btbuild ( Relation  heap,
Relation  index,
IndexInfo indexInfo 
)

Definition at line 299 of file nbtsort.c.

References _bt_end_parallel(), _bt_leafbuild(), _bt_spooldestroy(), _bt_spools_heapscan(), BTBuildState::btleader, elog, ERROR, BTBuildState::havedead, BTSpool::heap, BTBuildState::heap, IndexBuildResult::heap_tuples, IndexInfo::ii_Unique, IndexBuildResult::index_tuples, BTBuildState::indtuples, BTBuildState::isunique, log_btree_build_stats, palloc(), RelationGetNumberOfBlocks, RelationGetRelationName, ResetUsage(), ShowUsage(), BTBuildState::spool, and BTBuildState::spool2.

Referenced by bthandler().

300 {
301  IndexBuildResult *result;
302  BTBuildState buildstate;
303  double reltuples;
304 
305 #ifdef BTREE_BUILD_STATS
307  ResetUsage();
308 #endif /* BTREE_BUILD_STATS */
309 
310  buildstate.isunique = indexInfo->ii_Unique;
311  buildstate.havedead = false;
312  buildstate.heap = heap;
313  buildstate.spool = NULL;
314  buildstate.spool2 = NULL;
315  buildstate.indtuples = 0;
316  buildstate.btleader = NULL;
317 
318  /*
319  * We expect to be called exactly once for any index relation. If that's
320  * not the case, big trouble's what we have.
321  */
322  if (RelationGetNumberOfBlocks(index) != 0)
323  elog(ERROR, "index \"%s\" already contains data",
324  RelationGetRelationName(index));
325 
326  reltuples = _bt_spools_heapscan(heap, index, &buildstate, indexInfo);
327 
328  /*
329  * Finish the build by (1) completing the sort of the spool file, (2)
330  * inserting the sorted tuples into btree pages and (3) building the upper
331  * levels. Finally, it may also be necessary to end use of parallelism.
332  */
333  _bt_leafbuild(buildstate.spool, buildstate.spool2);
334  _bt_spooldestroy(buildstate.spool);
335  if (buildstate.spool2)
336  _bt_spooldestroy(buildstate.spool2);
337  if (buildstate.btleader)
338  _bt_end_parallel(buildstate.btleader);
339 
340  result = (IndexBuildResult *) palloc(sizeof(IndexBuildResult));
341 
342  result->heap_tuples = reltuples;
343  result->index_tuples = buildstate.indtuples;
344 
345 #ifdef BTREE_BUILD_STATS
347  {
348  ShowUsage("BTREE BUILD STATS");
349  ResetUsage();
350  }
351 #endif /* BTREE_BUILD_STATS */
352 
353  return result;
354 }
Relation heap
Definition: nbtsort.c:211
void ShowUsage(const char *title)
Definition: postgres.c:4618
bool havedead
Definition: nbtsort.c:210
static void _bt_end_parallel(BTLeader *btleader)
Definition: nbtsort.c:1654
static void _bt_leafbuild(BTSpool *btspool, BTSpool *btspool2)
Definition: nbtsort.c:539
BTSpool * spool
Definition: nbtsort.c:212
void ResetUsage(void)
Definition: postgres.c:4611
#define ERROR
Definition: elog.h:43
BTSpool * spool2
Definition: nbtsort.c:218
double indtuples
Definition: nbtsort.c:219
bool isunique
Definition: nbtsort.c:209
#define RelationGetRelationName(relation)
Definition: rel.h:490
static double _bt_spools_heapscan(Relation heap, Relation index, BTBuildState *buildstate, IndexInfo *indexInfo)
Definition: nbtsort.c:368
bool log_btree_build_stats
Definition: guc.c:520
BTLeader * btleader
Definition: nbtsort.c:226
#define RelationGetNumberOfBlocks(reln)
Definition: bufmgr.h:211
bool ii_Unique
Definition: execnodes.h:172
static void _bt_spooldestroy(BTSpool *btspool)
Definition: nbtsort.c:518
void * palloc(Size size)
Definition: mcxt.c:949
#define elog(elevel,...)
Definition: elog.h:214
double index_tuples
Definition: genam.h:33
double heap_tuples
Definition: genam.h:32